{
 "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": [
    "# Estimating Arrhenius parameters from isothermal experiments\n",
    "\n",
    "The thermal decomposition of benzenediazonium chloride in water,\n",
    "\n",
    "$$\\mathrm{C_6H_5N_2Cl}+\\mathrm{H_2O}\\;\\longrightarrow\\;\\mathrm{C_6H_5OH}+\\mathrm{N_2}+\\mathrm{HCl},$$\n",
    "\n",
    "is a classical first-order reaction: the nitrogen it releases makes the conversion\n",
    "easy to follow. In a batch experiment at the temperature $T$ the diazonium\n",
    "concentration decays as\n",
    "\n",
    "$$\\frac{dc}{dt}=-k(T)\\,c,\\qquad k(T)=k_\\mathrm{ref}\\exp\\!\\Big[-\\frac{E_a}{R}\\Big(\\frac1T-\\frac1{T_\\mathrm{ref}}\\Big)\\Big].$$\n",
    "\n",
    "Writing the Arrhenius law around a reference temperature $T_\\mathrm{ref}$ in the middle\n",
    "of the experiments decouples the two parameters $k_\\mathrm{ref}$ and $E_a$, which makes\n",
    "the estimation well conditioned.\n",
    "\n",
    "OneSimulation solves each experiment as a homogeneous reaction network\n",
    "(`ReactionKinetics`, classical Runge-Kutta). The `SimulationStudyService` wraps the five\n",
    "simulations into one study, and its `fit` turns them into a least-squares problem: for a\n",
    "trial pair $(k_\\mathrm{ref},E_a)$ it runs all five experiments, forms the residuals\n",
    "$\\big(c_\\mathrm{sim}(t_j)-c_\\mathrm{data}(t_j)\\big)/s$ and minimises their sum of squares\n",
    "$\\chi^2$ with the Levenberg-Marquardt method. It returns the estimates with their\n",
    "linearised covariance in physical units.\n",
    "\n",
    "**Reference.** The data are synthetic: they are generated by OneSimulation itself from\n",
    "chosen \"true\" values, $k_\\mathrm{ref}=1.0\\times10^{-3}$ 1/s at 50 °C and\n",
    "$E_a=115$ kJ/mol, of the order reported for this reaction, with normally distributed\n",
    "noise of standard deviation $s=0.05$ mol/m³ (0.5 % of the initial 10 mol/m³). A\n",
    "correct estimation must recover the true values within the uncertainty that this\n",
    "noise allows and leave residuals of the size of the noise, $\\chi^2\\approx N-2$\n",
    "(Y. Bard, *Nonlinear Parameter Estimation*, Academic Press 1974; on the reaction:\n",
    "E. A. Moelwyn-Hughes, *The Kinetics of Reactions in Solution*, Oxford 1947)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.cad.geometry import LumpedDomain\n",
    "from onesim.meshing import LumpedMesh\n",
    "from onesim.numerics import Numerics\n",
    "from onesim.numerics.discretization import LumpedParameters\n",
    "from onesim.numerics.time import ClassicalRungeKutta4\n",
    "from onesim.physics.chemistry import (\n",
    "    ReactionIR,\n",
    "    ReactionKinetics,\n",
    "    ReactionNetworkIR,\n",
    "    SpeciesIR,\n",
    ")\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.simulation.studies import SimulationStudyService, StudyParameter\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Experiments and model\n",
    "\n",
    "Five isothermal experiments from 40 °C to 60 °C, one hour each, with twelve samples\n",
    "every five minutes. `experiments(values)` builds the five reaction models for one\n",
    "parameter pair, `run(models)` integrates them and samples the diazonium concentration."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "gas, reference_temperature, initial, noise = 8.314462618, 323.15, 10.0, 0.05\n",
    "temperatures = (313.15, 318.15, 323.15, 328.15, 333.15)\n",
    "samples = np.linspace(300.0, 3600.0, 12)\n",
    "cell = LumpedDomain()\n",
    "experiments = lambda values: {\n",
    "    T: ReactionKinetics(\n",
    "        domain=cell.system,\n",
    "        temperature=T,\n",
    "        network=ReactionNetworkIR(\n",
    "            \"diazonium_decomposition\",\n",
    "            \"1\",\n",
    "            species=(\n",
    "                SpeciesIR(\"diazonium\", 0, 1e-27, composition={\"H\": 1}),\n",
    "                SpeciesIR(\"products\", 0, 1e-27, composition={\"H\": 1}),\n",
    "            ),\n",
    "            reactions=(\n",
    "                ReactionIR(\n",
    "                    \"decomposition\",\n",
    "                    {\"diazonium\": 1},\n",
    "                    {\"products\": 1},\n",
    "                    {\n",
    "                        \"kind\": \"arrhenius\",\n",
    "                        \"activation_energy\": 1e3 * values[\"activation_energy\"],\n",
    "                        \"boltzmann_constant\": gas,\n",
    "                        \"pre_exponential\": values[\"k_ref\"]\n",
    "                        * np.exp(\n",
    "                            1e3\n",
    "                            * values[\"activation_energy\"]\n",
    "                            / (gas * reference_temperature)\n",
    "                        ),\n",
    "                    },\n",
    "                ),\n",
    "            ),\n",
    "            strict_balance=True,\n",
    "        ),\n",
    "    )\n",
    "    for T in temperatures\n",
    "}\n",
    "run = lambda models: {\n",
    "    T: np.interp(\n",
    "        samples,\n",
    "        *Simulation(\n",
    "            problem=Problem(\n",
    "                name=f\"Batch decomposition at {T - 273.15:.0f} °C\",\n",
    "                geometry=cell,\n",
    "                physics=(model,),\n",
    "                initial_conditions=(\n",
    "                    InitialValue(model.concentration(\"diazonium\"), initial),\n",
    "                    InitialValue(model.concentration(\"products\"), 0.0),\n",
    "                ),\n",
    "            ),\n",
    "            mesh=LumpedMesh(cell),\n",
    "            numerics=Numerics(\n",
    "                spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "            ),\n",
    "        )\n",
    "        .run(start_time=0.0, end_time=3600.0, time_step=20.0)\n",
    "        .field(model.concentration(\"diazonium\"))\n",
    "        .time_series(),\n",
    "    )\n",
    "    for T, model in models.items()\n",
    "}\n",
    "study = SimulationStudyService(\n",
    "    (\n",
    "        StudyParameter(\"k_ref\", 1e-4, 1e-2),\n",
    "        StudyParameter(\"activation_energy\", 60.0, 180.0),\n",
    "    ),\n",
    "    experiments,\n",
    "    lambda computed: {\n",
    "        f\"{T}_{j}\": c for T in temperatures for j, c in enumerate(computed[T])\n",
    "    },\n",
    "    solve=run,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Synthetic measurements\n",
    "\n",
    "The true parameters are run once and normally distributed noise is added (fixed seed,\n",
    "so the notebook is reproducible)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "true = {\"k_ref\": 1.0e-3, \"activation_energy\": 115.0}\n",
    "clean = study.sweep(combinations=[true]).runs[0].measurements\n",
    "rng = np.random.default_rng(2026)\n",
    "data = {key: value + rng.normal(0.0, noise) for key, value in clean.items()}\n",
    "print(\n",
    "    f\"{len(temperatures)} experiments x {samples.size} samples = {len(data)} data points, noise s = {noise} mol/m³\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Least-squares fit\n",
    "\n",
    "Bounds: $k_\\mathrm{ref}$ between $10^{-4}$ and $10^{-2}$ 1/s, $E_a$ between 60 and 180 kJ/mol.\n",
    "Levenberg-Marquardt starts far from the truth, at $k_\\mathrm{ref}=3\\times10^{-4}$ 1/s and\n",
    "$E_a=80$ kJ/mol."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fit = study.fit(\n",
    "    residuals=lambda m: np.array([(m[key] - data[key]) / noise for key in data]),\n",
    "    start={\"k_ref\": 3e-4, \"activation_energy\": 80.0},\n",
    "    method=\"levenberg_marquardt\",\n",
    "    maximum_runs=100,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the true values\n",
    "\n",
    "Standard errors from the linearised covariance, scaled with the residual variance."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "print(\n",
    "    f\"{fit.run_count} study runs ({len(temperatures) * fit.run_count} kinetic 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            estimate ± standard error        true        deviation\")\n",
    "for name, unit, scale in ((\"k_ref\", \"1/ks\", 1e3), (\"activation_energy\", \"kJ/mol\", 1.0)):\n",
    "    print(\n",
    "        f\"{name:18s} {scale * fit.parameters[name]:10.4f} ± {scale * fit.standard_errors[name]:.4f} {unit:6s} {scale * true[name]:9.3f}   \"\n",
    "        f\"{(fit.parameters[name] - true[name]) / fit.standard_errors[name]:+6.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",
    "    f\"rms residual {noise * np.sqrt(np.mean(fit.residuals ** 2)):.4f} mol/m³ (noise {noise})\"\n",
    ")\n",
    "print(\n",
    "    f\"χ² at the true values exceeds the minimum by Δχ² = {sum(((clean[k] - data[k]) / noise) ** 2 for k in data) - fit.residuals @ fit.residuals:.1f} \"\n",
    "    f\"(joint regions of two parameters: 68 % Δχ² < 2.30, 95 % < 5.99, 99 % < 9.21)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The estimates scatter around the truth by their standard errors. For this noise\n",
    "realisation the true pair lies just outside the joint 95 % confidence region and inside\n",
    "the 99 % region, as happens for about one data set in fifty; another seed gives another,\n",
    "equally valid data set and estimate.\n",
    "\n",
    "## Figure\n",
    "\n",
    "The five experiments with the fitted model; every parameter pair the fit ran (including\n",
    "the finite-difference probes); and the Arrhenius plot."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fitted = study.sweep(combinations=[dict(fit.parameters)]).runs[0].measurements\n",
    "path = np.array(\n",
    "    [\n",
    "        [r.parameters[\"activation_energy\"], r.parameters[\"k_ref\"]]\n",
    "        for r in fit.runs\n",
    "        if dict(r.parameters) != true\n",
    "    ]\n",
    ")\n",
    "inverse = np.linspace(1 / 335.0, 1 / 311.0, 50)\n",
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{T - 273.15:.0f} °C\": (\n",
    "            samples / 60,\n",
    "            np.array([data[f\"{T}_{j}\"] for j in range(samples.size)]),\n",
    "        )\n",
    "        for T in temperatures\n",
    "    },\n",
    "    reference={\n",
    "        f\"{T - 273.15:.0f} °C\": (\n",
    "            samples / 60,\n",
    "            np.array([fitted[f\"{T}_{j}\"] for j in range(samples.size)]),\n",
    "        )\n",
    "        for T in temperatures\n",
    "    },\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"diazonium concentration [mol/m³]\",\n",
    "    title=\"Data and fitted model (dashed)\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"trial points\": (path[:, 0], 1e3 * path[:, 1])},\n",
    "    points={\"true values\": (np.array([115.0]), np.array([1.0]))},\n",
    "    markers=True,\n",
    "    scale=\"logy\",\n",
    "    xlabel=\"activation energy E_a [kJ/mol]\",\n",
    "    ylabel=\"k_ref at 50 °C [1/ks]\",\n",
    "    title=\"Path of the fit\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"fitted model\": (\n",
    "            1e3 / np.array(temperatures),\n",
    "            np.log(fit.parameters[\"k_ref\"])\n",
    "            - 1e3\n",
    "            * fit.parameters[\"activation_energy\"]\n",
    "            / gas\n",
    "            * (1 / np.array(temperatures) - 1 / reference_temperature),\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"true Arrhenius law\": (\n",
    "            1e3 * inverse,\n",
    "            np.log(true[\"k_ref\"])\n",
    "            - 1e3\n",
    "            * true[\"activation_energy\"]\n",
    "            / gas\n",
    "            * (inverse - 1 / reference_temperature),\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"1000 / T [1/K]\",\n",
    "    ylabel=\"ln k [k in 1/s]\",\n",
    "    title=\"Arrhenius plot\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Halve the noise and the standard deviations halve; drop the 40 °C and 60 °C experiments\n",
    "and watch $E_a$ become much less certain while $k_\\mathrm{ref}$ hardly changes, the\n",
    "reason for spreading experiments over a wide temperature range. Real data, for example\n",
    "nitrogen volumes read from a gas burette, replace the synthetic `data` dictionary\n",
    "directly; the measured volume is proportional to the converted amount\n",
    "$c_0-c(t)$."
   ]
  }
 ]
}
