{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ordinary-dif-00",
   "metadata": {},
   "source": [
    "# Integrating a bead constrained to a circular guide\n",
    "Observe three independent diagnostics: radius, tangency and phase. A force-free bead in a circular guide has an exact orbit with which to compare both a constrained step and a simple normalisation. NumPy and Matplotlib are sufficient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ordinary-dif-01",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "omega = 1.6                      # s^-1, unit radius in metres\n",
    "h = .25                          # seconds\n",
    "steps = 80\n",
    "assert .1 <= omega <= 3 and .01 <= h and h*omega < .93 and 8 <= steps <= 300\n",
    "\n",
    "def constrained_step(q, v, dt):\n",
    "    transverse = dt*v\n",
    "    # The inward impulse is represented by a multiple of the old unit normal q.\n",
    "    radial = np.sqrt(1-np.dot(transverse,transverse))\n",
    "    new_q = radial*q + transverse\n",
    "    v_half = (new_q-q)/dt\n",
    "    new_v = v_half - np.dot(v_half,new_q)*new_q\n",
    "    return new_q, new_v\n",
    "\n",
    "def normalised_drift(q, v, dt):\n",
    "    new_q = q+dt*v\n",
    "    new_q = new_q/np.linalg.norm(new_q)\n",
    "    new_v = v-np.dot(new_q,v)*new_q\n",
    "    return new_q,new_v\n",
    "\n",
    "def trajectory(advance, dt, count):\n",
    "    q, v = np.array([1.,0.]), np.array([0.,omega])\n",
    "    positions, velocities = [q.copy()], [v.copy()]\n",
    "    for _ in range(count):\n",
    "        q,v = advance(q,v,dt)\n",
    "        positions.append(q.copy())\n",
    "        velocities.append(v.copy())\n",
    "    return np.array(positions),np.array(velocities)\n",
    "\n",
    "q, v = trajectory(constrained_step,h,steps)\n",
    "qn, vn = trajectory(normalised_drift,h,steps)\n",
    "time = np.arange(steps+1)*h\n",
    "phase = np.unwrap(np.arctan2(q[:,1],q[:,0]))\n",
    "ang = q[:,0]*v[:,1]-q[:,1]*v[:,0]\n",
    "print(\"Largest position/tangency defects:\",np.max(abs(np.linalg.norm(q,axis=1)-1)), np.max(abs((q*v).sum(axis=1))))\n",
    "print(f\"Final phase lead {phase[-1]-omega*time[-1]:.6f} rad; angular momentum change {ang[-1]-ang[0]:.3e}\")\n",
    "assert np.max(abs(ang-omega)) < 2e-10 and np.max(abs(phase-np.arange(steps+1)*np.arcsin(h*omega))) < 1e-9"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ordinary-dif-02",
   "metadata": {},
   "source": [
    "## Read both the shape and the clock\n",
    "The left panel samples the first part of the trajectory. On the right, unwrapped angles are compared at the same physical times. Halve the step and double the number of steps to retain the final time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ordinary-dif-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, (path, drift) = plt.subplots(1,2,figsize=(10,4),layout=\"constrained\")\n",
    "theta = np.linspace(0,2*np.pi,241)\n",
    "path.plot(np.cos(theta),np.sin(theta),color=\"grey\",lw=1,label=\"exact guide\")\n",
    "show = min(steps+1, max(4, int(2*np.pi/(omega*h))+1))\n",
    "path.plot(q[:show,0],q[:show,1],\"o-\",ms=3,color=\"#145c71\",label=\"RATTLE nodes\")\n",
    "path.plot(qn[:show,0],qn[:show,1],\".--\",ms=4,color=\"#b94626\",label=\"normalised drift\")\n",
    "path.set(aspect=\"equal\",xlabel=\"x (m)\",ylabel=\"y (m)\",title=\"Both sets of points lie on the guide\")\n",
    "path.legend(fontsize=8)\n",
    "drift.plot(time, phase-omega*time,color=\"#145c71\",label=\"RATTLE\")\n",
    "drift.plot(time,np.unwrap(np.arctan2(qn[:,1],qn[:,0]))-omega*time,\"--\",color=\"#b94626\",label=\"normalised drift\")\n",
    "drift.set(xlabel=\"Time (s)\",ylabel=\"Phase error (rad)\",title=\"Constraint satisfaction and timing\")\n",
    "drift.legend()\n",
    "for ax in (path,drift): ax.grid(alpha=.2)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ordinary-dif-04",
   "metadata": {},
   "source": [
    "## Compare a different local solver\n",
    "An installed OneSimulation environment also lets you integrate the continuous Cartesian acceleration with classical RK4. This alternative implements the centripetal force directly and has no algebraic projection. Compare the end radius with the constrained run at the same step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ordinary-dif-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.time import ClassicalRungeKutta4TimeIntegrator\n",
    "except ImportError:\n",
    "    print(\"The constrained and exact references above are complete. OneSimulation comparison is available locally.\")\n",
    "else:\n",
    "    method = ClassicalRungeKutta4TimeIntegrator()\n",
    "    def rhs(z, clock):\n",
    "        pos, vel = np.asarray(z[:2]), np.asarray(z[2:])\n",
    "        acc = -(vel@vel)/(pos@pos)*pos\n",
    "        return (*vel, *acc)\n",
    "    state = (1.,0.,0.,omega)\n",
    "    for n in range(steps):\n",
    "        state = method.advance(state,rhs,h,time=n*h)\n",
    "    print(\"OneSimulation RK4 end-radius error (m):\",np.linalg.norm(state[:2])-1)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
