{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Consecutive reactions A -> B -> C\n",
    "\n",
    "A species $A$ reacts to an intermediate $B$, which in turn reacts to a final\n",
    "product $C$, in a homogeneous, well-mixed (0D) batch reactor:\n",
    "\n",
    "$$A \\xrightarrow{\\;k_1\\;} B \\xrightarrow{\\;k_2\\;} C .$$\n",
    "\n",
    "With first-order (mass-action) rate laws the homogeneous balances are\n",
    "\n",
    "$$\\frac{dC_A}{dt}=-k_1 C_A,\\quad\n",
    "  \\frac{dC_B}{dt}=k_1 C_A-k_2 C_B,\\quad\n",
    "  \\frac{dC_C}{dt}=k_2 C_B,$$\n",
    "\n",
    "with $C_A(0)=C_{A0}$, $C_B(0)=C_C(0)=0$. OneSimulation integrates the network\n",
    "on a lumped (0D) domain with an explicit classical Runge-Kutta scheme.\n",
    "\n",
    "**Reference.** For $k_1\\neq k_2$ the classical closed-form solution is\n",
    "\n",
    "$$C_A=C_{A0}e^{-k_1 t},\\quad\n",
    "  C_B=C_{A0}\\frac{k_1}{k_2-k_1}\\bigl(e^{-k_1 t}-e^{-k_2 t}\\bigr),\\quad\n",
    "  C_C=C_{A0}-C_A-C_B .$$\n",
    "\n",
    "The intermediate $C_B$ reaches a maximum at\n",
    "$t_{\\max}=\\dfrac{\\ln(k_2/k_1)}{k_2-k_1}$. We compare the transient and the peak."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "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.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The values are freely adjustable. With $k_1$ and $k_2$ of different size the\n",
    "intermediate $B$ builds up and then decays, giving a clear interior peak."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "k1 = 1.0\n",
    "k2 = 0.3\n",
    "C_A0 = 1.0\n",
    "\n",
    "t_peak = np.log(k2 / k1) / (k2 - k1)\n",
    "end_time = 6.0 / min(k1, k2)\n",
    "time_step = 0.02 / max(k1, k2)\n",
    "print(\n",
    "    f\"k1 = {k1:.3f} 1/s,  k2 = {k2:.3f} 1/s,  intermediate peak at t = {t_peak:.3f} s\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Three species ($A$, $B$, $C$) and two irreversible reactions with constant rate\n",
    "coefficients, in a single lumped control volume."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "network = ReactionNetworkIR(\n",
    "    \"consecutive_chain\",\n",
    "    \"1\",\n",
    "    species=(\n",
    "        SpeciesIR(\"A\", 0, 1e-27, composition={\"H\": 1}),\n",
    "        SpeciesIR(\"B\", 0, 1e-27, composition={\"H\": 1}),\n",
    "        SpeciesIR(\"C\", 0, 1e-27, composition={\"H\": 1}),\n",
    "    ),\n",
    "    reactions=(\n",
    "        ReactionIR(\"step1\", {\"A\": 1}, {\"B\": 1}, {\"kind\": \"constant\", \"value\": k1}),\n",
    "        ReactionIR(\"step2\", {\"B\": 1}, {\"C\": 1}, {\"kind\": \"constant\", \"value\": k2}),\n",
    "    ),\n",
    "    strict_balance=True,\n",
    ")\n",
    "\n",
    "domain = LumpedDomain()\n",
    "model = ReactionKinetics(domain=domain.system, temperature=300.0, network=network)\n",
    "C_A = model.concentration(\"A\")\n",
    "C_B = model.concentration(\"B\")\n",
    "C_C = model.concentration(\"C\")\n",
    "\n",
    "problem = Problem(\n",
    "    name=\"Consecutive reactions\",\n",
    "    geometry=domain,\n",
    "    physics=(model,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(C_A, C_A0),\n",
    "        InitialValue(C_B, 0.0),\n",
    "        InitialValue(C_C, 0.0),\n",
    "    ),\n",
    ")\n",
    "simulation = Simulation(\n",
    "    problem=problem,\n",
    "    mesh=LumpedMesh(domain),\n",
    "    numerics=Numerics(\n",
    "        spatial=LumpedParameters(),\n",
    "        time_integrator=ClassicalRungeKutta4(),\n",
    "    ),\n",
    ")\n",
    "simulation.validate().require_valid()\n",
    "result = simulation.run(start_time=0.0, end_time=end_time, time_step=time_step)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the series solution\n",
    "\n",
    "The stored concentration histories are compared, time by time, with the\n",
    "closed-form solution, and the intermediate peak is compared with its analytic\n",
    "height and position."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "times, num_A = result.field(C_A).time_series()\n",
    "_, num_B = result.field(C_B).time_series()\n",
    "_, num_C = result.field(C_C).time_series()\n",
    "\n",
    "exact_A = C_A0 * np.exp(-k1 * times)\n",
    "exact_B = C_A0 * k1 / (k2 - k1) * (np.exp(-k1 * times) - np.exp(-k2 * times))\n",
    "exact_C = C_A0 - exact_A - exact_B\n",
    "\n",
    "err = max(\n",
    "    float(np.max(np.abs(num_A - exact_A))),\n",
    "    float(np.max(np.abs(num_B - exact_B))),\n",
    "    float(np.max(np.abs(num_C - exact_C))),\n",
    ")\n",
    "rel_error = err / C_A0\n",
    "print(\n",
    "    f\"Maximum absolute error against the series: {err:.3e} mol/m^3\"\n",
    "    f\"  ({100 * rel_error:.4f} % of C_A0)\"\n",
    ")\n",
    "\n",
    "B_peak_exact = C_A0 * (k1 / k2) ** (k2 / (k2 - k1))\n",
    "i_peak = int(np.argmax(num_B))\n",
    "print(\n",
    "    f\"intermediate peak: numeric C_B_max = {num_B[i_peak]:.5f} at t = {times[i_peak]:.3f} s,\"\n",
    "    f\"  analytic C_B_max = {B_peak_exact:.5f} at t = {t_peak:.3f} s\"\n",
    ")\n",
    "\n",
    "mass_error = float(np.max(np.abs(num_A + num_B + num_C - C_A0)))\n",
    "print(f\"Maximum mass-balance error C_A+C_B+C_C-C_A0: {mass_error:.3e} mol/m^3\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "t_fine = np.linspace(0.0, end_time, 400)\n",
    "shown = slice(None, None, max(1, len(times) // 40))\n",
    "fine_A = C_A0 * np.exp(-k1 * t_fine)\n",
    "fine_B = C_A0 * k1 / (k2 - k1) * (np.exp(-k1 * t_fine) - np.exp(-k2 * t_fine))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"C_A\": (times[shown], num_A[shown]),\n",
    "        \"C_B\": (times[shown], num_B[shown]),\n",
    "        \"C_C\": (times[shown], num_C[shown]),\n",
    "    },\n",
    "    reference={\n",
    "        \"C_A\": (t_fine, fine_A),\n",
    "        \"C_B\": (t_fine, fine_B),\n",
    "        \"C_C\": (t_fine, C_A0 - fine_A - fine_B),\n",
    "    },\n",
    "    vlines={\"peak of C_B\": t_peak},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"concentration [mol/m^3]\",\n",
    "    title=\"Consecutive reactions: OneSimulation (markers) and exact solution (dashed)\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Bring $k_2$ close to $k_1$ and watch the intermediate peak grow and move later;\n",
    "at $k_2=k_1$ the series solution switches to its $t\\,e^{-kt}$ form. Make $k_2$\n",
    "much larger than $k_1$ to approach the quasi-steady-state limit in which $B$\n",
    "stays small and $C$ follows $A$'s decay directly."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
