{
 "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": [
    "# Ion cyclotron motion\n",
    "\n",
    "A charged particle of mass $m$ and charge $q$ in uniform fields obeys the Lorentz force law\n",
    "\n",
    "$$m\\,\\frac{d\\mathbf v}{dt}=q\\,(\\mathbf E+\\mathbf v\\times\\mathbf B),\\qquad \\frac{d\\mathbf x}{dt}=\\mathbf v .$$\n",
    "\n",
    "With $\\mathbf B=B\\,\\hat{\\mathbf z}$ alone, the velocity across the field rotates at the cyclotron\n",
    "frequency while the velocity along the field stays constant: the particle moves on a helix. An\n",
    "additional electric field across $\\mathbf B$ makes the centre of the circle drift perpendicular\n",
    "to both fields, independent of charge and mass.\n",
    "\n",
    "| quantity | value |\n",
    "|---|---|\n",
    "| particle | proton, $m=1.6726\\times10^{-27}$ kg, $q=e$ |\n",
    "| magnetic field | $B=0.1$ T along $z$ |\n",
    "| initial velocity | $v_\\perp=100$ km/s along $x$, $v_\\parallel=20$ km/s along $z$ |\n",
    "| electric field (second run) | $E=2$ kV/m along $x$ |\n",
    "\n",
    "`ChargedParticle` declares the six equations of motion for position and velocity as a lumped\n",
    "(0D) model in the uniform fields; OneSimulation integrates them in time like any other transient\n",
    "model, so the integrator is a free choice.\n",
    "\n",
    "**Reference** (F. F. Chen, *Introduction to Plasma Physics and Controlled Fusion*, 3rd ed.,\n",
    "Springer 2016, §2.2; J. D. Jackson, *Classical Electrodynamics*, 3rd ed., §12.3).\n",
    "\n",
    "$$\\omega_c=\\frac{|q|B}{m},\\qquad r_L=\\frac{m v_\\perp}{|q|B},\\qquad\n",
    "  \\mathbf v_E=\\frac{\\mathbf E\\times\\mathbf B}{B^2}.$$\n",
    "\n",
    "In complex notation $w=x+\\mathrm iy$ a positive ion starting at $w_0$ with transverse velocity\n",
    "$u_0$ follows $w(t)=w_0+v_Et+\\mathrm i\\,(u_0-v_E)\\,(e^{-\\mathrm i\\omega_ct}-1)/\\omega_c$, where\n",
    "$v_E$ is the drift velocity written as a complex number."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\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.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler, ClassicalRungeKutta4\n",
    "from onesim.physics.plasma import ChargedParticle\n",
    "from onesim.results import oscillation_fit\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.constants import e, m_p\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The proton circles 1.52 million times per second on a radius of about 10.4 mm."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "B, v_perp, v_par, E = 0.1, 1.0e5, 2.0e4, 2.0e3\n",
    "omega = e * B / m_p\n",
    "period, larmor, drift = 2 * np.pi / omega, m_p * v_perp / (e * B), E / B\n",
    "print(\n",
    "    f\"cyclotron frequency {omega / (2 * np.pi) / 1e6:.4f} MHz, Larmor radius {1e3 * larmor:.4f} mm, E x B drift {drift / 1e3:.1f} km/s\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "One problem per field configuration. The particle starts at $(0, r_L, 0)$ so that the circle of\n",
    "the first run is centred on the axis. Ten gyration periods are integrated with 40 steps per\n",
    "period by the classical Runge-Kutta method, the backward Euler method and the second-order BDF\n",
    "method; the implicit methods use Newton's method with the analytic Jacobian."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "fields = {\"B only\": (0.0, 0.0, 0.0), \"E x B\": (E, 0.0, 0.0)}\n",
    "particles = {\n",
    "    name: ChargedParticle(\n",
    "        domain=domain.system,\n",
    "        mass=m_p,\n",
    "        charge=e,\n",
    "        electric=electric,\n",
    "        magnetic=(0.0, 0.0, B),\n",
    "    )\n",
    "    for name, electric in fields.items()\n",
    "}\n",
    "start = (0.0, larmor, 0.0, v_perp, 0.0, v_par)\n",
    "problems = {\n",
    "    name: Problem(\n",
    "        name=f\"Proton, {name}\",\n",
    "        geometry=domain,\n",
    "        physics=(model,),\n",
    "        initial_conditions=tuple(\n",
    "            InitialValue(ref, value)\n",
    "            for ref, value in zip(\n",
    "                (\n",
    "                    model.x,\n",
    "                    model.y,\n",
    "                    model.z,\n",
    "                    model.velocity_x,\n",
    "                    model.velocity_y,\n",
    "                    model.velocity_z,\n",
    "                ),\n",
    "                start,\n",
    "            )\n",
    "        ),\n",
    "    )\n",
    "    for name, model in particles.items()\n",
    "}\n",
    "newton = Newton(linear_solver=SparseDirect(), jacobian=\"analytic\")\n",
    "integrators = {\n",
    "    \"classical Runge-Kutta\": Numerics(\n",
    "        spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "    ),\n",
    "    \"backward Euler\": Numerics(\n",
    "        spatial=LumpedParameters(),\n",
    "        time_integrator=BackwardEuler(),\n",
    "        nonlinear_solver=newton,\n",
    "    ),\n",
    "    \"BDF2\": Numerics(\n",
    "        spatial=LumpedParameters(),\n",
    "        time_integrator=BDF(order=2),\n",
    "        nonlinear_solver=newton,\n",
    "    ),\n",
    "}\n",
    "runs = {\n",
    "    (name, method): Simulation(\n",
    "        problem=problems[name], mesh=LumpedMesh(domain), numerics=numerics\n",
    "    ).run(start_time=0.0, end_time=10 * period, time_step=period / 40)\n",
    "    for name in problems\n",
    "    for method, numerics in integrators.items()\n",
    "}\n",
    "orbits = {\n",
    "    key: np.array(\n",
    "        [\n",
    "            result.field(ref).time_series()[1]\n",
    "            for ref in (\n",
    "                particles[key[0]].x,\n",
    "                particles[key[0]].y,\n",
    "                particles[key[0]].z,\n",
    "                particles[key[0]].velocity_x,\n",
    "                particles[key[0]].velocity_y,\n",
    "            )\n",
    "        ]\n",
    "    )\n",
    "    for key, result in runs.items()\n",
    "}\n",
    "times = (\n",
    "    runs[\"B only\", \"classical Runge-Kutta\"]\n",
    "    .field(particles[\"B only\"].x)\n",
    "    .time_series()[0]\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed forms\n",
    "\n",
    "The frequency is fitted to the rotating transverse velocity; the guiding centre is the mean\n",
    "position over the first and over the last period; the radius is the mean distance from it."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "exact = (\n",
    "    lambda t, drift_velocity: 1j * larmor\n",
    "    + drift_velocity * t\n",
    "    + 1j * (v_perp - drift_velocity) * (np.exp(-1j * omega * t) - 1) / omega\n",
    ")\n",
    "print(\n",
    "    \"B only: integrator       frequency [MHz]   Larmor radius [mm]   |v_perp| after 10 periods   largest orbit error [mm]\"\n",
    ")\n",
    "for method in integrators:\n",
    "    x, y, z, vx, vy = orbits[\"B only\", method]\n",
    "    centre = np.mean(x[:40] + 1j * y[:40])\n",
    "    print(\n",
    "        f\"  {method:22s} {abs(oscillation_fit(times, vx + 1j * vy).frequency) / (2 * np.pi) / 1e6:15.5f} \"\n",
    "        f\"{1e3 * np.mean(np.abs(x[:40] + 1j * y[:40] - centre)):20.4f} {np.hypot(vx[-1], vy[-1]) / v_perp:27.5f} \"\n",
    "        f\"{1e3 * np.abs(x + 1j * y - exact(times, 0)).max():25.3f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"  {'closed form':22s} {omega / (2 * np.pi) / 1e6:15.5f} {1e3 * larmor:20.4f} {1.0:27.5f}\"\n",
    ")\n",
    "print(\n",
    "    \"E x B:  integrator       drift of the guiding centre [km/s]   largest orbit error [mm]\"\n",
    ")\n",
    "for method in integrators:\n",
    "    x, y = orbits[\"E x B\", method][:2]\n",
    "    first, last = (np.mean(x[sl] + 1j * y[sl]) for sl in (slice(0, 40), slice(-41, -1)))\n",
    "    print(\n",
    "        f\"  {method:22s} {abs(last - first) / (9 * period) / 1e3:28.3f} {1e3 * np.abs(x + 1j * y - exact(times, -1j * drift)).max():26.3f}\"\n",
    "    )\n",
    "print(f\"  {'closed form E/B':22s} {drift / 1e3:28.3f}\")\n",
    "x, y, z = orbits[\"B only\", \"classical Runge-Kutta\"][:3]\n",
    "print(\n",
    "    f\"pitch of the helix: {1e3 * (z[40] - z[0]):.4f} mm per turn, closed form v_par 2 pi / omega_c = {1e3 * v_par * period:.4f} mm\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fine = np.linspace(0, 10 * period, 4000)\n",
    "circle, cycloid = exact(fine, 0), exact(fine, -1j * drift)\n",
    "fig = plots.figure(1, 3, size=(18, 5.2))\n",
    "plots.line(\n",
    "    points={\n",
    "        method: (\n",
    "            1e3 * orbits[\"B only\", method][0][::3],\n",
    "            1e3 * orbits[\"B only\", method][1][::3],\n",
    "        )\n",
    "        for method in integrators\n",
    "    },\n",
    "    reference={\"exact circle\": (1e3 * circle.real, 1e3 * circle.imag)},\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"Gyration across B, 10 periods\",\n",
    "    legend=\"center\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    1e6 * times,\n",
    "    {\n",
    "        method: np.hypot(*orbits[\"B only\", method][3:5]) / v_perp\n",
    "        for method in integrators\n",
    "    },\n",
    "    hlines={\"exact\": 1.0},\n",
    "    ylimits=(0, 1.1),\n",
    "    xlabel=\"time [µs]\",\n",
    "    ylabel=\"|v_perp| / v_perp(0)\",\n",
    "    title=\"Kinetic energy across B\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"classical Runge-Kutta\": (\n",
    "            1e3 * orbits[\"E x B\", \"classical Runge-Kutta\"][0][:121],\n",
    "            1e3 * orbits[\"E x B\", \"classical Runge-Kutta\"][1][:121],\n",
    "        )\n",
    "    },\n",
    "    reference={\"exact orbit\": (1e3 * cycloid.real[:1201], 1e3 * cycloid.imag[:1201])},\n",
    "    xlabel=\"x [mm]\",\n",
    "    ylabel=\"y [mm]\",\n",
    "    title=\"E x B drift with E along x, 3 periods\",\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",
    "Halve the time step and watch the backward Euler damping shrink only linearly while the\n",
    "Runge-Kutta orbit error drops sixteen-fold. Give the particle the charge $-e$ and the mass of an\n",
    "electron: it gyrates the other way and 1836 times faster, but drifts with the same $\\mathbf v_E$.\n",
    "A field that varies in space calls for the guiding-centre models `UniformGuidingCenter` and\n",
    "`NonuniformGuidingCenter`."
   ]
  }
 ]
}
