{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "How far does an energy-preserving rotation lag behind?",
   "lead": "Integrate uniform circular motion by the implicit midpoint rule. The points stay exactly on the energy circle in exact arithmetic. Derive the angle advanced at each step and measure the accumulated timing error.",
   "unit_slug": "cayley-rotation-and-phase-lag"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4b8cbe2fe11c",
   "metadata": {},
   "source": [
    "# How far does an energy-preserving rotation lag behind?\n",
    "\n",
    "Integrate uniform circular motion by the implicit midpoint rule. The points stay exactly on the energy circle in exact arithmetic. Derive the angle advanced at each step and measure the accumulated timing error."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "95c85c9e7851",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## From a midpoint balance to a rotation matrix\n",
    "\n",
    "Write a two-component oscillator as $v'=\\omega Jv$, where $J$ sends $(x,y)$ to $(-y,x)$. Choosing scaled coordinates makes both components comparable; for a mechanical oscillator one may take displacement and a suitably scaled speed. The generator is skew-symmetric, so $d(v^Tv)/dt=\\omega v^T(J^T+J)v=0$. The exact motion has angular advance $h\\omega$ over an interval $h$.\n",
    "\n",
    "Midpoint approximates the velocity at the midpoint of the segment joining the old and new states. This yields $(I-aJ)v_{n+1}=(I+aJ)v_n$ with $a=h\\omega/2$. Since $J^2=-I$, multiplication by $I+aJ$ eliminates the inverse and gives\n",
    "\n",
    "$$R_h=(I-aJ)^{-1}(I+aJ)=\\frac{(1-a^2)I+2aJ}{1+a^2}.$$\n",
    "\n",
    "The coefficients of $I$ and $J$ have squares summing to one. They are the cosine and sine of the angle $\\theta_h=2\\arctan a$. Thus every update preserves the squared radius. The angle differs from the exact $h\\omega$. Expanding the arctangent gives\n",
    "\n",
    "$$\n",
    "\\theta_h=h\\omega-(h\\omega)^3/12+O((h\\omega)^5).\n",
    "$$\n",
    "\n",
    "Over a fixed duration $T=nh$, the leading accumulated angle error is $-T\\omega^3h^2/12$. This phase lag is especially visible after many periods even when a graph of energy looks perfect.\n",
    "\n",
    "For comparison, explicit Euler takes the tangent line to its end point. Its amplification is $\\sqrt{1+(h\\omega)^2}$. Studying both amplitude and timing identifies different defects of the two updates."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79692cca01f6",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Put a clock on the unit circle\n",
    "\n",
    "Let $\\omega=2$ rad/s, $h=0.5$ s and $v_0=(1,0)$. The half-step parameter is 0.5. The rotation sends the first point to $(0.6,0.8)$ instead of the exact $(\\cos1,\\sin1)\\approx(0.5403,0.8415)$. Both radii are one. The angular deficit is $1-2\\arctan(0.5)\\approx0.072705$ rad per update. After ten updates, the numerical clock is behind by 0.72705 rad or about 0.364 s of physical time.\n",
    "\n",
    "With $h=0.25$ s over the same five seconds the deficit is $10-40\\arctan(0.25)\\approx0.20085$ rad. Its ratio to the coarse-step error is close to one quarter. In the notebook the rotation is built by a linear solve and its angle is measured from a dot product and an oriented area. These are independent ways to check the hand formula. Counting full turns requires retaining unwrapped increments; a final point alone cannot identify the number of completed turns."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fbf3e10fb9d8",
   "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": "3fd788729b7b",
   "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": "3f403a034cdd",
   "metadata": {},
   "source": [
    "omega = 2.0\n",
    "step_seconds = 0.5\n",
    "steps = 10"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "5d01b04add0e",
   "metadata": {},
   "source": [
    "assert step_seconds > 0 and 2 <= steps <= 2000 and np.isfinite(omega)\n",
    "J = np.array([[0.,-1.],[1.,0.]])\n",
    "I = np.eye(2)\n",
    "initial = np.array([1.,0.])\n",
    "\n",
    "def integrate(h,n):\n",
    "    a = omega*h/2\n",
    "    rotation = np.linalg.solve(I-a*J,I+a*J)\n",
    "    states = np.empty((n+1,2)); states[0] = initial\n",
    "    for k in range(n): states[k+1] = rotation @ states[k]\n",
    "    left,right = states[:-1],states[1:]\n",
    "    areas = left[:,0]*right[:,1] - left[:,1]*right[:,0]\n",
    "    dots = np.sum(left*right,axis=1)\n",
    "    angles = np.r_[0.,np.cumsum(np.arctan2(areas,dots))]\n",
    "    time = h*np.arange(n+1)\n",
    "    assert np.allclose(np.sum(states**2,axis=1),1)\n",
    "    assert np.allclose(angles,2*np.arctan(a)*np.arange(n+1))\n",
    "    return time,states,angles-time*omega\n",
    "\n",
    "time,path,lag = integrate(step_seconds,steps)\n",
    "fine_time,fine,fine_lag = integrate(step_seconds/2,steps*2)\n",
    "print(f\"After {time[-1]:.3f} s: signed phase errors {lag[-1]:.7f} and {fine_lag[-1]:.7f} rad\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "6d4881c315a3",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "ordinary-differential-equations-ordinary-differential-equations-methods-1.png",
      "alt": "The exact arc and midpoint lie on the unit circle, while one explicit tangent step ends outside it.",
      "caption": "The three markers correspond to one physical time step. The midpoint result lies on the circle at its own numerical angle."
     }
    }
   },
   "source": [
    "fig, ax = axes(\"Scaled first component\", \"Scaled second component\")\n",
    "angle = np.linspace(0,2*np.pi,301)\n",
    "ax.plot(np.cos(angle),np.sin(angle),color=\"#aaa\",label=\"Energy circle\")\n",
    "angle = np.linspace(0,omega*step_seconds,101)\n",
    "ax.plot(np.cos(angle),np.sin(angle),color=blue,lw=2,label=\"Exact arc\")\n",
    "euler = initial + omega*step_seconds*J@initial\n",
    "ax.plot([1,euler[0]],[0,euler[1]],ls=\":\",color=orange)\n",
    "for point,marker,color,label in [(path[1],\"o\",teal,\"Midpoint\"),(euler,\"s\",orange,\"Euler\"),\n",
    "                                  (np.array([np.cos(angle[-1]),np.sin(angle[-1])]),\"x\",blue,\"Exact\")]:\n",
    "    ax.scatter(*point,marker=marker,c=color,s=55,label=label,zorder=3)\n",
    "ax.set_aspect(\"equal\", adjustable=\"datalim\")\n",
    "ax.legend(fontsize=8)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "519dfc7f5914",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The three markers correspond to one physical time step. The midpoint result lies on the circle at its own numerical angle."
   ]
  },
  {
   "cell_type": "code",
   "id": "f6ea2b92fa83",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "ordinary-differential-equations-ordinary-differential-equations-methods-2.png",
      "alt": "The measured unwrapped phase error grows linearly with elapsed time and decreases on halving the step.",
      "caption": "The full and half steps cover the same physical interval. The dotted trace is the leading asymptotic error for the coarse step."
     }
    }
   },
   "source": [
    "fig, ax = axes(\"Elapsed time (s)\", \"Numerical minus exact phase (rad)\")\n",
    "ax.plot(time,lag,color=orange,marker=\"o\",ms=3,label=\"Full step\")\n",
    "ax.plot(fine_time,fine_lag,color=teal,label=\"Half step\")\n",
    "ax.plot(time,-time*omega**3*step_seconds**2/12,color=blue,ls=\":\",label=\"Leading full-step prediction\")\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "0af6eea5f536",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The full and half steps cover the same physical interval. The dotted trace is the leading asymptotic error for the coarse step."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b3c827e0d993",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · reverse the sign of time\n",
    "\n",
    "Show why a forward midpoint update followed by one equal backward update returns to the starting state. Does forward Euler have the same property here?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb0decb75f60",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "Replacing $a$ by $-a$ interchanges the two factors in the Cayley formula, so $R_{-h}=R_h^{-1}$. Their product is the identity. For explicit Euler the product is $(I-h\\omega J)(I+h\\omega J)=(1+(h\\omega)^2)I$. The reversal increases every radius when the angular speed and the step are nonzero."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b93c65591cdf",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · set a phase budget\n",
    "\n",
    "For $\\omega=2$ rad/s, approximate a time step that keeps the accumulated phase lag below 0.02 rad over six seconds. Give an exact way to check the choice."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25cd24ad16ed",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "The leading magnitude is $T\\omega^3h^2/12=4h^2$. Equating this to 0.02 gives about 0.0707 s. Choosing 90 equal steps over six seconds gives $h=1/15$ s. The exact lag is $12-180\\arctan(1/15)$ rad, about 0.0177. The exact check is useful when the step is large enough that the cubic series term has limited accuracy."
   ]
  }
 ]
}
