{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# First-order reaction A -> B\n",
    "\n",
    "A single species $A$ decays irreversibly into a product $B$ in a homogeneous,\n",
    "well-mixed (0D) batch reactor:\n",
    "\n",
    "$$A \\xrightarrow{\\;k\\;} B .$$\n",
    "\n",
    "With a first-order (mass-action) rate law the reaction rate is $r=k\\,C_A$, so\n",
    "the concentrations obey\n",
    "\n",
    "$$\\frac{dC_A}{dt}=-k\\,C_A,\\qquad \\frac{dC_B}{dt}=+k\\,C_A,\\qquad\n",
    "  C_A(0)=C_{A0},\\;\\; C_B(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.\n",
    "\n",
    "**Reference.** The linear system has the exact solution\n",
    "\n",
    "$$C_A(t)=C_{A0}\\,e^{-k t},\\qquad C_B(t)=C_{A0}\\,\\bigl(1-e^{-k t}\\bigr),$$\n",
    "\n",
    "and total mass is conserved, $C_A(t)+C_B(t)=C_{A0}$. We compare the computed\n",
    "transient with this exponential."
   ]
  },
  {
   "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 rate coefficient $k$ sets the\n",
    "characteristic time $1/k$; the window spans five of those times, so $A$ decays\n",
    "to about $e^{-5}\\approx0.7\\,\\%$ of its initial value."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "k = 0.8\n",
    "C_A0 = 1.0\n",
    "C_B0 = 0.0\n",
    "tau = 1.0 / k\n",
    "end_time = 5.0 * tau\n",
    "time_step = 0.05 * tau\n",
    "print(\n",
    "    f\"k = {k:.3f} 1/s,  characteristic time 1/k = {tau:.2f} s,  end time = {end_time:.2f} s\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Two species ($A$, $B$) and one irreversible reaction $A\\to B$ with a constant\n",
    "(mass-action) rate coefficient. The reactor is a single lumped control volume."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "network = ReactionNetworkIR(\n",
    "    \"first_order_decay\",\n",
    "    \"1\",\n",
    "    species=(\n",
    "        SpeciesIR(\"A\", 0, 1e-27, composition={\"H\": 1}),\n",
    "        SpeciesIR(\"B\", 0, 1e-27, composition={\"H\": 1}),\n",
    "    ),\n",
    "    reactions=(\n",
    "        ReactionIR(\"decay\", {\"A\": 1}, {\"B\": 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_B = model.concentration(\"B\")\n",
    "\n",
    "problem = Problem(\n",
    "    name=\"First-order reaction decay\",\n",
    "    geometry=domain,\n",
    "    physics=(model,),\n",
    "    initial_conditions=(\n",
    "        InitialValue(C_A, C_A0),\n",
    "        InitialValue(C_B, C_B0),\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 exponential solution\n",
    "\n",
    "The stored history of each concentration is read back and compared, time by\n",
    "time, with the closed-form exponential."
   ]
  },
  {
   "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",
    "\n",
    "exact_A = C_A0 * np.exp(-k * times)\n",
    "exact_B = C_A0 * (1.0 - np.exp(-k * times))\n",
    "\n",
    "err_A = float(np.max(np.abs(num_A - exact_A)))\n",
    "err_B = float(np.max(np.abs(num_B - exact_B)))\n",
    "rel_error = max(err_A, err_B) / C_A0\n",
    "print(\n",
    "    f\"Maximum absolute error against the exponential: {max(err_A, err_B):.3e} mol/m^3\"\n",
    "    f\"  ({100 * rel_error:.4f} % of C_A0)\"\n",
    ")\n",
    "\n",
    "mass_error = float(np.max(np.abs(num_A + num_B - C_A0)))\n",
    "print(f\"Maximum mass-balance error C_A+C_B-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",
    "plots.line(\n",
    "    points={\"C_A\": (times[shown], num_A[shown]), \"C_B\": (times[shown], num_B[shown])},\n",
    "    reference={\n",
    "        \"C_A\": (t_fine, C_A0 * np.exp(-k * t_fine)),\n",
    "        \"C_B\": (t_fine, C_A0 * (1.0 - np.exp(-k * t_fine))),\n",
    "    },\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"concentration [mol/m^3]\",\n",
    "    title=\"First-order decay: OneSimulation (markers) and exact solution (dashed)\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower the time step and watch the Runge-Kutta error against the exponential\n",
    "shrink at fourth order. Replace the constant rate law by an Arrhenius law\n",
    "(`{\"kind\": \"arrhenius\", ...}`) and couple a temperature so the rate coefficient\n",
    "follows $k(T)$, or add a reverse reaction $B\\to A$ to obtain a relaxation to\n",
    "chemical equilibrium instead of a complete conversion."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
