{
 "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": [
    "# Stirred tank reactors in series with level control\n",
    "\n",
    "Fermenters and many liquid-phase reactors are ideally mixed tanks whose liquid volume is not fixed:\n",
    "feeds and withdrawals change the filling, and a level controller keeps it within limits. Two tanks\n",
    "with the same cross-section $S=10$ m$^2$ are connected in series. Tank 1 receives a feed with\n",
    "reactant A, tank 2 the transfer stream from tank 1 and a second, fresh feed; the product leaves tank 2.\n",
    "In both tanks A turns into B by a first-order reaction, $r=k\\,c_A$.\n",
    "\n",
    "For every tank the volume, the moles of each species and the level $h=V/S$ follow from the balances\n",
    "\n",
    "$$\\frac{dV}{dt}=\\sum q_\\text{in}-\\sum q_\\text{out},\\qquad\n",
    "  \\frac{d(Vc_i)}{dt}=\\sum q_\\text{in}c_{i,\\text{in}}-\\Big(\\sum q_\\text{out}\\Big)c_i+\\nu_i\\,k\\,c_A\\,V .$$\n",
    "\n",
    "OneSimulation integrates them with `ProcessUnit(..., dynamic_volume=True, cross_section_area=S)`;\n",
    "a `ProcessStream` whose flow is a function of the current state can read the levels, which is how a\n",
    "controller is attached.\n",
    "\n",
    "| stream | from → to | phase 1: filling | phase 2: level control |\n",
    "|---|---|---|---|\n",
    "| feed | → tank 1, $c_A=8$ mol/m³ | 1.0 m³/min | 1.0 m³/min |\n",
    "| transfer | tank 1 → tank 2 | 0.9 m³/min | $q_{b1}+K_1(h_1-h_{s1})$ |\n",
    "| fresh feed | → tank 2, $c_A=3$ mol/m³ | 0.5 m³/min | 0.5 m³/min |\n",
    "| product | tank 2 → | 1.0 m³/min | $q_{b2}+K_2(h_2-h_{s2})$ |\n",
    "\n",
    "Phase 1 starts from 1 m³ and 1.5 m³ of pure solvent and lasts two hours; phase 2 starts from its end\n",
    "state. The rate constant is $k=0.37$ 1/min.\n",
    "\n",
    "**Reference** (O. Levenspiel, *Chemical Reaction Engineering*, 3rd ed., Wiley 1999, ch. 5 and 6;\n",
    "D. E. Seborg, T. F. Edgar, D. A. Mellichamp and F. J. Doyle, *Process Dynamics and Control*, 4th ed.,\n",
    "Wiley 2016, §2.4, §4 and §11.3). With fixed flows the volumes grow linearly, and the total\n",
    "concentration $s=c_A+c_B$ in tank 1, untouched by the reaction, has the closed form\n",
    "\n",
    "$$V_j(t)=V_j(0)+\\Big(\\sum q_\\text{in}-\\sum q_\\text{out}\\Big)_j\\,t,\\qquad\n",
    "  s_1(t)=c_{A,\\text{feed}}\\Big[1-\\Big(\\frac{V_1(0)}{V_1(t)}\\Big)^{q_\\text{feed}/(q_\\text{feed}-q_\\text{transfer})}\\Big].$$\n",
    "\n",
    "Under proportional control tank 1 is a first-order system with time constant $\\tau_1=S/K_1$ that\n",
    "settles with the offset $(q_\\text{feed}-q_{b1})/K_1$ above its set point; tank 2 is driven by it and\n",
    "responds with two exponentials:\n",
    "\n",
    "$$h_1=h_{1\\infty}+\\Delta_1e^{-K_1t/S},\\qquad\n",
    "  h_2=h_{2\\infty}+(\\Delta_2-\\beta)\\,e^{-K_2t/S}+\\beta\\,e^{-K_1t/S},\\qquad \\beta=\\frac{K_1\\Delta_1}{K_2-K_1},$$\n",
    "\n",
    "with $h_{1\\infty}=h_{s1}+(q_\\text{feed}-q_{b1})/K_1$, $h_{2\\infty}=h_{s2}+(q_\\text{feed}+q_\\text{fresh}-q_{b2})/K_2$ and\n",
    "the initial distances $\\Delta_j$ from them. At steady state each tank is a CSTR,\n",
    "$c_{A1}=q_\\text{feed}c_{A,\\text{feed}}/(q_\\text{feed}+kV_1)$ and\n",
    "$c_{A2}=(q_\\text{feed}c_{A1}+q_\\text{fresh}c_{A,\\text{fresh}})/(q_\\text{feed}+q_\\text{fresh}+kV_2)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import ProcessModelsProvider, ProcessStream, ProcessUnit\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.integrate import cumulative_trapezoid\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Phase 1: filling with fixed flows\n",
    "\n",
    "Flows in m³/s, times in s. The reaction law returns the production rate of each species and the heat\n",
    "released (none here). `bind_provider_parameters` selects the classical fourth-order Runge-Kutta method\n",
    "for the balances."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "minute = 60.0\n",
    "area, k, feed_a, fresh_a = 10.0, 0.37 / minute, 8.0, 3.0\n",
    "feed, transfer, fresh, product = 1.0 / minute, 0.9 / minute, 0.5 / minute, 1.0 / minute\n",
    "rk4 = ProcessModelsProvider.bind_provider_parameters(\n",
    "    {\"time_integration\": \"classical_rk4\"}\n",
    ")\n",
    "reaction = lambda c, temperature, time: ({\"A\": -k * c[\"A\"], \"B\": k * c[\"A\"]}, 0.0)\n",
    "filling = ProcessModelsProvider(\n",
    "    component_ids=(\"A\", \"B\"),\n",
    "    units=(\n",
    "        ProcessUnit(\n",
    "            \"tank1\",\n",
    "            volume=1.0,\n",
    "            initial_concentrations={\"A\": 0.0, \"B\": 0.0},\n",
    "            reaction_law=reaction,\n",
    "            dynamic_volume=True,\n",
    "            cross_section_area=area,\n",
    "        ),\n",
    "        ProcessUnit(\n",
    "            \"tank2\",\n",
    "            volume=1.5,\n",
    "            initial_concentrations={\"A\": 0.0, \"B\": 0.0},\n",
    "            reaction_law=reaction,\n",
    "            dynamic_volume=True,\n",
    "            cross_section_area=area,\n",
    "        ),\n",
    "    ),\n",
    "    streams=(\n",
    "        ProcessStream(\"feed\", None, \"tank1\", feed, {\"A\": feed_a}),\n",
    "        ProcessStream(\"transfer\", \"tank1\", \"tank2\", transfer),\n",
    "        ProcessStream(\"fresh\", None, \"tank2\", fresh, {\"A\": fresh_a}),\n",
    "        ProcessStream(\"product\", \"tank2\", None, product),\n",
    "    ),\n",
    "    final_time=120 * minute,\n",
    "    time_step=3.0,\n",
    "    **rk4,\n",
    ").execute()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The volumes against the linear closed form, the total concentration in tank 1 against $s_1(t)$, and\n",
    "the mole balance of the plant: moles in both tanks plus moles that left with the product must equal\n",
    "the moles fed."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "t = filling.times\n",
    "c1, c2 = filling.concentrations[\"tank1\"], filling.concentrations[\"tank2\"]\n",
    "V1, V2 = filling.volumes[\"tank1\"], filling.volumes[\"tank2\"]\n",
    "exact_V1, exact_V2 = 1.0 + (feed - transfer) * t, 1.5 + (fresh + transfer - product) * t\n",
    "exact_s1 = feed_a * (1 - (1.0 / exact_V1) ** (feed / (feed - transfer)))\n",
    "inventory = V1 * (c1[\"A\"] + c1[\"B\"]) + V2 * (c2[\"A\"] + c2[\"B\"])\n",
    "left = cumulative_trapezoid(\n",
    "    filling.flows[\"product\"] * (c2[\"A\"] + c2[\"B\"]), t, initial=0.0\n",
    ")\n",
    "fed = (feed * feed_a + fresh * fresh_a) * t\n",
    "print(\n",
    "    f\"after 2 h: V1 = {V1[-1]:.4f} m³ (closed form {exact_V1[-1]:.4f}), V2 = {V2[-1]:.4f} m³ (closed form {exact_V2[-1]:.4f}); \"\n",
    "    f\"largest volume deviation {max(np.abs(V1 - exact_V1).max(), np.abs(V2 - exact_V2).max()):.1e} m³\"\n",
    ")\n",
    "print(\n",
    "    f\"levels after 2 h: h1 = {filling.levels['tank1'][-1]:.3f} m, h2 = {filling.levels['tank2'][-1]:.3f} m\"\n",
    ")\n",
    "print(\n",
    "    f\"total concentration in tank 1 against the closed form: largest deviation {np.abs(c1['A'] + c1['B'] - exact_s1).max():.1e} mol/m³ \"\n",
    "    f\"(final value {exact_s1[-1]:.4f} mol/m³)\"\n",
    ")\n",
    "print(\n",
    "    f\"mole balance: {fed[-1]:.1f} mol fed, {inventory[-1]:.1f} mol in the tanks, {left[-1]:.1f} mol left with the product; \"\n",
    "    f\"largest relative imbalance {np.abs(inventory + left - fed)[1:].max() / fed[-1]:.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Phase 2: proportional level control\n",
    "\n",
    "The transfer and the product valves now follow proportional laws of the current levels. Both tanks\n",
    "start from the end of phase 1."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "setpoint_1, setpoint_2, bias_1, bias_2 = 1.0, 2.0, 0.9 / minute, 1.0 / minute\n",
    "gain_1, gain_2 = 5.0 / minute, 2.5 / minute\n",
    "controlled = ProcessModelsProvider(\n",
    "    component_ids=(\"A\", \"B\"),\n",
    "    units=tuple(\n",
    "        ProcessUnit(\n",
    "            name,\n",
    "            volume=filling.volumes[name][-1],\n",
    "            initial_concentrations={\n",
    "                s: filling.concentrations[name][s][-1] for s in \"AB\"\n",
    "            },\n",
    "            reaction_law=reaction,\n",
    "            dynamic_volume=True,\n",
    "            cross_section_area=area,\n",
    "        )\n",
    "        for name in (\"tank1\", \"tank2\")\n",
    "    ),\n",
    "    streams=(\n",
    "        ProcessStream(\"feed\", None, \"tank1\", feed, {\"A\": feed_a}),\n",
    "        ProcessStream(\n",
    "            \"transfer\",\n",
    "            \"tank1\",\n",
    "            \"tank2\",\n",
    "            lambda state, time: bias_1 + gain_1 * (state.levels[\"tank1\"] - setpoint_1),\n",
    "        ),\n",
    "        ProcessStream(\"fresh\", None, \"tank2\", fresh, {\"A\": fresh_a}),\n",
    "        ProcessStream(\n",
    "            \"product\",\n",
    "            \"tank2\",\n",
    "            None,\n",
    "            lambda state, time: bias_2 + gain_2 * (state.levels[\"tank2\"] - setpoint_2),\n",
    "        ),\n",
    "    ),\n",
    "    final_time=60 * minute,\n",
    "    time_step=1.0,\n",
    "    **rk4,\n",
    ").execute()\n",
    "\n",
    "tc = controlled.times\n",
    "h1, h2 = controlled.levels[\"tank1\"], controlled.levels[\"tank2\"]\n",
    "steady_1, steady_2 = (\n",
    "    setpoint_1 + (feed - bias_1) / gain_1,\n",
    "    setpoint_2 + (feed + fresh - bias_2) / gain_2,\n",
    ")\n",
    "delta_1, delta_2 = h1[0] - steady_1, h2[0] - steady_2\n",
    "beta = gain_1 * delta_1 / (gain_2 - gain_1)\n",
    "exact_h1 = steady_1 + delta_1 * np.exp(-gain_1 * tc / area)\n",
    "exact_h2 = (\n",
    "    steady_2\n",
    "    + (delta_2 - beta) * np.exp(-gain_2 * tc / area)\n",
    "    + beta * np.exp(-gain_1 * tc / area)\n",
    ")\n",
    "cstr_1 = feed * feed_a / (feed + k * area * steady_1)\n",
    "cstr_2 = (feed * cstr_1 + fresh * fresh_a) / (feed + fresh + k * area * steady_2)\n",
    "print(\n",
    "    f\"level response: largest deviation from the closed form {np.abs(h1 - exact_h1).max():.1e} m (tank 1), \"\n",
    "    f\"{np.abs(h2 - exact_h2).max():.1e} m (tank 2); time constants {area / gain_1 / minute:.0f} and {area / gain_2 / minute:.0f} min\"\n",
    ")\n",
    "print(\"                          simulation (1 h)   controller law / CSTR   deviation\")\n",
    "for name, value, exact in (\n",
    "    (\"level tank 1 [m]\", h1[-1], steady_1),\n",
    "    (\"level tank 2 [m]\", h2[-1], steady_2),\n",
    "    (\"c_A tank 1 [mol/m³]\", controlled.concentrations[\"tank1\"][\"A\"][-1], cstr_1),\n",
    "    (\"c_A tank 2 [mol/m³]\", controlled.concentrations[\"tank2\"][\"A\"][-1], cstr_2),\n",
    "    (\n",
    "        \"product flow [m³/min]\",\n",
    "        minute * controlled.flows[\"product\"][-1],\n",
    "        minute * (feed + fresh),\n",
    "    ),\n",
    "):\n",
    "    print(\n",
    "        f\"{name:24s} {value:16.5f} {exact:22.5f} {100 * (value / exact - 1):+11.4f} %\"\n",
    "    )\n",
    "print(\n",
    "    f\"offset of proportional control: tank 1 settles {100 * (steady_1 - setpoint_1):.0f} cm, tank 2 {100 * (steady_2 - setpoint_2):.0f} cm above its set point\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Top: phase 1, the growing volumes with their closed form and the concentrations in both tanks. Bottom:\n",
    "phase 2, the levels drawn down by the controllers to their steady values above the set points, and the\n",
    "concentrations of A settling at the CSTR values."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(2, 2, size=(14, 9))\n",
    "plots.line(\n",
    "    t / minute,\n",
    "    {\"tank 1\": V1, \"tank 2\": V2},\n",
    "    reference={\"tank 1\": exact_V1, \"tank 2\": exact_V2},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"liquid volume [m³]\",\n",
    "    title=\"Phase 1: filling (dashed: closed form)\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    t / minute,\n",
    "    {\n",
    "        \"A, tank 1\": c1[\"A\"],\n",
    "        \"B, tank 1\": c1[\"B\"],\n",
    "        \"A, tank 2\": c2[\"A\"],\n",
    "        \"B, tank 2\": c2[\"B\"],\n",
    "    },\n",
    "    reference={\"A + B in tank 1, closed form\": exact_s1},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"concentration [mol/m³]\",\n",
    "    title=\"Phase 1: concentrations\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    tc / minute,\n",
    "    {\"tank 1\": h1, \"tank 2\": h2},\n",
    "    reference={\"tank 1\": exact_h1, \"tank 2\": exact_h2},\n",
    "    hlines={\"set point tank 1\": setpoint_1, \"set point tank 2\": setpoint_2},\n",
    "    xlimits=(0, 30),\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"liquid level [m]\",\n",
    "    title=\"Phase 2: level control (dashed: closed form)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.line(\n",
    "    tc / minute,\n",
    "    {\n",
    "        \"A, tank 1\": controlled.concentrations[\"tank1\"][\"A\"],\n",
    "        \"A, tank 2\": controlled.concentrations[\"tank2\"][\"A\"],\n",
    "    },\n",
    "    hlines={\"CSTR steady state, tank 1\": cstr_1, \"CSTR steady state, tank 2\": cstr_2},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"concentration of A [mol/m³]\",\n",
    "    title=\"Phase 2: approach to the steady state\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[3],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add an integral part to the valve laws to remove the offset, or replace the proportional law by the\n",
    "blocks of `ControlSignalFlowProvider` (gain, sum, limiter) to model a valve that cannot open beyond\n",
    "its full stroke. A heat source and a temperature-dependent rate constant turn the tanks into a\n",
    "non-isothermal reactor cascade."
   ]
  }
 ]
}
