{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Where does a complex Newton step take its starting point?",
   "lead": "A single cubic has three equally simple roots. Derive the iteration, colour starting values by destination and use a separate convergence history to distinguish a bad first step from slow local convergence.",
   "unit_slug": "newton-basins-in-the-complex-plane"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fbb0f385666c",
   "metadata": {},
   "source": [
    "# Where does a complex Newton step take its starting point?\n",
    "\n",
    "A single cubic has three equally simple roots. Derive the iteration, colour starting values by destination and use a separate convergence history to distinguish a bad first step from slow local convergence."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebe142383a83",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Continue the tangent step into the complex plane\n",
    "\n",
    "A holomorphic function has a complex linear approximation $f(z+s)\\approx f(z)+f'(z)s$. Requiring this approximation to vanish gives $s=-f(z)/f'(z)$ wherever the derivative is nonzero. For $f(z)=z^3-1$, the resulting map is\n",
    "\n",
    "$$N(z)=\\frac{2z}{3}+\\frac{1}{3z^2}.$$\n",
    "\n",
    "The second term is a pole at zero. Starting at a small positive number sends the next iterate far to the right, after which large iterates return approximately by multiplication by 2/3. At a root $r$, write $z=r+e$ and substitute $r^3=1$. Exact cancellation of the linear error gives\n",
    "\n",
    "$$\n",
    "N(r+e)-r=e^2(3r+2e)/[3(r+e)^2].\n",
    "$$\n",
    "\n",
    "Sufficiently near $r$, the new error is about $e^2/r$. This argument predicts the speed after entry into a local neighbourhood. It has no information about which root a distant initial point will reach.\n",
    "\n",
    "Let $s=\\exp(2\\pi i/3)$. Since $s^3=1$, symmetry gives\n",
    "\n",
    "$$\n",
    "N(sz)=sN(z).\n",
    "$$\n",
    "\n",
    "The entire sequence, including its root, rotates with the start. Conjugate starting points likewise produce conjugate histories because the coefficients are real. These are two independent checks for numerical basin maps. We classify a pixel only once its residual falls below a declared tolerance. A starting pole and a trajectory that exhausts its iteration allowance can both appear unclassified. Increasing the allowance separates these cases for many pixels."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "815ff7411439",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Follow a detour before quadratic convergence\n",
    "\n",
    "From $z_0=1/2$ the first iterate is $1/3+4/3=5/3$. The next is $10/9+3/25=277/225\\approx1.23111$. The error initially rises from 0.5 to 0.667. By contrast, starting at 0.1 gives $z_1=33.4$. The subsequent near-geometric return explains the long shoulder in the second figure. Both starts ultimately approach the real root.\n",
    "\n",
    "Move the orange sample by writing a complex number such as $-0.5+0.85i$ in Python as `-0.5+0.85j`. The sample mark and the residual trace follow the same new starting point. The intricate boundaries in the image are computed from independent point trajectories. Refining the grid examines finer samples of those boundaries; the speed on the residual graph belongs to one particular start."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54511b38a64e",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "9544c5a451f2",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "4f4461bbad4a",
   "metadata": {},
   "source": [
    "sample_start = 0.1 + 0j\n",
    "grid_size = 201\n",
    "max_steps = 38\n",
    "tolerance = 1.e-8"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "29f3048f329f",
   "metadata": {},
   "source": [
    "assert 31 <= grid_size <= 501 and 1 <= max_steps <= 180 and 0 < tolerance < 0.1\n",
    "roots = np.exp(2j*np.pi*np.arange(3)/3)\n",
    "def step(z):\n",
    "    return (2*z + 1/(z*z))/3\n",
    "\n",
    "def classify(initial):\n",
    "    z = np.asarray(initial, dtype=complex).copy().reshape(-1)\n",
    "    labels = np.full(z.size, -1, dtype=int)\n",
    "    active = np.ones(z.size, dtype=bool)\n",
    "    for _ in range(max_steps+1):\n",
    "        with np.errstate(over=\"ignore\",invalid=\"ignore\",divide=\"ignore\"):\n",
    "            residual = np.abs(z**3-1)\n",
    "            done = active & (residual < tolerance)\n",
    "            labels[done] = np.argmin(np.abs(z[done,None]-roots), axis=1)\n",
    "            active &= ~done & np.isfinite(z) & (np.abs(z) > 1.e-120)\n",
    "            z[active] = step(z[active])\n",
    "    return labels.reshape(np.shape(initial))\n",
    "\n",
    "points = np.linspace(-1.6,1.6,grid_size)\n",
    "X,Y = np.meshgrid(points,points)\n",
    "basin = classify(X+1j*Y)\n",
    "assert np.array_equal(classify(roots), [0,1,2]) and classify(0j) == -1\n",
    "check = 0.75 + 0.1j\n",
    "assert np.isclose(step(roots[1]*check),roots[1]*step(check))\n",
    "print(\"Basin counts [unclassified, real root, upper root, lower root]:\",\n",
    "      np.bincount((basin+1).ravel(),minlength=4))"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "7fcfddadb6d2",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "nonlinear-equations-nonlinear-equations-methods-1.png",
      "alt": "Three root basins weave together near their boundaries, and a marker identifies the selected starting point.",
      "caption": "Each grid point starts an independent cubic iteration. Dark grey means the residual criterion was never met within the allowed steps, including the pole at zero."
     }
    }
   },
   "source": [
    "from matplotlib.colors import ListedColormap\n",
    "from matplotlib.patches import Patch\n",
    "fig, ax = axes(\"Real part of initial value\", \"Imaginary part of initial value\")\n",
    "palette = [\"#353943\",\"#add8c9\",\"#85aed5\",\"#e9a98e\"]\n",
    "ax.imshow(basin+1, origin=\"lower\", extent=[-1.6,1.6,-1.6,1.6],\n",
    "          cmap=ListedColormap(palette),vmin=0,vmax=3,interpolation=\"nearest\")\n",
    "ax.scatter(roots.real,roots.imag,marker=\"*\",c=\"black\",s=90,label=\"Roots\")\n",
    "ax.scatter(sample_start.real,sample_start.imag,marker=\"x\",c=\"black\",s=50,label=\"Sample\")\n",
    "handles = [Patch(color=c,label=s) for c,s in zip(palette,[\"Unclassified\",\"+1\",\"Upper root\",\"Lower root\"])]\n",
    "ax.legend(handles=handles+ax.get_legend_handles_labels()[0],loc=\"upper left\",fontsize=7,ncol=2)\n",
    "ax.grid(False)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "777638c3fc4e",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Each grid point starts an independent cubic iteration. Dark grey means the residual criterion was never met within the allowed steps, including the pole at zero."
   ]
  },
  {
   "cell_type": "code",
   "id": "90c55da0a8db",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "nonlinear-equations-nonlinear-equations-methods-2.png",
      "alt": "Residual histories for different initial points show the near-pole excursion and rapid final convergence.",
      "caption": "The dashed line is the actual residual tolerance. A small initial magnitude can produce a large first residual followed by a long return."
     }
    }
   },
   "source": [
    "fig, ax = axes(\"Newton step\", \"Cubic residual magnitude\")\n",
    "for z0,col in zip([0.5+0j,sample_start,-.5+.8j],[teal,orange,blue]):\n",
    "    z=complex(z0); history=[]\n",
    "    for _ in range(max_steps+1):\n",
    "        if abs(z)>1.e95: break\n",
    "        value=abs(z**3-1); history.append(max(value,1.e-16))\n",
    "        if value<tolerance or abs(z)<1.e-120: break\n",
    "        z=step(z)\n",
    "    ax.semilogy(range(len(history)),history,marker=\"o\",ms=3,color=col,label=f\"Start {z0:.3g}\")\n",
    "ax.axhline(tolerance,color=\"#484848\",ls=\"--\",label=\"Stopping tolerance\")\n",
    "ax.legend(fontsize=8)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "bf8afb56d0dd",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The dashed line is the actual residual tolerance. A small initial magnitude can produce a large first residual followed by a long return."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86455cc9c9bf",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · obtain two basin colours for free\n",
    "\n",
    "Suppose $0.75+0.10i$ reaches the real root in five updates. What are the destinations and update counts after multiplying the start by either non-real cube root of one?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26aad89786f8",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "Write the original iterates as $z_k$. By induction $N^k(sz_0)=sz_k$ and $N^k(s^2z_0)=s^2z_k$. The destinations are $s$ and $s^2$. Since $(sz_k)^3-1=z_k^3-1$, every residual and hence the first crossing of the same threshold is unchanged. Differences in a finely sampled plot may arise because the rotated point falls between pixels."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c5eec757a5c",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · quantify the final two digits\n",
    "\n",
    "For a real iterate $z=1.01$, estimate the next error by the quadratic approximation and calculate its exact value using the error formula."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed0bb1f6e64e",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "The leading term gives $0.01^2=10^{-4}$. The exact error is $10^{-4}(3.02)/(3\\times1.01^2)\\approx9.8683\\times10^{-5}$. The difference is of the next order in the initial error. The small residual after this update is about three times the error because $f'(1)=3$."
   ]
  }
 ]
}
