{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Dzhanibekov effect: the flipping T-handle\n",
    "\n",
    "In 1985 the cosmonaut Vladimir Dzhanibekov noticed that a wing nut spinning off its bolt in\n",
    "weightlessness turns over every few seconds, keeps spinning and turns back. The effect is the\n",
    "**intermediate axis theorem**: a rigid body with principal moments of inertia $I_1<I_2<I_3$\n",
    "spins stably about the axes of the smallest and the largest moment, but not about the\n",
    "intermediate one. Without torques the angular velocity $\\boldsymbol\\omega$ in the body frame\n",
    "obeys Euler's equations\n",
    "\n",
    "$$I_1\\dot\\omega_1=(I_2-I_3)\\,\\omega_2\\omega_3,\\qquad I_2\\dot\\omega_2=(I_3-I_1)\\,\\omega_3\\omega_1,\\qquad\n",
    "  I_3\\dot\\omega_3=(I_1-I_2)\\,\\omega_1\\omega_2 ,$$\n",
    "\n",
    "which conserve the kinetic energy $E=\\tfrac12\\sum I_i\\omega_i^2$ and the magnitude of the\n",
    "angular momentum $M=|\\,(I_1\\omega_1,I_2\\omega_2,I_3\\omega_3)\\,|$.\n",
    "\n",
    "The body is a T-handle of aluminium bar from the CAD file `dzhanibekov_t_handle.step`, written\n",
    "by `dzhanibekov_t_handle_geometry.py` with the CAD objects of OneSimulation. Its principal axes\n",
    "are the coordinate axes: $x$ along the crossbar (smallest moment), $y$ along the stem\n",
    "(intermediate) and $z$ normal to the plane of the T (largest).\n",
    "\n",
    "**Reference.** L. D. Landau and E. M. Lifshitz, *Mechanics*, 3rd ed., Pergamon (1976), §37: for\n",
    "$M^2>2EI_2$ the components are Jacobi elliptic functions of\n",
    "$\\tau=t\\sqrt{(I_3-I_2)(M^2-2EI_1)/(I_1I_2I_3)}$ with the modulus\n",
    "$k^2=(I_2-I_1)(2EI_3-M^2)/\\big((I_3-I_2)(M^2-2EI_1)\\big)$; $\\omega_2\\propto\\operatorname{sn}\\tau$\n",
    "changes sign twice in the period\n",
    "\n",
    "$$T=4K(k)\\sqrt{\\frac{I_1I_2I_3}{(I_3-I_2)(M^2-2EI_1)}} .$$"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.exchange import load\n",
    "from onesim.cad.geometry import LumpedDomain\n",
    "from onesim.meshing import LumpedMesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.time import ClassicalRungeKutta4\n",
    "from onesim.physics.multibody import EulerTop\n",
    "from onesim.results.sampling import crossing_times\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.special import ellipk\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Geometry and inertia\n",
    "\n",
    "`load` returns the solid; its `inertia` is the inertia tensor about the centre of mass per unit\n",
    "density. Multiplied by the density of aluminium it gives the principal moments."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "handle = load(\"dzhanibekov_t_handle.step\")\n",
    "density = 2700.0\n",
    "inertia = tuple(np.diag(handle.inertia) * density)\n",
    "print(\n",
    "    f\"mass {1e3 * density * handle.volumes[0].measure:.1f} g, centre of mass ({', '.join(f'{1e3 * c:.2f}' for c in handle.center_of_mass)}) mm\"\n",
    ")\n",
    "print(\n",
    "    \"principal moments of inertia [kg mm²]: \"\n",
    "    + \", \".join(f\"I_{axis} = {1e6 * value:.3f}\" for axis, value in zip(\"xyz\", inertia))\n",
    ")\n",
    "\n",
    "view = plots.Camera(elevation=30, azimuth=-55)\n",
    "fig = plots.figure(1, 2, size=(14, 5.5))\n",
    "plots.geometry(\n",
    "    handle,\n",
    "    selection={\"crossbar\": handle.boundaries.crossbar, \"stem\": handle.boundaries.stem},\n",
    "    labels=False,\n",
    "    camera=view,\n",
    "    title=\"T-handle with its two bars\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.render(handle, camera=view, title=\"Rendered part\", ax=fig[1])\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`EulerTop` holds Euler's equations for the three body-frame components of the angular velocity.\n",
    "The handle is spun at 5 revolutions per second about each principal axis in turn, with a small\n",
    "disturbance of 1 % of the spin on the component about the axis of the largest moment (about the\n",
    "smallest axis for the spin about $z$). Classical Runge-Kutta with a step of 1 ms integrates 3 s."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "spin, disturbance = 2 * np.pi * 5.0, 0.01\n",
    "domain = LumpedDomain()\n",
    "top = EulerTop(domain=domain.system, inertia=inertia, torque=(0.0, 0.0, 0.0))\n",
    "starts = {\n",
    "    \"x (smallest)\": (spin, 0.0, disturbance * spin),\n",
    "    \"y (intermediate)\": (0.0, spin, disturbance * spin),\n",
    "    \"z (largest)\": (disturbance * spin, 0.0, spin),\n",
    "}\n",
    "numerics = Numerics(spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4())\n",
    "runs = {\n",
    "    axis: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Spin about {axis}\",\n",
    "            geometry=domain,\n",
    "            physics=(top,),\n",
    "            initial_conditions=tuple(\n",
    "                InitialValue(top.angular_velocity(c), w) for c, w in zip(\"xyz\", omega)\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(domain),\n",
    "        numerics=numerics,\n",
    "    ).run(start_time=0.0, end_time=3.0, time_step=1e-3)\n",
    "    for axis, omega in starts.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Energy and angular momentum over the whole run, the largest excursion of the two disturbed\n",
    "components, and the flip period of the intermediate-axis spin from the sign changes of\n",
    "$\\omega_y$ against the elliptic-function period."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "omega = {\n",
    "    axis: np.array([run.field(top.angular_velocity(c)).time_series()[1] for c in \"xyz\"])\n",
    "    for axis, run in runs.items()\n",
    "}\n",
    "times = runs[\"y (intermediate)\"].field(top.angular_velocity(\"y\")).time_series()[0]\n",
    "energy, momentum = (\n",
    "    0.5 * np.dot(inertia, np.square(starts[\"y (intermediate)\"])),\n",
    "    np.linalg.norm(np.multiply(inertia, starts[\"y (intermediate)\"])),\n",
    ")\n",
    "i1, i2, i3 = inertia\n",
    "landau = (\n",
    "    4\n",
    "    * ellipk(\n",
    "        (i2 - i1)\n",
    "        * (2 * energy * i3 - momentum**2)\n",
    "        / ((i3 - i2) * (momentum**2 - 2 * energy * i1))\n",
    "    )\n",
    "    * np.sqrt(i1 * i2 * i3 / ((i3 - i2) * (momentum**2 - 2 * energy * i1)))\n",
    ")\n",
    "flips = crossing_times(times, omega[\"y (intermediate)\"][1], 0.0, direction=\"both\")\n",
    "\n",
    "for axis, run in runs.items():\n",
    "    e, m = (\n",
    "        run.field(top.energy).time_series()[1],\n",
    "        run.field(top.momentum_norm).time_series()[1],\n",
    "    )\n",
    "    k = \"xyz\".index(axis[0])\n",
    "    print(\n",
    "        f\"spin about {axis:17s} relative drift: energy {np.ptp(e) / e[0]:.1e}, angular momentum {np.ptp(m) / m[0]:.1e}; \"\n",
    "        f\"spin component from {omega[axis][k].min() / spin:+.3f} to {omega[axis][k].max() / spin:+.3f} of the initial spin\"\n",
    "    )\n",
    "print(\n",
    "    f\"intermediate axis: {len(flips)} flips in 3 s, flip period {2 * np.diff(flips).mean():.5f} s, \"\n",
    "    f\"elliptic-function period {landau:.5f} s, deviation {100 * (2 * np.diff(flips).mean() / landau - 1):+.3f} %\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The three components of the angular velocity for the spin about the intermediate axis, the spin\n",
    "component for all three axes, and the path of the angular-momentum direction in the body frame:\n",
    "it circles the stable axes and swings from pole to pole around the intermediate one."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    times,\n",
    "    {f\"ω_{c}\": omega[\"y (intermediate)\"][k] / spin for k, c in enumerate(\"xyz\")},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"angular velocity / initial spin\",\n",
    "    title=\"Spin about the intermediate axis y\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times,\n",
    "    {f\"spin about {axis}\": omega[axis][\"xyz\".index(axis[0])] / spin for axis in runs},\n",
    "    ylimits=(-1.2, 1.8),\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"spin component / initial spin\",\n",
    "    title=\"Stable and unstable axes\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"spin about {axis}\": (\n",
    "            np.multiply(inertia, omega[axis].T)[::5, 0]\n",
    "            / np.linalg.norm(np.multiply(inertia, starts[axis])),\n",
    "            np.multiply(inertia, omega[axis].T)[::5, 1]\n",
    "            / np.linalg.norm(np.multiply(inertia, starts[axis])),\n",
    "        )\n",
    "        for axis in runs\n",
    "    },\n",
    "    xlimits=(-1.1, 1.1),\n",
    "    ylimits=(-1.1, 1.1),\n",
    "    xlabel=\"M_x / |M|\",\n",
    "    ylabel=\"M_y / |M|\",\n",
    "    title=\"Angular momentum seen from the body\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the stem in `dzhanibekov_t_handle_geometry.py` until its moment about $y$ is no longer\n",
    "intermediate, write the STEP file again and watch the flips disappear; or make the disturbance\n",
    "smaller: the flip period grows only with its logarithm."
   ]
  }
 ]
}
