{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Proportional control of a first-order plant\n",
    "\n",
    "A first-order plant with the time constant $\\tau$ and the static gain $K$,\n",
    "\n",
    "$$\\tau\\,\\frac{dy}{dt}=-y+K\\,u,$$\n",
    "\n",
    "is driven by a proportional controller $u=K_p\\,(r-y)$ that compares the output\n",
    "$y$ with a constant setpoint $r$. OneSimulation builds the loop from signal\n",
    "blocks (setpoint, summing junction, controller, plant) and integrates the single\n",
    "continuous state with the classical fourth-order Runge-Kutta method.\n",
    "\n",
    "**Reference.** Substituting the control law gives another first-order system,\n",
    "so the closed-loop step response from rest is\n",
    "\n",
    "$$y(t)=y_\\infty\\left(1-e^{-t/\\tau_\\mathrm{cl}}\\right),\\qquad\n",
    "  y_\\infty=\\frac{K K_p}{1+K K_p}\\,r,\\qquad\n",
    "  \\tau_\\mathrm{cl}=\\frac{\\tau}{1+K K_p}.$$\n",
    "\n",
    "A proportional controller speeds the plant up by the factor $1+KK_p$ but leaves\n",
    "the steady-state offset $r-y_\\infty=r/(1+KK_p)$. Both facts are checked below."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import ControlSignalFlowProvider, SignalBlock\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters and model\n",
    "\n",
    "The parameters can be changed; the reference stays valid for any positive gains\n",
    "and time constant. The values describe a sluggish process (20 s time constant,\n",
    "gain 2) under a moderate proportional gain, so the offset remains clearly visible."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "time_constant = 20.0\n",
    "plant_gain = 2.0\n",
    "proportional_gain = 4.0\n",
    "setpoint = 1.0\n",
    "\n",
    "loop_gain = plant_gain * proportional_gain\n",
    "steady_output = loop_gain / (1.0 + loop_gain) * setpoint\n",
    "closed_loop_time_constant = time_constant / (1.0 + loop_gain)\n",
    "end_time = 6.0 * closed_loop_time_constant\n",
    "time_step = 0.01\n",
    "print(\n",
    "    f\"loop gain K*Kp = {loop_gain:.1f},  closed-loop time constant = {closed_loop_time_constant:.3f} s \"\n",
    "    f\"(open loop {time_constant:.1f} s),  steady output = {steady_output:.4f}\"\n",
    ")\n",
    "\n",
    "loop = ControlSignalFlowProvider(\n",
    "    blocks=(\n",
    "        SignalBlock(\"setpoint\", \"constant\", parameters={\"value\": setpoint}),\n",
    "        SignalBlock(\n",
    "            \"error\",\n",
    "            \"sum\",\n",
    "            inputs=(\"setpoint\", \"plant\"),\n",
    "            parameters={\"weights\": (1.0, -1.0)},\n",
    "        ),\n",
    "        SignalBlock(\n",
    "            \"controller\",\n",
    "            \"pid\",\n",
    "            inputs=(\"error\",),\n",
    "            parameters={\"proportional_gain\": proportional_gain},\n",
    "        ),\n",
    "        SignalBlock(\n",
    "            \"actuator\", \"gain\", inputs=(\"controller\",), parameters={\"gain\": plant_gain}\n",
    "        ),\n",
    "        SignalBlock(\n",
    "            \"plant\",\n",
    "            \"first_order\",\n",
    "            inputs=(\"actuator\",),\n",
    "            parameters={\"time_constant\": time_constant, \"initial_value\": 0.0},\n",
    "        ),\n",
    "    ),\n",
    "    final_time=end_time,\n",
    "    time_step=time_step,\n",
    "    time_integration=\"classical_rk4\",\n",
    ")\n",
    "run = loop.execute()\n",
    "times = np.asarray(run.times)\n",
    "outputs = np.asarray(run.signals[\"plant\"])\n",
    "commands = np.asarray(run.signals[\"controller\"])\n",
    "print(\"evaluation order:\", \" -> \".join(run.evaluation_order))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form solution\n",
    "\n",
    "The closed-loop exponential is evaluated at every stored time, the closed-loop\n",
    "time constant is fitted to the simulated approach, and the control law is\n",
    "verified sample by sample. A passing check shows that this numerical example\n",
    "agrees with the linear loop equations; it is not a measurement of a real process."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "reference = steady_output * (1.0 - np.exp(-times / closed_loop_time_constant))\n",
    "max_output_error = float(np.max(np.abs(outputs - reference)))\n",
    "print(\n",
    "    f\"Maximum output error against the closed-loop exponential: {max_output_error:.3e}\"\n",
    ")\n",
    "\n",
    "\n",
    "approach = steady_output - outputs\n",
    "fitted_rate = -np.polyfit(times, np.log(approach), 1)[0]\n",
    "fitted_time_constant = 1.0 / fitted_rate\n",
    "print(\n",
    "    f\"Closed-loop time constant: fitted {fitted_time_constant:.5f} s, exact {closed_loop_time_constant:.5f} s\"\n",
    ")\n",
    "final_offset = setpoint - outputs[-1]\n",
    "expected_offset = setpoint / (1.0 + loop_gain)\n",
    "print(\n",
    "    f\"Steady-state offset: simulated {final_offset:.5f}, exact r/(1+K Kp) = {expected_offset:.5f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "dense_t = np.linspace(0.0, end_time, 400)\n",
    "fig = plots.figure(2, 1, size=(8, 7))\n",
    "plots.line(\n",
    "    times,\n",
    "    points={\"OneSimulation RK4\": (times[::10], outputs[::10])},\n",
    "    reference={\n",
    "        \"exact step response\": (\n",
    "            dense_t,\n",
    "            steady_output * (1.0 - np.exp(-dense_t / closed_loop_time_constant)),\n",
    "        )\n",
    "    },\n",
    "    hlines={\"setpoint r\": setpoint, \"steady state K Kp r / (1 + K Kp)\": steady_output},\n",
    "    vlines={\"closed-loop time constant\": closed_loop_time_constant},\n",
    "    ylabel=\"plant output y\",\n",
    "    title=\"First-order plant under proportional control\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times,\n",
    "    {\"controller output u = Kp (r - y)\": commands},\n",
    "    hlines={\"steady state Kp r / (1 + K Kp)\": proportional_gain * expected_offset},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"control signal u\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise `proportional_gain` and the offset shrinks as $1/(1+KK_p)$ while the loop\n",
    "becomes faster; it can never vanish with proportional action alone. Add an\n",
    "`integral_gain` to the controller block and the offset disappears, but the loop\n",
    "becomes second order and may overshoot; derive the new characteristic equation\n",
    "$\\tau s^2+(1+KK_p)s+KK_i=0$ before adapting the checks. A `saturation` block\n",
    "between controller and actuator or a `transport_delay` in the feedback path\n",
    "turns the example into the standard anti-windup and dead-time studies."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
