{
 "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": [
    "# Spacecraft on an elliptical transfer orbit\n",
    "\n",
    "A spacecraft leaves a low Earth parking orbit on a geostationary transfer orbit: at\n",
    "the perigee, 250 km above the surface, it has just the speed that carries it out to\n",
    "the geostationary radius of 42 164 km. Only the Earth's central gravity acts, so the\n",
    "motion stays in the orbital plane and obeys\n",
    "\n",
    "$$\\ddot{\\mathbf r}=-\\frac{\\mu}{r^3}\\,\\mathbf r,\\qquad \\mathbf r=(x,y),\\quad r=|\\mathbf r|,$$\n",
    "\n",
    "with the gravitational parameter of the Earth $\\mu=GM=3.986\\,004\\times10^{14}$ m³/s².\n",
    "OneSimulation assembles the equations as a signal-flow graph: four integrator blocks\n",
    "hold the position and the velocity, two blocks evaluate the gravitational\n",
    "acceleration, and the graph is integrated with the classical fourth-order\n",
    "Runge-Kutta method at a fixed step.\n",
    "\n",
    "**Reference.** Kepler's laws for the two-body problem (H. D. Curtis, *Orbital\n",
    "Mechanics for Engineering Students*, 3rd ed., Butterworth-Heinemann 2014, ch. 2).\n",
    "With the perigee and apogee radii $r_p$, $r_a$, the semi-major axis and the\n",
    "eccentricity are $a=(r_p+r_a)/2$, $e=(r_a-r_p)/(r_a+r_p)$, and\n",
    "\n",
    "$$r(\\theta)=\\frac{a(1-e^2)}{1+e\\cos\\theta},\\qquad T=2\\pi\\sqrt{\\frac{a^3}{\\mu}},\\qquad\n",
    "  \\varepsilon=\\frac{v^2}{2}-\\frac{\\mu}{r}=-\\frac{\\mu}{2a},\\qquad h=|\\mathbf r\\times\\mathbf v|=\\sqrt{\\mu a(1-e^2)}.$$\n",
    "\n",
    "The vis-viva equation gives the perigee speed $v_p=\\sqrt{\\mu\\,(2/r_p-1/a)}$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.time import DEFAULT_TIME_INTEGRATOR_REGISTRY\n",
    "from onesim.physics.systems import ControlSignalFlowProvider, SignalBlock\n",
    "from onesim.results.sampling import crossing_times\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Orbit\n",
    "\n",
    "The spacecraft starts at the perigee on the $x$ axis with the vis-viva speed in the\n",
    "$y$ direction and is followed for three revolutions."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "mu, earth_radius = 3.986004418e14, 6.378137e6\n",
    "perigee, apogee = earth_radius + 250e3, 42.164e6\n",
    "semi_major, eccentricity = 0.5 * (perigee + apogee), (apogee - perigee) / (\n",
    "    apogee + perigee\n",
    ")\n",
    "period = 2 * np.pi * np.sqrt(semi_major**3 / mu)\n",
    "perigee_speed = np.sqrt(mu * (2 / perigee - 1 / semi_major))\n",
    "energy_exact, momentum_exact = -mu / (2 * semi_major), np.sqrt(\n",
    "    mu * semi_major * (1 - eccentricity**2)\n",
    ")\n",
    "print(\n",
    "    f\"a = {semi_major / 1e3:.1f} km, e = {eccentricity:.5f}, period T = {period:.1f} s ({period / 3600:.3f} h), \"\n",
    "    f\"perigee speed {perigee_speed:.2f} m/s\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Signal-flow graph and step study\n",
    "\n",
    "The same graph is integrated with steps of 120, 60, 30 and 15 s; the 15 s run is the\n",
    "result shown below. Near the perigee the spacecraft covers about 150 km per step."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "steps = (120.0, 60.0, 30.0, 15.0)\n",
    "runs = {\n",
    "    dt: ControlSignalFlowProvider(\n",
    "        blocks=(\n",
    "            SignalBlock(\n",
    "                \"x\", \"integrator\", inputs=(\"vx\",), parameters={\"initial_value\": perigee}\n",
    "            ),\n",
    "            SignalBlock(\"y\", \"integrator\", inputs=(\"vy\",)),\n",
    "            SignalBlock(\"vx\", \"integrator\", inputs=(\"ax\",)),\n",
    "            SignalBlock(\n",
    "                \"vy\",\n",
    "                \"integrator\",\n",
    "                inputs=(\"ay\",),\n",
    "                parameters={\"initial_value\": perigee_speed},\n",
    "            ),\n",
    "            SignalBlock(\n",
    "                \"ax\",\n",
    "                \"custom\",\n",
    "                inputs=(\"x\", \"y\"),\n",
    "                custom_evaluator=lambda s, t, p: -mu * s[0] / np.hypot(*s) ** 3,\n",
    "                custom_derivative=lambda *a: (),\n",
    "            ),\n",
    "            SignalBlock(\n",
    "                \"ay\",\n",
    "                \"custom\",\n",
    "                inputs=(\"x\", \"y\"),\n",
    "                custom_evaluator=lambda s, t, p: -mu * s[1] / np.hypot(*s) ** 3,\n",
    "                custom_derivative=lambda *a: (),\n",
    "            ),\n",
    "        ),\n",
    "        final_time=3 * period,\n",
    "        time_step=dt,\n",
    "        time_integrator=DEFAULT_TIME_INTEGRATOR_REGISTRY.resolve_id(\"classical_rk4\"),\n",
    "    ).execute()\n",
    "    for dt in steps\n",
    "}\n",
    "orbit = {\n",
    "    dt: {k: np.asarray(run.signals[k]) for k in (\"x\", \"y\", \"vx\", \"vy\")}\n",
    "    for dt, run in runs.items()\n",
    "}\n",
    "energy = {\n",
    "    dt: 0.5 * (s[\"vx\"] ** 2 + s[\"vy\"] ** 2) - mu / np.hypot(s[\"x\"], s[\"y\"])\n",
    "    for dt, s in orbit.items()\n",
    "}\n",
    "momentum = {dt: s[\"x\"] * s[\"vy\"] - s[\"y\"] * s[\"vx\"] for dt, s in orbit.items()}\n",
    "times, s = np.asarray(runs[15.0].times), orbit[15.0]\n",
    "radius, anomaly = np.hypot(s[\"x\"], s[\"y\"]), np.arctan2(s[\"y\"], s[\"x\"])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with Kepler's laws\n",
    "\n",
    "The period is the time between successive perigee passages, where $y$ crosses zero\n",
    "upwards; the orbit radius is compared with the conic section at the same true\n",
    "anomaly $\\theta$; energy and angular momentum must stay at their initial values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "ellipse = (\n",
    "    lambda theta: semi_major\n",
    "    * (1 - eccentricity**2)\n",
    "    / (1 + eccentricity * np.cos(theta))\n",
    ")\n",
    "passages = np.asarray(\n",
    "    crossing_times(times, s[\"y\"], 0.0, direction=\"rising\", after=0.5 * period)\n",
    ")\n",
    "print(\n",
    "    f\"perigee passages after {', '.join(f'{t:.1f}' for t in passages)} s;  \"\n",
    "    f\"period {np.mean(np.diff(np.r_[0.0, passages])):.2f} s, Kepler {period:.2f} s\"\n",
    ")\n",
    "print(\n",
    "    f\"apogee radius {radius.max() / 1e3:.2f} km (exact {apogee / 1e3:.2f} km),  \"\n",
    "    f\"largest deviation from the ellipse {np.abs(radius / ellipse(anomaly) - 1).max():.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"specific energy {energy[15.0][0] / 1e6:.4f} MJ/kg (exact {energy_exact / 1e6:.4f}),  \"\n",
    "    f\"angular momentum {momentum[15.0][0] / 1e6:.2f} km²/s (exact {momentum_exact / 1e6:.2f})\"\n",
    ")\n",
    "print(\n",
    "    \"  step [s]   energy drift after 3 revolutions   largest energy error   angular-momentum drift\"\n",
    ")\n",
    "for dt in steps:\n",
    "    print(\n",
    "        f\"{dt:9.0f} {abs(energy[dt][-1] / energy_exact - 1):24.2e} {np.abs(energy[dt] / energy_exact - 1).max():22.2e} \"\n",
    "        f\"{abs(momentum[dt][-1] / momentum_exact - 1):24.2e}\"\n",
    "    )\n",
    "drift = [abs(energy[dt][-1] / energy_exact - 1) for dt in steps]\n",
    "largest = [np.abs(energy[dt] / energy_exact - 1).max() for dt in steps]\n",
    "print(\n",
    "    f\"observed order between the two finest steps: {np.log2(largest[-2] / largest[-1]):.2f} for the largest energy error, \"\n",
    "    f\"{np.log2(drift[-2] / drift[-1]):.2f} for the drift after whole revolutions\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The classical Runge-Kutta method has global order four, and so does the largest energy\n",
    "error along the orbit. Nearly all of the error is made during the fast perigee\n",
    "passages, and right at the perigee part of it cancels, so the drift evaluated after\n",
    "whole revolutions falls even faster.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The computed orbit over the Kepler ellipse with the Earth to scale; the distance from\n",
    "the Earth's centre over time (dotted verticals: the perigee passages); the relative drift of energy and angular momentum; and\n",
    "the energy drift against the step size."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = np.linspace(0.0, 2 * np.pi, 721)\n",
    "fig = plots.figure(2, 2, size=(14, 10.5))\n",
    "plots.line(\n",
    "    y={\n",
    "        \"computed orbit\": (s[\"x\"][::4] / 1e6, s[\"y\"][::4] / 1e6),\n",
    "        \"Earth\": (\n",
    "            earth_radius * np.cos(theta) / 1e6,\n",
    "            earth_radius * np.sin(theta) / 1e6,\n",
    "        ),\n",
    "    },\n",
    "    reference={\n",
    "        \"Kepler ellipse\": (\n",
    "            ellipse(theta) * np.cos(theta) / 1e6,\n",
    "            ellipse(theta) * np.sin(theta) / 1e6,\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"x [1000 km]\",\n",
    "    ylabel=\"y [1000 km]\",\n",
    "    title=\"Geostationary transfer orbit\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times / 3600,\n",
    "    {\"computed r(t)\": radius / 1e6},\n",
    "    hlines={\"apogee r_a\": apogee / 1e6, \"perigee r_p\": perigee / 1e6},\n",
    "    vlines=passages / 3600,\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"distance from the Earth's centre [1000 km]\",\n",
    "    title=\"Radius over three revolutions\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    times / 3600,\n",
    "    {\n",
    "        \"energy ε/ε0 - 1\": energy[15.0] / energy_exact - 1,\n",
    "        \"angular momentum h/h0 - 1\": momentum[15.0] / momentum_exact - 1,\n",
    "    },\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"relative drift\",\n",
    "    title=\"Conservation laws, step 15 s\",\n",
    "    legend=\"center\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.convergence(\n",
    "    np.array(steps),\n",
    "    {\n",
    "        \"largest energy error\": np.array(largest),\n",
    "        \"drift after 3 revolutions\": np.array(drift),\n",
    "    },\n",
    "    order=(4, 5),\n",
    "    xlabel=\"time step [s]\",\n",
    "    ylabel=\"relative energy drift\",\n",
    "    title=\"Energy drift against the step size\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a third block pair for the $J_2$ oblateness acceleration and watch the line of\n",
    "apsides rotate; or a thrust block that fires at apogee to circularise the orbit at\n",
    "the geostationary radius (the classical Hohmann manoeuvre, $\\Delta v\\approx1.47$ km/s).\n",
    "With a symplectic integrator instead of Runge-Kutta the energy error stays bounded\n",
    "instead of drifting, a property that matters for very long propagations."
   ]
  }
 ]
}
