{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "469afff6",
   "metadata": {},
   "source": [
    "# How a single delayed sample moves a closed-loop pole\n",
    "\n",
    "The controller samples a first-order plant and holds its command until the next sample. Compare immediate application with the same calculation arriving exactly one sample late. Predict which gain produces oscillation before running the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66e174f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "tau,period,gain=.50,.10,4.5    # seconds, seconds, dimensionless proportional gain\n",
    "samples=50\n",
    "assert tau>0 and period>0 and gain>=0 and 10<=samples<=200\n",
    "a=np.exp(-period/tau)\n",
    "b=1-a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6eed08b",
   "metadata": {},
   "source": [
    "## Derive the homogeneous sampled recurrences\n",
    "For regulation to zero the direct controller gives x[k+1] = (a - bK)x[k]. With delay the coefficient multiplies x[k-1] instead. Initialise the remembered reading to zero, so the first delayed command is zero."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91655842",
   "metadata": {},
   "outputs": [],
   "source": [
    "def run(k,delay):\n",
    "    old,x=0.,1.;values=[x]\n",
    "    for _ in range(samples):\n",
    "        old,x=x,a*x-b*k*(old if delay else x)\n",
    "        values.append(x)\n",
    "    return np.array(values)\n",
    "poles=np.roots([1,-a,b*gain])\n",
    "direct=run(gain,False);delayed=run(gain,True)\n",
    "print(f\"a = {a:.4f}, direct pole = {a-b*gain:.4f}, delayed poles = {poles}\")\n",
    "print(f\"Upper positive gain limits: immediate {(1+a)/b:.3f}, delayed {1/b:.3f}\")\n",
    "assert np.isclose(direct[1],a-b*gain) and np.isclose(delayed[1],a)\n",
    "assert np.isclose(np.prod(poles),b*gain)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9374729",
   "metadata": {},
   "source": [
    "## Locate the damping and stability limits\n",
    "The two controllers use identical numerical coefficients and the same plant. Compare the absolute value of the largest pole with the sequence of sampled displacements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21c2f6a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "gains=np.linspace(0,1.15*(1+a)/b,260)\n",
    "spectral=[np.max(np.abs(np.roots([1,-a,b*k]))) for k in gains]\n",
    "fig,ax=plt.subplots(1,2,figsize=(9,3.5),layout=\"constrained\")\n",
    "times=np.arange(samples+1)*period\n",
    "ax[0].plot(times,direct,\".-\",ms=3,label=\"Immediate\")\n",
    "ax[0].plot(times,delayed,\".--\",ms=3,label=\"One sample late\")\n",
    "ax[0].set(xlabel=\"Time (s)\",ylabel=\"Sampled deviation\",title=\"Response from the same initial state\")\n",
    "ax[1].plot(gains,np.abs(a-b*gains),label=\"Immediate\")\n",
    "ax[1].plot(gains,spectral,\"--\",label=\"One sample late\")\n",
    "ax[1].axhline(1,color=\"0.5\",ls=\":\",label=\"Unit circle\")\n",
    "ax[1].set(xlabel=\"Positive gain K\",ylabel=\"Maximum pole modulus\",title=\"Discrete stability margin\")\n",
    "for p in ax:p.grid(alpha=.22);p.legend(fontsize=8)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11ece6bb",
   "metadata": {},
   "source": [
    "Set the gain between the two limits and compare the traces. Reduce the sample period by half while leaving the physical time constant unchanged; recompute the gain limits instead of simply reusing the original values. What would change if the delay were fixed in seconds rather than in samples?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
