{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8e1ba59c",
   "metadata": {},
   "source": [
    "# Learn a repeatable move from its previous tracking error\n",
    "\n",
    "A stage repeats the same trajectory many times. Predict what happens if the learning update becomes too aggressive. The horizontal coordinate within each motion is distinct from the trial number. Edit the first cell and rerun."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77dc0c6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "memory = .75            # sampled plant pole, 0 < memory < 1\n",
    "relative_step = .9      # fraction of 2 / largest squared singular value\n",
    "trials = 30\n",
    "N = 48                 # commands per move\n",
    "assert 0 < memory < 1 and 0 < relative_step <= 1.12 and 1 <= trials <= 60 and 12 <= N <= 96"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08e2ed06",
   "metadata": {},
   "source": [
    "## Lift the causal recurrence onto one trial\n",
    "Model the stage by $y_{k+1}=a y_k+(1-a)u_k$ with zero initial state. Record $y_1$ to $y_N$ for inputs $u_0$ to $u_{N-1}$. A deterministic output disturbance returns in the same phase of every trial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "121c1e2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "lag = np.arange(N)[:,None]-np.arange(N)[None,:]\n",
    "G = np.tril((1-memory)*memory**np.maximum(lag,0))\n",
    "t = np.arange(1,N+1)/N\n",
    "target = .9*np.sin(np.pi*t)**2 + .13*np.sin(6*np.pi*t)\n",
    "disturbance = .09*np.sin(2*np.pi*t) + .025*np.cos(8*np.pi*t)\n",
    "sigma = np.linalg.svd(G,compute_uv=False)\n",
    "gamma = relative_step*2/sigma[0]**2\n",
    "print(f\"Singular values range {sigma[-1]:.4f} to {sigma[0]:.4f}.\")\n",
    "print(f\"Learning step {gamma:.3f}; upper bound for monotone contraction {2/sigma[0]**2:.3f}.\")\n",
    "u_test = np.linspace(-1,1,N); state=0.; sequence=[]\n",
    "for u in u_test:\n",
    "    state=memory*state+(1-memory)*u\n",
    "    sequence.append(state)\n",
    "assert np.allclose(G@u_test,sequence)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2181b80f",
   "metadata": {},
   "source": [
    "## Apply the adjoint of the forward operator\n",
    "Corrections use the entire previous record. Compare against the theoretically slowest contraction factor; the reference starts at the measured first error. For an intentionally excessive step study only this linear model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "902cdee4",
   "metadata": {},
   "outputs": [],
   "source": [
    "u = np.zeros(N)\n",
    "energies, paths = [], []\n",
    "for j in range(trials+1):\n",
    "    y = G@u + disturbance\n",
    "    error = target-y\n",
    "    paths.append(y.copy())\n",
    "    energies.append(np.linalg.norm(error)/np.sqrt(N))\n",
    "    u += gamma*(G.T@error)\n",
    "factor = np.max(np.abs(1-gamma*sigma**2))\n",
    "if relative_step < 1:\n",
    "    assert np.all(np.diff(energies) <= 1e-11)\n",
    "assert np.all(np.asarray(energies) <= energies[0]*factor**np.arange(trials+1)+1e-11)\n",
    "print(f\"RMS error from {energies[0]:.5f} to {energies[-1]:.5f}; worst-case error-norm factor {factor:.4f}.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6f79258",
   "metadata": {},
   "source": [
    "## Compare a trajectory to a convergence diagnostic\n",
    "The dashed bound permits mixtures of error directions and can lie above the actual error. Print the singular values to estimate which components of a tracking error are learned slowly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12ed5675",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig,ax=plt.subplots(1,2,figsize=(9.2,3.5),layout=\"constrained\")\n",
    "ax[0].plot(t,target,color=\"0.2\",lw=2,label=\"Target\")\n",
    "for j,style in [(0,\":\"),(min(2,trials),\"--\"),(trials,\"-.\")]:\n",
    "    ax[0].plot(t,paths[j],style,label=f\"Trial {j}\")\n",
    "idx=np.arange(trials+1)\n",
    "ax[1].semilogy(idx,energies,label=\"Simulated RMS error\")\n",
    "ax[1].semilogy(idx,energies[0]*factor**idx,\"--\",label=\"Singular-value bound\")\n",
    "ax[0].set(xlabel=\"Fraction of one move\",ylabel=\"Normalised position\",title=\"Motion within a trial\")\n",
    "ax[1].set(xlabel=\"Completed learning updates\",ylabel=\"RMS tracking error\",title=\"Improvement across trials\")\n",
    "for p in ax:\n",
    "    p.grid(alpha=.2); p.legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52017e1e",
   "metadata": {},
   "source": [
    "## Change one assumption\n",
    "Set the relative step to 1.05 and increase the trial count. A particular reference can show several improving trials even though the worst singular direction grows. Replace the repeatable disturbance by a different vector on each trial, remove the deterministic contraction assertion, and calculate errors against a separate clean trajectory. Explain why the original bound no longer follows."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f88dcdfd",
   "metadata": {},
   "source": [
    "## Identify the worst-case error from an independent eigenproblem\n",
    "The eigenvalues of the symmetric error-propagation matrix are the gains on independent error directions. OneSimulation can solve that eigenproblem locally. In the browser use the corresponding NumPy solver and cross-check against the earlier singular-value prediction."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84ac515f",
   "metadata": {},
   "outputs": [],
   "source": [
    "error_map = np.eye(N) - gamma * (G @ G.T)\n",
    "try:\n",
    "    from onesim.numerics.linear.matrices.dense_linear_algebra import symmetric_eigenvalues\n",
    "    method = \"OneSimulation symmetric eigenvalues\"\n",
    "except ImportError:\n",
    "    symmetric_eigenvalues = np.linalg.eigvalsh\n",
    "    method = \"NumPy symmetric eigenvalues\"\n",
    "\n",
    "error_gains = symmetric_eigenvalues(error_map)\n",
    "measured_factor = np.max(np.abs(error_gains))\n",
    "assert np.isclose(measured_factor, factor)\n",
    "print(f\"{method}: worst one-trial error gain {measured_factor:.6f}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
