{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "Which sampling times reveal the velocity of an oscillator?",
   "lead": "A sensor measures displacement while a controller needs velocity as well. Use the exact free vibration between two readings to recover the missing state, then quantify how a poorly chosen sample interval amplifies measurement noise.",
   "unit_slug": "sampling-a-position-only-oscillator"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "6964571d9293",
   "metadata": {},
   "source": [
    "# Which sampling times reveal the velocity of an oscillator?\n",
    "\n",
    "A sensor measures displacement while a controller needs velocity as well. Use the exact free vibration between two readings to recover the missing state, then quantify how a poorly chosen sample interval amplifies measurement noise."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b06ce8b323d9",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Observe a rotation through one coordinate\n",
    "\n",
    "For an undamped, unforced oscillator $\\ddot x+\\omega^2x=0$, use the state $z=[x,\\dot x/\\omega]^T$. Both entries then have units of length. A delay $\\Delta t$ advances phase by $\\theta=\\omega\\Delta t$. Integrating the equation exactly gives\n",
    "\n",
    "$$\n",
    "x(t+\\Delta t)=x(t)\\cos\\theta+[\\dot x(t)/\\omega]\\sin\\theta.\n",
    "$$\n",
    "\n",
    "The velocity equation follows by differentiating with respect to $\\Delta t$. Together they rotate the state by a matrix with first row $(\\cos\\theta,\\sin\\theta)$ and second row $(-\\sin\\theta,\\cos\\theta)$.\n",
    "\n",
    "The position sensor has observation row $(1,0)$. At consecutive samples its noiseless readings obey\n",
    "\n",
    "$$\\begin{bmatrix}y_0\\\\y_1\\end{bmatrix}=\\underbrace{\\begin{bmatrix}1&0\\\\\\cos\\theta&\\sin\\theta\\end{bmatrix}}_{O}\\begin{bmatrix}x_0\\\\v_0/\\omega\\end{bmatrix}.$$\n",
    "\n",
    "The determinant is $\\sin\\theta$. At integer half-period intervals the sensor measures the same direction in the state plane twice, allowing opposite velocities to produce exactly the same pair of readings. Away from those intervals,\n",
    "\n",
    "$$\n",
    "v_0=\\omega(y_1-y_0\\cos\\theta)/\\sin\\theta.\n",
    "$$\n",
    "\n",
    "The determinant diagnoses whether an exact reconstruction exists. The singular values describe whether that reconstruction will tolerate small errors. Because $OO^T$ has diagonal entries one and off-diagonal entries $\\cos\\theta$, its eigenvalues are $1\\pm|\\cos\\theta|$. Their square roots are the singular values of $O$ in the chosen state scaling."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0f404fb36401",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Propagate the uncertainty in two readings\n",
    "\n",
    "Suppose each recorded position has independent zero-mean noise of standard deviation $\\sigma_x$. A linear combination $y_1-y_0\\cos\\theta$ has variance $\\sigma_x^2(1+\\cos^2\\theta)$. Multiply by the square of the velocity gain to obtain\n",
    "\n",
    "$$\n",
    "\\sigma_v=\\omega\\sigma_x\\sqrt{1+\\cos^2\\theta}/|\\sin\\theta|.\n",
    "$$\n",
    "\n",
    "An exact knowledge of the sample times and natural frequency is assumed in this expression.\n",
    "\n",
    "A 2 Hz oscillator has period 0.5 s and angular frequency $4\\pi$ rad/s. With a 0.125 s interval the second reading directly measures $v_0/\\omega$. For 0.10 mm position noise the recovered velocity has standard deviation 1.257 mm/s. Increasing the delay to 0.240 s moves the second observation close to the direction opposite the first. The same position uncertainty now produces 14.12 mm/s of velocity uncertainty, although the mathematical reconstruction still exists. The notebook varies the sampling interval continuously and checks the formula against noise propagation through the inverse matrix."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2838e95f9f25",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "156daf215183",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "58d7b8092a21",
   "metadata": {},
   "source": [
    "frequency_hz = 2.0\n",
    "sample_interval_s = 0.125\n",
    "position_mm = 1.0\n",
    "velocity_mm_s = 10.0\n",
    "noise_mm = 0.10"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "e1304898c340",
   "metadata": {},
   "source": [
    "assert min(frequency_hz, sample_interval_s) > 0 and noise_mm >= 0\n",
    "omega = 2*np.pi*frequency_hz\n",
    "period = 1/frequency_hz\n",
    "theta = omega*sample_interval_s\n",
    "c, s = np.cos(theta), np.sin(theta)\n",
    "observation = np.array([[1.0, 0.0], [c, s]])\n",
    "state = np.array([position_mm, velocity_mm_s/omega])\n",
    "readings = observation @ state\n",
    "print(f\"Pair of noiseless readings (mm): {readings.round(5)}\")\n",
    "if abs(s) < 1e-10:\n",
    "    print(\"At this sample interval both readings are independent of the initial velocity.\")\n",
    "else:\n",
    "    velocity_est = omega*(readings[1]-c*readings[0])/s\n",
    "    sigma_v = omega*noise_mm*np.sqrt(1+c*c)/abs(s)\n",
    "    inverse = np.linalg.inv(observation)\n",
    "    expected_variance = omega**2*noise_mm**2*(inverse @ inverse.T)[1,1]\n",
    "    assert np.isclose(sigma_v**2, expected_variance) and np.isclose(velocity_est, velocity_mm_s)\n",
    "    print(f\"Inferred velocity: {velocity_est:.4g} mm/s; standard deviation: {sigma_v:.4g} mm/s\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "51d8e3c2250a",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "control-engineering-control-engineering-methods-1.png",
      "alt": "Two motions with equal initial position and different initial velocities intersect at every half-period sample.",
      "caption": "Compare the equal half-period readings with the selected off-grid observation. Continuous motion between sample points can carry information that the readings discard."
     }
    }
   },
   "source": [
    "time_s = np.linspace(0, 1.05*period, 400)\n",
    "fig, ax = axes(\"Time (s)\", \"Displacement (mm)\")\n",
    "other_velocity = velocity_mm_s + max(5.0, abs(velocity_mm_s))\n",
    "for vel, color in [(velocity_mm_s, teal), (other_velocity, orange)]:\n",
    "    motion = position_mm*np.cos(omega*time_s) + vel/omega*np.sin(omega*time_s)\n",
    "    ax.plot(time_s, motion, color=color, label=f\"Initial velocity {vel:.2g} mm/s\")\n",
    "    selected_time = sample_interval_s % period\n",
    "    observed = position_mm*np.cos(omega*selected_time)+vel/omega*np.sin(omega*selected_time)\n",
    "    ax.scatter([selected_time], [observed], color=color, zorder=4)\n",
    "half_times = period*np.array([0, 0.5, 1])\n",
    "ax.scatter(half_times, position_mm*np.array([1, -1, 1]), color=\"black\", zorder=5, label=\"Half-period samples\")\n",
    "ax.legend(fontsize=8)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "90ec65aa6fcc",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Compare the equal half-period readings with the selected off-grid observation. Continuous motion between sample points can carry information that the readings discard."
   ]
  },
  {
   "cell_type": "code",
   "id": "32d199b625bb",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "control-engineering-control-engineering-methods-2.png",
      "alt": "Velocity uncertainty from two position readings as a function of the sampling interval in periods, with divergences at integral half-periods.",
      "caption": "The smallest uncertainty occurs at the quarter-period points where the second position reading depends only on the initial velocity."
     }
    }
   },
   "source": [
    "fraction = np.linspace(0.002, 0.998, 1001)\n",
    "ss, cc = np.sin(2*np.pi*fraction), np.cos(2*np.pi*fraction)\n",
    "gain = np.sqrt(1+cc**2) / np.maximum(abs(ss), 1e-14)\n",
    "gain[abs(ss) < 0.02] = np.nan\n",
    "fig, ax = axes(\"Sampling interval / oscillator period\", \"Velocity noise gain relative to ωσₓ\")\n",
    "ax.semilogy(fraction, gain, color=teal, label=\"Two-position estimate\")\n",
    "ax.axvline(0.5, color=orange, linestyle=\"--\", label=\"Unobservable half-period\")\n",
    "ax.plot([0.25, 0.75], [1, 1], \"ko\", label=\"Quarter-period optima\")\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "1c241c7bf0e5",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "The smallest uncertainty occurs at the quarter-period points where the second position reading depends only on the initial velocity."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ea47e60c909",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Problem 1 · Take more readings at exactly one half-period\n",
    "\n",
    "A colleague proposes collecting 100 equally spaced positions to recover velocity at $\\Delta t=T/2$. Does the larger data set recover the missing state for this exact model?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "105fbbbf189d",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "After $k$ steps the observation row is $(\\cos k\\pi,\\sin k\\pi)=((-1)^k,0)$. Every reading measures only the initial position, up to its alternating sign. Averaging can reduce the noise in $x_0$, while the initial velocity remains arbitrary. One extra measured position at a known quarter-period after the first would add row $(0,1)$ and restore the missing independent equation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dea9a71c85f5",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Problem 2 · Relate observability to a finite difference\n",
    "\n",
    "For $\\omega\\Delta t\\ll1$, derive the leading noise in the reconstructed velocity. Explain why decreasing the interval can increase the velocity error here."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8936b928b8d",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "Use $\\sin\\theta\\simeq\\theta=\\omega\\Delta t$ and $\\cos\\theta\\simeq1$. The estimate becomes $(y_1-y_0)/\\Delta t$ to leading order and $\\sigma_v\\simeq\\sqrt{2}\\sigma_x/\\Delta t$. The actual displacement accumulated over a short interval shrinks, while the two independent noise samples have a difference of fixed standard deviation. This result applies to the two-reading estimate; fitting many accurately timed readings over a fixed observation duration uses different information."
   ]
  }
 ]
}
