{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Second-order reaction 2A -> P\n",
    "\n",
    "A single species $A$ is consumed by an irreversible second-order reaction in a\n",
    "homogeneous, well-mixed (0D) batch reactor, two molecules of $A$ forming one\n",
    "product $P$:\n",
    "\n",
    "$$2A \\xrightarrow{\\;k\\;} P .$$\n",
    "\n",
    "With a mass-action rate law the reaction rate is $r=k\\,C_A^2$. Because each\n",
    "reaction event removes two molecules of $A$, the stoichiometry gives\n",
    "\n",
    "$$\\frac{dC_A}{dt}=-2\\,k\\,C_A^2,\\qquad \\frac{dC_P}{dt}=+k\\,C_A^2,\\qquad\n",
    "  C_A(0)=C_{A0},\\;\\; C_P(0)=0 .$$\n",
    "\n",
    "OneSimulation integrates the homogeneous species balance on a lumped (0D)\n",
    "domain with an explicit classical Runge-Kutta scheme; the rate coefficient is\n",
    "declared as a constant mass-action law in a reaction network, and the factor of\n",
    "two in $dC_A/dt$ comes from the reactant stoichiometry, not from the rate law.\n",
    "\n",
    "**Reference.** Separating variables in $dC_A/dt=-2kC_A^2$ gives the hyperbola\n",
    "\n",
    "$$\\frac{1}{C_A(t)}=\\frac{1}{C_{A0}}+2\\,k\\,t,\\qquad\\text{so}\\qquad\n",
    "  C_A(t)=\\frac{C_{A0}}{1+2\\,k\\,C_{A0}\\,t}.$$\n",
    "\n",
    "Mass is conserved as $C_A(t)+2\\,C_P(t)=C_{A0}$ (two $A$ per $P$). We compare the\n",
    "computed transient with this closed form."
   ]
  },
  {
   "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. The product $k\\,C_{A0}$ sets the\n",
    "characteristic time $1/(2kC_{A0})$; the window spans several of those times, so\n",
    "$A$ falls well below its initial value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "k = 0.5\n",
    "C_A0 = 2.0\n",
    "C_P0 = 0.0\n",
    "half_time = 1.0 / (2.0 * k * C_A0)\n",
    "end_time = 10.0 * half_time\n",
    "time_step = 0.02 * half_time\n",
    "print(\n",
    "    f\"k = {k:.3f} m^3/(mol s),  half-time 1/(2 k C_A0) = {half_time:.2f} s,  end time = {end_time:.2f} s\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Two species ($A$, $P$) and one irreversible reaction $2A\\to P$ with a constant\n",
    "(mass-action) rate coefficient. The element balance closes with $A$ carrying one\n",
    "unit of a fictitious element and $P$ carrying two. The reactor is a single\n",
    "lumped control volume."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "network = ReactionNetworkIR(\n",
    "    \"second_order_dimerization\",\n",
    "    \"1\",\n",
    "    species=(\n",
    "        SpeciesIR(\"A\", 0, 1e-27, composition={\"X\": 1}),\n",
    "        SpeciesIR(\"P\", 0, 2e-27, composition={\"X\": 2}),\n",
    "    ),\n",
    "    reactions=(\n",
    "        ReactionIR(\"dimerize\", {\"A\": 2}, {\"P\": 1}, {\"kind\": \"constant\", \"value\": k}),\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_P = model.concentration(\"P\")\n",
    "\n",
    "problem = Problem(\n",
    "    name=\"Second-order batch reactor\",\n",
    "    geometry=domain,\n",
    "    physics=(model,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(C_A, C_A0),\n",
    "        InitialValue(C_P, C_P0),\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 hyperbola\n",
    "\n",
    "The stored history of each concentration is read back and compared, time by\n",
    "time, with the closed-form second-order solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "times, num_A = result.field(C_A).time_series()\n",
    "_, num_P = result.field(C_P).time_series()\n",
    "\n",
    "exact_A = C_A0 / (1.0 + 2.0 * k * C_A0 * times)\n",
    "exact_P = 0.5 * (C_A0 - exact_A)\n",
    "\n",
    "err_A = float(np.max(np.abs(num_A - exact_A)))\n",
    "err_P = float(np.max(np.abs(num_P - exact_P)))\n",
    "rel_error = max(err_A, err_P) / C_A0\n",
    "print(\n",
    "    f\"Maximum absolute error against the hyperbola: {max(err_A, err_P):.3e} mol/m^3\"\n",
    "    f\"  ({100 * rel_error:.4f} % of C_A0)\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Physical sanity: mass conserved as C_A + 2 C_P, A monotonically decreasing, P\n",
    "monotonically increasing."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "mass_error = float(np.max(np.abs(num_A + 2.0 * num_P - C_A0)))\n",
    "print(f\"Maximum mass-balance error C_A+2 C_P-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",
    "a_fine = C_A0 / (1.0 + 2.0 * k * C_A0 * t_fine)\n",
    "plots.line(\n",
    "    points={\"C_A\": (times[shown], num_A[shown]), \"C_P\": (times[shown], num_P[shown])},\n",
    "    reference={\"C_A\": (t_fine, a_fine), \"C_P\": (t_fine, 0.5 * (C_A0 - a_fine))},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"concentration [mol/m^3]\",\n",
    "    title=\"Second-order batch 2A -> P: OneSimulation (markers) and exact solution (dashed)\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Compare with the first-order case: a second-order reaction tails off much more\n",
    "slowly because the rate $k C_A^2$ collapses as $A$ is depleted, so $C_A$ follows\n",
    "a $1/t$ hyperbola rather than an exponential. Raise $C_{A0}$ and the early decay\n",
    "sharpens, since the second-order rate scales with the square of concentration."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
