{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Golf ball trajectory: why dimples carry further\n",
    "\n",
    "A golf ball leaves the club with speed $U_0$, launch angle $\\theta_0$ and backspin. In flight it\n",
    "feels gravity, drag opposite to the velocity and Magnus lift perpendicular to it. With the speed\n",
    "$U$, the cross-section $A$ and the mass $m$,\n",
    "\n",
    "$$\\ddot x = -\\frac{\\rho A U}{2m}\\,\\big(C_D\\,\\dot x + C_L\\,\\dot y\\big),\\qquad\n",
    "  \\ddot y = \\frac{\\rho A U}{2m}\\,\\big(C_L\\,\\dot x - C_D\\,\\dot y\\big) - g .$$\n",
    "\n",
    "The coefficients depend on the Reynolds number $Re=\\rho U d/\\mu$ and the spin parameter\n",
    "$S=\\omega d/(2U)$. For the dimpled ball $C_D=0.24+0.18\\,S$ and $C_L=0.54\\,S^{0.4}$ (Smits and\n",
    "Smith, *Science and Golf II*). The smooth ball has the drag of a smooth sphere (Morrison's\n",
    "correlation) and, as in the published comparison, the same lift.\n",
    "\n",
    "**Reference.** Without air the trajectory is a parabola with the carry $U_0^2\\sin 2\\theta_0/g$.\n",
    "The published result for this shot is a carry of about 150 m for the dimpled ball and a smooth\n",
    "ball that flies about 25 % shorter."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.time import (\n",
    "    AdaptiveBDF,\n",
    "    AdaptiveRungeKutta45,\n",
    "    EventDefinition,\n",
    "    FixedStepRungeKutta,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()\n",
    "\n",
    "diameter, mass, air_density, air_viscosity, gravity = (\n",
    "    42.67e-3,\n",
    "    45.93e-3,\n",
    "    1.204,\n",
    "    1.825e-5,\n",
    "    9.80665,\n",
    ")\n",
    "speed, angle, spin = 187.0 / 3.6, np.radians(17.4), 6113.0 * 2 * np.pi / 60\n",
    "launch = np.array([0.0, 0.0, speed * np.cos(angle), speed * np.sin(angle)])\n",
    "landing = EventDefinition(\n",
    "    \"landing\", lambda t, state: state[1], direction=-1, terminal=True\n",
    ")\n",
    "\n",
    "balls = {\n",
    "    \"dimpled\": lambda reynolds, s: (0.24 + 0.18 * s, 0.54 * s**0.4),\n",
    "    \"smooth\": lambda reynolds, s: (\n",
    "        24 / reynolds\n",
    "        + 2.6 * (reynolds / 5) / (1 + (reynolds / 5) ** 1.52)\n",
    "        + 0.411 * (reynolds / 2.63e5) ** -7.94 / (1 + (reynolds / 2.63e5) ** -8.0)\n",
    "        + 0.25 * (reynolds / 1e6) / (1 + reynolds / 1e6),\n",
    "        0.54 * s**0.4,\n",
    "    ),\n",
    "    \"no air\": lambda reynolds, s: (0.0, 0.0),\n",
    "}\n",
    "\n",
    "\n",
    "def flight(ball):\n",
    "    \"\"\"Right-hand side of the equations of motion for the state (x, y, vx, vy).\"\"\"\n",
    "\n",
    "    def rate(time, state):\n",
    "        u = np.hypot(state[2], state[3])\n",
    "        omega = spin * np.exp(-1e-4 * u * time / diameter)\n",
    "        drag, lift = balls[ball](\n",
    "            air_density * u * diameter / air_viscosity, omega * diameter / (2 * u)\n",
    "        )\n",
    "        k = air_density * np.pi * diameter**2 / 4 * u / (2 * mass)\n",
    "        return np.array(\n",
    "            [\n",
    "                state[2],\n",
    "                state[3],\n",
    "                -k * (drag * state[2] + lift * state[3]),\n",
    "                k * (lift * state[2] - drag * state[3]) - gravity,\n",
    "            ]\n",
    "        )\n",
    "\n",
    "    return rate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Trajectories\n",
    "\n",
    "The adaptive Dormand-Prince method integrates each flight; the landing is an event that stops\n",
    "the integration exactly at $y=0$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "precise = AdaptiveRungeKutta45(\n",
    "    relative_tolerance=1e-12, absolute_tolerance=1e-14, maximum_step=0.01\n",
    ")\n",
    "runs = {\n",
    "    ball: precise.integrate(\n",
    "        flight(ball), launch, 0.0, 30.0, initial_step=1e-3, events=(landing,)\n",
    "    )\n",
    "    for ball in balls\n",
    "}\n",
    "carry = {ball: run.events[-1].state[0] for ball, run in runs.items()}\n",
    "exact_carry = speed**2 * np.sin(2 * angle) / gravity\n",
    "print(f\"no air:  carry {carry['no air']:.6f} m, exact parabola {exact_carry:.6f} m\")\n",
    "print(\n",
    "    f\"dimpled: carry {carry['dimpled']:.1f} m (published: about 150 m), flight time {runs['dimpled'].events[-1].time:.2f} s\"\n",
    ")\n",
    "print(\n",
    "    f\"smooth:  carry {carry['smooth']:.1f} m, {100 * (1 - carry['smooth'] / carry['dimpled']):.0f} % shorter (published: about 25 %)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Three time integrators\n",
    "\n",
    "The dimpled-ball flight again with the adaptive Runge-Kutta method, an adaptive second-order BDF\n",
    "method and the classical fixed-step Runge-Kutta method, each at several accuracies. The error of\n",
    "the carry is measured against the precise run above."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "methods = {\n",
    "    \"Dormand-Prince (adaptive)\": [\n",
    "        (\n",
    "            AdaptiveRungeKutta45(relative_tolerance=tol, absolute_tolerance=tol / 100),\n",
    "            {\"initial_step\": 1e-3},\n",
    "        )\n",
    "        for tol in (1e-3, 1e-5, 1e-7, 1e-9)\n",
    "    ],\n",
    "    \"BDF2 (adaptive)\": [\n",
    "        (\n",
    "            AdaptiveBDF(order=2, relative_tolerance=tol, absolute_tolerance=tol / 100),\n",
    "            {\"initial_step\": 1e-3},\n",
    "        )\n",
    "        for tol in (1e-3, 1e-4, 1e-5, 1e-6)\n",
    "    ],\n",
    "    \"classical Runge-Kutta (fixed step)\": [\n",
    "        (FixedStepRungeKutta(\"rk4\"), {\"step\": step}) for step in (0.2, 0.1, 0.05, 0.025)\n",
    "    ],\n",
    "}\n",
    "work = {}\n",
    "for name, variants in methods.items():\n",
    "    results = [\n",
    "        solver.integrate(\n",
    "            flight(\"dimpled\"), launch, 0.0, 30.0, events=(landing,), **options\n",
    "        )\n",
    "        for solver, options in variants\n",
    "    ]\n",
    "    work[name] = (\n",
    "        [len(run.times) - 1 for run in results],\n",
    "        [abs(run.events[-1].state[0] - carry[\"dimpled\"]) for run in results],\n",
    "    )\n",
    "    print(\n",
    "        f\"{name:36s} steps {work[name][0]}   carry error [m] \"\n",
    "        + \", \".join(f\"{error:.1e}\" for error in work[name][1])\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "paths = {\n",
    "    f\"{ball}: {carry[ball]:.1f} m\": (run.states[:, 0], run.states[:, 1])\n",
    "    for ball, run in runs.items()\n",
    "}\n",
    "fig = plots.figure(1, 2, size=(14, 5))\n",
    "plots.line(\n",
    "    y=paths,\n",
    "    vlines={\"published carry of the dimpled ball\": 150.0},\n",
    "    xlimits=(0, 185),\n",
    "    ylimits=(0, 48),\n",
    "    xlabel=\"distance [m]\",\n",
    "    ylabel=\"height [m]\",\n",
    "    title=\"7-iron shot: 187 km/h, 17.4°, 6113 rpm\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y=work,\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"time steps\",\n",
    "    ylabel=\"error of the carry [m]\",\n",
    "    title=\"Accuracy against work for three integrators\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a head wind by subtracting it from the velocity in `flight`, tilt the spin axis for a slice\n",
    "in three dimensions, or sweep the launch angle to find the longest carry."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
