{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tank series with feedback control\n",
    "\n",
    "Three equal, perfectly mixed tanks of volume $V$ are connected in series with the flow $q$. In\n",
    "each tank the reactant decays by a first-order reaction $A\\to B$ with the rate constant $k$:\n",
    "\n",
    "$$V\\,\\frac{dc_i}{dt} = q\\,(c_{i-1}-c_i) - k\\,V\\,c_i\n",
    "  \\quad\\Longleftrightarrow\\quad\n",
    "  \\tau\\,\\frac{dc_i}{dt} = G\\,c_{i-1}-c_i,\\qquad \\tau=\\frac{V}{q+kV},\\quad G=\\frac{q}{q+kV},$$\n",
    "\n",
    "so every tank is a first-order lag with time constant $\\tau$ and static gain $G<1$. A feedback\n",
    "controller measures the outlet $c_3$ and sets the inlet concentration $c_0$ of the first tank,\n",
    "for instance by dosing a concentrate into the feed.\n",
    "\n",
    "| block | law | value |\n",
    "|---|---|---|\n",
    "| tank $i$ | $\\tau\\dot c_i = G c_{i-1} - c_i$ | $V=2$ m³, $q=0.01$ m³/s, $k=0.005$ 1/s |\n",
    "| controller | $c_0 = K_p e + K_i\\int e\\,dt$, $\\;e=c_\\text{set}-c_3$ | $0 \\le c_0 \\le 20$ mol/m³ |\n",
    "\n",
    "The loop is integrated as a signal-flow graph with the classical Runge-Kutta method.\n",
    "\n",
    "**Reference.** With proportional control the closed loop has the transfer function\n",
    "$K_pG^3/\\big((\\tau s+1)^3+K_pG^3\\big)$; its step response is computed independently by\n",
    "`scipy.signal`, and its steady offset is $c_\\text{set}/(1+K_pG^3)$. The Routh criterion gives\n",
    "the ultimate gain $K_u = 8/G^3$, at which the loop oscillates with the period\n",
    "$P_u = 2\\pi\\tau/\\sqrt3$ (Seborg, Edgar, Mellichamp & Doyle, *Process Dynamics and Control*,\n",
    "chapter 11). Ziegler & Nichols (*Trans. ASME* 64, 1942) tune a PI controller from these two\n",
    "numbers: $K_p = 0.45\\,K_u$, $T_i = P_u/1.2$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import (\n",
    "    ControlSignalFlowConfiguration,\n",
    "    ControlSignalFlowPublicApi,\n",
    "    SignalBlock,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy import signal\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Plant data\n",
    "\n",
    "The three tank parameters give the time constant and gain of each lag, and from them the\n",
    "stability limit of the loop."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume, flow, rate, setpoint = 2.0, 0.01, 0.005, 1.0\n",
    "tau, G = volume / (flow + rate * volume), flow / (flow + rate * volume)\n",
    "ultimate_gain, ultimate_period = 8 / G**3, 2 * np.pi * tau / np.sqrt(3)\n",
    "print(\n",
    "    f\"tank time constant {tau:.1f} s, tank gain {G:.3f}; ultimate gain {ultimate_gain:.1f}, ultimate period {ultimate_period:.1f} s\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Proportional control\n",
    "\n",
    "The plant is one tuple of blocks, shared by all runs. The tanks start empty and the set point\n",
    "is 1 mol/m³. Four controller gains between a quarter of\n",
    "the ultimate gain and 10 % above it; the inlet concentration is not limited in these runs."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "plant = (\n",
    "    SignalBlock(\"dose\", \"gain\", inputs=(\"controller\",), parameters={\"gain\": G}),\n",
    "    SignalBlock(\n",
    "        \"tank1\", \"first_order\", inputs=(\"dose\",), parameters={\"time_constant\": tau}\n",
    "    ),\n",
    "    SignalBlock(\"into2\", \"gain\", inputs=(\"tank1\",), parameters={\"gain\": G}),\n",
    "    SignalBlock(\n",
    "        \"tank2\", \"first_order\", inputs=(\"into2\",), parameters={\"time_constant\": tau}\n",
    "    ),\n",
    "    SignalBlock(\"into3\", \"gain\", inputs=(\"tank2\",), parameters={\"gain\": G}),\n",
    "    SignalBlock(\n",
    "        \"tank3\", \"first_order\", inputs=(\"into3\",), parameters={\"time_constant\": tau}\n",
    "    ),\n",
    "    SignalBlock(\n",
    "        \"error\",\n",
    "        \"sum\",\n",
    "        inputs=(\"setpoint\", \"tank3\"),\n",
    "        parameters={\"weights\": (1.0, -1.0)},\n",
    "    ),\n",
    ")\n",
    "fractions = (0.25, 0.5, 0.95, 1.05)\n",
    "loop = lambda K: signal.lti(\n",
    "    [K * G**3],\n",
    "    np.polyadd(np.polymul(np.polymul([tau, 1], [tau, 1]), [tau, 1]), [K * G**3]),\n",
    ")\n",
    "proportional = {\n",
    "    f: ControlSignalFlowPublicApi().run(\n",
    "        ControlSignalFlowConfiguration(\n",
    "            parameters=dict(\n",
    "                blocks=plant\n",
    "                + (\n",
    "                    SignalBlock(\"setpoint\", \"constant\", parameters={\"value\": setpoint}),\n",
    "                    SignalBlock(\n",
    "                        \"controller\",\n",
    "                        \"pid\",\n",
    "                        inputs=(\"error\",),\n",
    "                        parameters={\"proportional_gain\": f * ultimate_gain},\n",
    "                    ),\n",
    "                ),\n",
    "                final_time=4000.0,\n",
    "                time_step=1.0,\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    for f in fractions\n",
    "}\n",
    "\n",
    "for f, run in proportional.items():\n",
    "    K = f * ultimate_gain\n",
    "    exact = setpoint * signal.step(loop(K), T=run.times)[1]\n",
    "    outlet = np.asarray(run.signals[\"tank3\"])\n",
    "    print(\n",
    "        f\"Kp = {f:4.2f} Ku: largest deviation from the exact step response {np.max(np.abs(outlet - exact)):.1e} mol/m^3\"\n",
    "        + (\n",
    "            f\", offset {setpoint - outlet[-1]:.5f} (exact {setpoint / (1 + K * G**3):.5f})\"\n",
    "            if f < 0.9\n",
    "            else \"\"\n",
    "        )\n",
    "    )\n",
    "for f in (0.95, 1.05):\n",
    "    times, outlet = np.asarray(proportional[f].times), np.asarray(\n",
    "        proportional[f].signals[\"tank3\"]\n",
    "    )\n",
    "    peaks = times[1:-1][(outlet[1:-1] > outlet[:-2]) & (outlet[1:-1] > outlet[2:])]\n",
    "    print(\n",
    "        f\"Kp = {f:4.2f} Ku: oscillation period {np.diff(peaks).mean():.1f} s, from the closed-loop poles {2 * np.pi / loop(f * ultimate_gain).poles.imag.max():.1f} s \"\n",
    "        f\"(ultimate period {ultimate_period:.1f} s)\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ziegler-Nichols PI control\n",
    "\n",
    "The PI controller removes the offset. Its output is limited to the physical range of the inlet\n",
    "concentration, with back-calculation against integrator wind-up. After 4000 s the set point is\n",
    "raised to 1.5 mol/m³. The tuning aims at a quarter decay ratio, so the response rings before it settles."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "Kp, Ti = 0.45 * ultimate_gain, ultimate_period / 1.2\n",
    "pi_run = ControlSignalFlowPublicApi().run(\n",
    "    ControlSignalFlowConfiguration(\n",
    "        parameters=dict(\n",
    "            blocks=plant\n",
    "            + (\n",
    "                SignalBlock(\n",
    "                    \"setpoint\",\n",
    "                    \"source\",\n",
    "                    source=lambda t: setpoint if t < 4000 else 1.5 * setpoint,\n",
    "                ),\n",
    "                SignalBlock(\n",
    "                    \"controller\",\n",
    "                    \"pid\",\n",
    "                    inputs=(\"error\",),\n",
    "                    parameters={\n",
    "                        \"proportional_gain\": Kp,\n",
    "                        \"integral_gain\": Kp / Ti,\n",
    "                        \"lower\": 0.0,\n",
    "                        \"upper\": 20.0,\n",
    "                        \"anti_windup\": \"back_calculation\",\n",
    "                        \"tracking_time\": Ti,\n",
    "                    },\n",
    "                ),\n",
    "            ),\n",
    "            final_time=8000.0,\n",
    "            time_step=1.0,\n",
    "            event_times=(4000.0,),\n",
    "        )\n",
    "    )\n",
    ")\n",
    "pi_times, pi_outlet = np.asarray(pi_run.times), np.asarray(pi_run.signals[\"tank3\"])\n",
    "print(\n",
    "    f\"PI controller Kp = {Kp:.2f}, Ti = {Ti:.1f} s: outlet at 4000 s {pi_outlet[pi_times <= 4000][-1]:.5f}, at 8000 s {pi_outlet[-1]:.5f} \"\n",
    "    f\"(set points 1.0 and 1.5); highest inlet concentration {np.max(pi_run.signals['controller']):.2f} mol/m^3\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Outlet concentration under proportional control against the exact response (a quarter of,\n",
    "half of and 5 % above the ultimate gain), the PI controlled outlet, and the inlet concentration\n",
    "the PI controller sets."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"Kp = {f} Ku\": (\n",
    "            np.asarray(run.times)[::40],\n",
    "            np.asarray(run.signals[\"tank3\"])[::40],\n",
    "        )\n",
    "        for f, run in proportional.items()\n",
    "        if f != 0.95\n",
    "    },\n",
    "    reference={\n",
    "        f\"Kp = {f} Ku\": (\n",
    "            run.times,\n",
    "            setpoint * signal.step(loop(f * ultimate_gain), T=run.times)[1],\n",
    "        )\n",
    "        for f, run in proportional.items()\n",
    "        if f != 0.95\n",
    "    },\n",
    "    hlines={\"set point\": setpoint},\n",
    "    xlimits=(0, 3000),\n",
    "    ylimits=(-0.3, 2.3),\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"outlet concentration c3 [mol/m3]\",\n",
    "    title=\"Proportional control, dashed: exact\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"outlet c3\": (pi_times, pi_run.signals[\"tank3\"])},\n",
    "    hlines={\"set point\": 1.0, \"new set point\": 1.5},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"concentration [mol/m3]\",\n",
    "    title=\"Ziegler-Nichols PI control\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"inlet concentration c0\": (pi_times, pi_run.signals[\"controller\"])},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"inlet concentration [mol/m3]\",\n",
    "    title=\"Controller output (limited to 20 mol/m3)\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add a transport delay between the controller and the first tank and watch the ultimate gain\n",
    "drop. Replace the PI controller by a sampled one (`sample_hold`) to see the effect of a slow\n",
    "analyser, or make the reaction rate in the tanks drift and test how robust the tuning is."
   ]
  }
 ]
}
