{
 "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": [
    "# Parameter estimation for a non-ideal stirred reactor\n",
    "\n",
    "A stirred tank of volume $V=1$ m³ is fed with $q=1$ l/s of liquid, so its mean residence time is\n",
    "$\\tau=V/q=1000$ s. An ideal stirred tank would answer a tracer step at the inlet with\n",
    "$F(t)=1-e^{-t/\\tau}$. Real tanks deviate: corners, baffles and the region behind the impeller are\n",
    "poorly mixed. The classical **dead-zone model** splits the tank into a well-mixed zone of volume\n",
    "$\\alpha V$ and a dead zone of volume $(1-\\alpha)V$ that exchange the flow $\\beta q$:\n",
    "\n",
    "$$\\alpha V\\frac{dc_1}{dt}=q\\,(c_\\mathrm{in}-c_1)+\\beta q\\,(c_2-c_1),\\qquad\n",
    "  (1-\\alpha)V\\frac{dc_2}{dt}=\\beta q\\,(c_1-c_2).$$\n",
    "\n",
    "The outlet concentration is $c_1$. The tank responds faster than an ideal tank at first (only\n",
    "the active zone is flushed) and slower later (the dead zone empties slowly).\n",
    "\n",
    "OneSimulation builds the two balances as a signal-flow graph (two integrators fed by weighted\n",
    "sums) and integrates it with the classical Runge-Kutta method. The `SimulationStudyService`\n",
    "turns the model into a least-squares problem: `fit` runs the graph for trial values of\n",
    "$(\\alpha,\\beta)$, forms the residuals of the outlet response divided by the noise level and\n",
    "minimises their sum of squares with the Levenberg-Marquardt method; it returns the estimates\n",
    "with their linearised covariance. The best ideal tank is fitted the same way, with one\n",
    "first-order block.\n",
    "\n",
    "| quantity | value |\n",
    "|---|---|\n",
    "| tank volume $V$ | 1 m³ |\n",
    "| feed $q$ | 1 l/s |\n",
    "| tracer step | $c_\\mathrm{in}=1$ for $t>0$ |\n",
    "| samples | every 60 s over 4 h, 1 % measurement noise |\n",
    "\n",
    "The measurements in this notebook are **synthetic**: they are generated with $\\alpha=0.65$ and\n",
    "$\\beta=0.10$ and disturbed with random noise, so the fit can be judged against known values.\n",
    "\n",
    "**Reference.** Levenspiel, *Chemical Reaction Engineering*, 3rd ed., Ch. 12 (models for non-ideal\n",
    "flow, the dead-zone and exchange models); Fogler, *Elements of Chemical Reaction Engineering*,\n",
    "Ch. 18. The model is linear, $\\dot{\\mathbf c}=A\\,\\mathbf c+\\mathbf b$, and its step response is\n",
    "exactly $\\mathbf c(t)=\\bigl(I-e^{At}\\bigr)\\,\\mathbf 1$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.time import DEFAULT_TIME_INTEGRATOR_REGISTRY\n",
    "from onesim.physics.systems import ControlSignalFlowProvider, SignalBlock\n",
    "from onesim.simulation.studies import SimulationStudyService, StudyParameter\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.linalg import expm\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "`tank(values)` builds the signal-flow graph for one pair $(\\alpha,\\beta)$; the study runs it for\n",
    "four hours with steps of 5 s and reads the outlet at the sampling times."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "volume, feed = 1.0, 1e-3\n",
    "residence_time = volume / feed\n",
    "samples = np.arange(60.0, 4 * 3600.0 + 1, 60.0)\n",
    "rk4 = DEFAULT_TIME_INTEGRATOR_REGISTRY.resolve_id(\"classical_rk4\")\n",
    "tank = lambda values: ControlSignalFlowProvider(\n",
    "    blocks=(\n",
    "        SignalBlock(\"inlet\", \"constant\", parameters={\"value\": 1.0}),\n",
    "        SignalBlock(\"active\", \"integrator\", inputs=(\"d_active\",)),\n",
    "        SignalBlock(\"dead\", \"integrator\", inputs=(\"d_dead\",)),\n",
    "        SignalBlock(\n",
    "            \"d_active\",\n",
    "            \"sum\",\n",
    "            inputs=(\"inlet\", \"active\", \"dead\"),\n",
    "            parameters={\n",
    "                \"weights\": (\n",
    "                    feed / (values[\"alpha\"] * volume),\n",
    "                    -(1 + values[\"beta\"]) * feed / (values[\"alpha\"] * volume),\n",
    "                    values[\"beta\"] * feed / (values[\"alpha\"] * volume),\n",
    "                )\n",
    "            },\n",
    "        ),\n",
    "        SignalBlock(\n",
    "            \"d_dead\",\n",
    "            \"sum\",\n",
    "            inputs=(\"active\", \"dead\"),\n",
    "            parameters={\n",
    "                \"weights\": (\n",
    "                    values[\"beta\"] * feed / ((1 - values[\"alpha\"]) * volume),\n",
    "                    -values[\"beta\"] * feed / ((1 - values[\"alpha\"]) * volume),\n",
    "                )\n",
    "            },\n",
    "        ),\n",
    "    ),\n",
    "    final_time=samples[-1],\n",
    "    time_step=5.0,\n",
    "    time_integrator=rk4,\n",
    ")\n",
    "outlet = lambda run, block: {\n",
    "    f\"c_{i}\": c for i, c in enumerate(np.interp(samples, run.times, run.signals[block]))\n",
    "}\n",
    "study = SimulationStudyService(\n",
    "    (StudyParameter(\"alpha\", 0.05, 0.99), StudyParameter(\"beta\", 0.01, 5.0)),\n",
    "    tank,\n",
    "    lambda run: outlet(run, \"active\"),\n",
    "    solve=lambda graph: graph.execute(),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Synthetic experiment\n",
    "\n",
    "The exact response for the true parameters, disturbed with normally distributed noise of 1 % of\n",
    "the step height."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "true = {\"alpha\": 0.65, \"beta\": 0.10}\n",
    "exact = lambda t, a, b: np.array(\n",
    "    [\n",
    "        1\n",
    "        - (\n",
    "            expm(\n",
    "                np.array([[-(1 + b), b], [b * a / (1 - a), -b * a / (1 - a)]])\n",
    "                * feed\n",
    "                / (a * volume)\n",
    "                * s\n",
    "            )\n",
    "            @ np.ones(2)\n",
    "        )[0]\n",
    "        for s in np.atleast_1d(t)\n",
    "    ]\n",
    ")\n",
    "measured = exact(samples, *true.values()) + np.random.default_rng(7).normal(\n",
    "    0.0, 0.01, samples.size\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "First the signal-flow integration against the exact solution, then the least-squares fits of\n",
    "the dead-zone model (start $\\alpha=0.5$, $\\beta=0.5$) and of the ideal tank."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "simulated = study.sweep(combinations=[true]).runs[0].measurements\n",
    "print(\n",
    "    f\"time integration against the matrix exponential: largest deviation \"\n",
    "    f\"{np.abs(np.array([simulated[f'c_{i}'] for i in range(samples.size)]) - exact(samples, *true.values())).max():.1e}\"\n",
    ")\n",
    "fit = study.fit(\n",
    "    residuals=lambda m: np.array(\n",
    "        [(m[f\"c_{i}\"] - measured[i]) / 0.01 for i in range(samples.size)]\n",
    "    ),\n",
    "    start={\"alpha\": 0.5, \"beta\": 0.5},\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=100,\n",
    ")\n",
    "ideal = SimulationStudyService(\n",
    "    (StudyParameter(\"tau\", 100.0, 5000.0),),\n",
    "    lambda values: ControlSignalFlowProvider(\n",
    "        blocks=(\n",
    "            SignalBlock(\"inlet\", \"constant\", parameters={\"value\": 1.0}),\n",
    "            SignalBlock(\n",
    "                \"outlet\",\n",
    "                \"first_order\",\n",
    "                inputs=(\"inlet\",),\n",
    "                parameters={\"time_constant\": values[\"tau\"]},\n",
    "            ),\n",
    "        ),\n",
    "        final_time=samples[-1],\n",
    "        time_step=5.0,\n",
    "        time_integrator=rk4,\n",
    "    ),\n",
    "    lambda run: outlet(run, \"outlet\"),\n",
    "    solve=lambda graph: graph.execute(),\n",
    ").fit(\n",
    "    residuals=lambda m: np.array(\n",
    "        [(m[f\"c_{i}\"] - measured[i]) / 0.01 for i in range(samples.size)]\n",
    "    ),\n",
    "    start={\"tau\": residence_time},\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=50,\n",
    ")\n",
    "print(\n",
    "    f\"dead-zone fit: {fit.run_count} simulations, converged {fit.converged}, rank {fit.rank}, \"\n",
    "    f\"χ² = {fit.residuals @ fit.residuals:.1f} for {fit.degrees_of_freedom} degrees of freedom\"\n",
    ")\n",
    "print(\"parameter         true    estimate ± standard error   deviation\")\n",
    "for name, label in ((\"alpha\", \"active fraction\"), (\"beta\", \"exchange ratio\")):\n",
    "    print(\n",
    "        f\"{label:16s} {true[name]:6.3f} {fit.parameters[name]:10.4f} ± {fit.standard_errors[name]:.4f}       \"\n",
    "        f\"{(fit.parameters[name] - true[name]) / fit.standard_errors[name]:+5.2f} σ\"\n",
    "    )\n",
    "print(\n",
    "    f\"correlation of the two estimates {fit.covariance[0, 1] / np.sqrt(fit.covariance[0, 0] * fit.covariance[1, 1]):+.2f}\"\n",
    ")\n",
    "for name, result in ((\"dead-zone model\", fit), (\"ideal stirred tank\", ideal)):\n",
    "    print(\n",
    "        f\"{name:20s} rms residual {0.01 * np.sqrt(np.mean(result.residuals ** 2)):.4f}  (noise level 0.0100)\"\n",
    "    )\n",
    "print(\n",
    "    f\"best ideal tank: residence time {ideal.parameters['tau']:.0f} ± {ideal.standard_errors['tau']:.0f} s instead of V/q = {residence_time:.0f} s\"\n",
    ")\n",
    "print(\n",
    "    f\"well-mixed volume {fit.parameters['alpha'] * volume:.3f} m³, exchange flow {fit.parameters['beta'] * feed * 1e3:.3f} l/s\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The measured response with the fitted dead-zone model and the best ideal tank, the residuals of\n",
    "both models, and the sum of squared residuals over a grid of the two parameters (a sweep of the\n",
    "same study), whose minimum is the estimate."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "grid = SimulationStudyService(\n",
    "    (\n",
    "        StudyParameter(\"alpha\", 0.45, 0.85, values=tuple(np.linspace(0.45, 0.85, 13))),\n",
    "        StudyParameter(\"beta\", 0.02, 0.30, values=tuple(np.linspace(0.02, 0.30, 13))),\n",
    "    ),\n",
    "    tank,\n",
    "    lambda run: outlet(run, \"active\"),\n",
    "    solve=lambda graph: graph.execute(),\n",
    ").sweep()\n",
    "misfit = np.log10(\n",
    "    np.array(\n",
    "        [\n",
    "            np.sum(\n",
    "                (\n",
    "                    np.array([run.measurements[f\"c_{i}\"] for i in range(samples.size)])\n",
    "                    - measured\n",
    "                )\n",
    "                ** 2\n",
    "            )\n",
    "            for run in grid.runs\n",
    "        ]\n",
    "    ).reshape(13, 13)\n",
    ")\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    samples / 60,\n",
    "    {\n",
    "        \"dead-zone model, fitted\": measured + 0.01 * fit.residuals,\n",
    "        \"ideal stirred tank, fitted\": measured + 0.01 * ideal.residuals,\n",
    "    },\n",
    "    points={\"synthetic measurements\": (samples[::3] / 60, measured[::3])},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"outlet concentration / step height\",\n",
    "    title=\"Tracer step response\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"dead-zone model\": (samples / 60, 0.01 * fit.residuals),\n",
    "        \"ideal stirred tank\": (samples / 60, 0.01 * ideal.residuals),\n",
    "    },\n",
    "    hlines=0.0,\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"model - measured\",\n",
    "    title=\"Residuals\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.heatmap(\n",
    "    np.linspace(0.45, 0.85, 13),\n",
    "    np.linspace(0.02, 0.30, 13),\n",
    "    misfit,\n",
    "    contours=12,\n",
    "    label=\"log10(sum of squared residuals)\",\n",
    "    aspect=\"auto\",\n",
    "    xlabel=\"active fraction α\",\n",
    "    ylabel=\"exchange ratio β\",\n",
    "    title=\"Least-squares objective\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the step by a short tracer pulse and fit the residence-time distribution $E(t)$\n",
    "instead; add a bypass stream to the model (the Cholette-Cloutier model) and see whether the data\n",
    "can tell bypass and dead zone apart; or lower the noise and watch the standard errors shrink\n",
    "with its square root."
   ]
  }
 ]
}
