{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Reversible reaction A <-> B\n",
    "\n",
    "A species $A$ converts into $B$ and back in a homogeneous, well-mixed (0D)\n",
    "batch reactor through two opposing first-order steps:\n",
    "\n",
    "$$A \\xrightarrow{\\;k_f\\;} B,\\qquad B \\xrightarrow{\\;k_r\\;} A .$$\n",
    "\n",
    "With mass-action rate laws the homogeneous balances are\n",
    "\n",
    "$$\\frac{dC_A}{dt}=-k_f C_A + k_r C_B,\\qquad\n",
    "  \\frac{dC_B}{dt}=+k_f C_A - k_r C_B,\\qquad C_A(0)=C_{A0},\\;C_B(0)=0 .$$\n",
    "\n",
    "OneSimulation integrates this network on a lumped (0D) domain with an explicit\n",
    "classical Runge-Kutta scheme. The two opposing steps are declared as two\n",
    "irreversible constant-rate reactions sharing the same two species.\n",
    "\n",
    "**Reference.** Because $C_A+C_B=C_{A0}$ is conserved, $C_A$ obeys a single\n",
    "linear relaxation equation. With the relaxation rate $\\lambda=k_f+k_r$ and the\n",
    "equilibrium value $C_A^{\\mathrm{eq}}=\\dfrac{k_r}{k_f+k_r}C_{A0}$,\n",
    "\n",
    "$$C_A(t)=C_A^{\\mathrm{eq}}+\\bigl(C_{A0}-C_A^{\\mathrm{eq}}\\bigr)e^{-\\lambda t},$$\n",
    "\n",
    "and at equilibrium detailed balance fixes the ratio\n",
    "$C_B^{\\mathrm{eq}}/C_A^{\\mathrm{eq}}=k_f/k_r$. We compare both the transient and\n",
    "the equilibrium ratio."
   ]
  },
  {
   "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 forward and reverse coefficients set the\n",
    "relaxation rate $\\lambda=k_f+k_r$ and the equilibrium split. The window spans\n",
    "twelve relaxation times, so the system is essentially at equilibrium at the end."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "k_f = 1.2\n",
    "k_r = 0.4\n",
    "C_A0 = 1.0\n",
    "C_B0 = 0.0\n",
    "\n",
    "relaxation_rate = k_f + k_r\n",
    "C_total = C_A0 + C_B0\n",
    "C_A_eq = k_r / relaxation_rate * C_total\n",
    "C_B_eq = k_f / relaxation_rate * C_total\n",
    "tau = 1.0 / relaxation_rate\n",
    "end_time = 12.0 * tau\n",
    "time_step = 0.02 * tau\n",
    "print(\n",
    "    f\"relaxation rate k_f+k_r = {relaxation_rate:.3f} 1/s,  relaxation time = {tau:.3f} s\"\n",
    ")\n",
    "print(\n",
    "    f\"equilibrium: C_A_eq = {C_A_eq:.4f}, C_B_eq = {C_B_eq:.4f} mol/m^3,  ratio k_f/k_r = {k_f / k_r:.3f}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Two species ($A$, $B$) and two irreversible reactions with constant rate\n",
    "coefficients: $A\\to B$ at $k_f$ and $B\\to A$ at $k_r$. Together they form the\n",
    "reversible pair in a single lumped control volume."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "network = ReactionNetworkIR(\n",
    "    \"reversible_pair\",\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(\"forward\", {\"A\": 1}, {\"B\": 1}, {\"kind\": \"constant\", \"value\": k_f}),\n",
    "        ReactionIR(\"reverse\", {\"B\": 1}, {\"A\": 1}, {\"kind\": \"constant\", \"value\": k_r}),\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=\"Reversible reaction equilibrium\",\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 relaxation solution\n",
    "\n",
    "The stored concentration histories are compared, time by time, with the\n",
    "closed-form exponential relaxation, and the final state is compared with the\n",
    "equilibrium split and the detailed-balance ratio."
   ]
  },
  {
   "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_A_eq + (C_A0 - C_A_eq) * np.exp(-relaxation_rate * times)\n",
    "exact_B = C_B_eq + (C_B0 - C_B_eq) * np.exp(-relaxation_rate * times)\n",
    "\n",
    "err = max(\n",
    "    float(np.max(np.abs(num_A - exact_A))), float(np.max(np.abs(num_B - exact_B)))\n",
    ")\n",
    "rel_error = err / C_total\n",
    "print(\n",
    "    f\"Maximum absolute error against the relaxation: {err:.3e} mol/m^3\"\n",
    "    f\"  ({100 * rel_error:.4f} % of total)\"\n",
    ")\n",
    "\n",
    "final_A, final_B = num_A[-1], num_B[-1]\n",
    "print(\n",
    "    f\"final C_A = {final_A:.5f} (eq {C_A_eq:.5f}),  final C_B = {final_B:.5f} (eq {C_B_eq:.5f})\"\n",
    ")\n",
    "ratio = final_B / final_A\n",
    "print(f\"equilibrium ratio C_B/C_A = {ratio:.4f},  k_f/k_r = {k_f / k_r:.4f}\")\n",
    "\n",
    "mass_error = float(np.max(np.abs(num_A + num_B - C_total)))\n",
    "print(f\"Maximum mass-balance error C_A+C_B-C_total: {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_A_eq + (C_A0 - C_A_eq) * np.exp(-relaxation_rate * t_fine)),\n",
    "        \"C_B\": (t_fine, C_B_eq + (C_B0 - C_B_eq) * np.exp(-relaxation_rate * t_fine)),\n",
    "    },\n",
    "    hlines={\"equilibrium C_A\": C_A_eq, \"equilibrium C_B\": C_B_eq},\n",
    "    xlabel=\"time [s]\",\n",
    "    ylabel=\"concentration [mol/m^3]\",\n",
    "    title=\"Reversible reaction: OneSimulation (markers) and exact relaxation (dashed)\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Change the ratio $k_f/k_r$ and watch the equilibrium split move while the\n",
    "relaxation rate stays $k_f+k_r$. Start from the product side ($C_A=0$,\n",
    "$C_B=C_{B0}$) and confirm the same equilibrium is reached from above. Replace\n",
    "the two constant laws by Arrhenius laws and couple a temperature to study how\n",
    "the equilibrium shifts with $T$."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
