{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f2bfebaaef51",
   "metadata": {},
   "source": [
    "# Measuring Earth's rotation with a pendulum\n",
    "A pendulum swings in seconds but its direction turns over hours. Predict the sign of the change before running the cells. The origin is the suspension point projected onto the floor. Angles are positive counterclockwise as viewed from above."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e162012163e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "latitude_deg = 48.0    # try 0, -48, and 90\n",
    "length_m = 10.0\n",
    "amplitude_m = 0.15\n",
    "hours_between = 3.0\n",
    "assert -90 <= latitude_deg <= 90 and length_m > 0 and 0 < amplitude_m < 0.1*length_m\n",
    "assert 0 < hours_between <= 12"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "291096b301a5",
   "metadata": {},
   "source": [
    "## Separate fast and slow motion\n",
    "For east and north coordinates combine the horizontal equations into a complex displacement. An eastward release without initial velocity requires a small imaginary correction even when the observer sees an almost straight trace."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5fc11a26fba2",
   "metadata": {},
   "outputs": [],
   "source": [
    "earth_rate = 2*np.pi/86164.1\n",
    "f = earth_rate*np.sin(np.deg2rad(latitude_deg))\n",
    "omega = np.sqrt(9.81/length_m)\n",
    "nu = np.hypot(omega, f)\n",
    "def displacement(time):\n",
    "    time = np.asarray(time)\n",
    "    return amplitude_m*np.exp(-1j*f*time)*(np.cos(nu*time) + 1j*(f/nu)*np.sin(nu*time))\n",
    "\n",
    "period_s = 2*np.pi/nu\n",
    "days = 2*np.pi/(abs(f)*86400) if abs(f)>0 else np.inf\n",
    "print(f\"Swing period {period_s:.4f} s; apparent drift {-np.rad2deg(f)*3600:.3f} deg/h\")\n",
    "print(\"Directed-axis rotation period (solar days):\", days)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb4430c67dce",
   "metadata": {},
   "source": [
    "## Compare floor traces with the latitude law\n",
    "Each coloured curve spans one full swing at the displayed clock time. The adjacent graph uses a directed angle. A straight line on its own does not distinguish angles separated by 180 degrees."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0a91c7e2805",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1,2,figsize=(9,3.9),layout=\"constrained\")\n",
    "for hour, colour in zip([0,hours_between,2*hours_between],[\"#175868\",\"#a23d21\",\"#375b9a\"]):\n",
    "    u=displacement(hour*3600+np.linspace(0,period_s,220))\n",
    "    axes[0].plot(u.real*100,u.imag*100,lw=2.4,color=colour,label=f\"{hour:g} h\")\n",
    "axes[0].set(xlabel=\"East (cm)\",ylabel=\"North (cm)\",aspect=\"equal\",title=\"One swing at three times\",\n",
    "            xlim=(-110*amplitude_m,110*amplitude_m),ylim=(-110*amplitude_m,110*amplitude_m))\n",
    "axes[0].legend(fontsize=9)\n",
    "angles=np.linspace(-90,90,181); rates=-np.rad2deg(earth_rate*np.sin(np.deg2rad(angles)))*3600\n",
    "axes[1].plot(angles,rates,color=\"#175868\");axes[1].plot(latitude_deg,-np.rad2deg(f)*3600,\"o\",color=\"#a23d21\")\n",
    "axes[1].axhline(0,lw=.6,color=\"grey\")\n",
    "axes[1].set(xlabel=\"Latitude (degrees north)\",ylabel=\"Azimuth drift (degrees per hour)\",title=\"Clockwise drift is negative\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86fa6fb9de47",
   "metadata": {},
   "source": [
    "## Verify the initial condition and the equatorial limit\n",
    "Differentiate the sampled position symmetrically. Repeat with zero vertical rotation rate. Explain why changing the length changes the fast period but leaves the azimuthal drift rate unchanged."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f946a1a191bd",
   "metadata": {},
   "outputs": [],
   "source": [
    "assert abs(displacement(0)-amplitude_m)<1e-12\n",
    "assert abs((displacement(1e-5)-displacement(-1e-5))/2e-5)<1e-8\n",
    "if latitude_deg == 0: assert abs(displacement(.31).imag)<1e-12"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b0e202f6dc6",
   "metadata": {},
   "source": [
    "## Optional OneSimulation check\n",
    "In a OneSimulation installation, integrate both coupled real equations without using the complex solution. Compare the result after three swings. In the web notebook the analytic study above is fully usable with NumPy alone."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d6d52301a92",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    from onesim.numerics.time import ClassicalRungeKutta4TimeIntegrator\n",
    "except ImportError:\n",
    "    print(\"The optional integrator check runs in a local OneSimulation installation.\")\n",
    "else:\n",
    "    def acceleration(s,t):\n",
    "        x,y,vx,vy=s\n",
    "        return (vx,vy,-omega**2*x+2*f*vy,-omega**2*y-2*f*vx)\n",
    "    state=(amplitude_m,0.0,0.0,0.0); dt=period_s/180\n",
    "    method=ClassicalRungeKutta4TimeIntegrator()\n",
    "    for j in range(540): state=method.advance(state,acceleration,dt,time=j*dt)\n",
    "    error=abs(complex(*state[:2])-displacement(540*dt))/amplitude_m\n",
    "    print(\"Relative final displacement disagreement:\",error)\n",
    "    assert error < 1e-5"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
