{
 "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": [
    "# Hydrogen iodide batch reactor, isothermal and adiabatic\n",
    "\n",
    "Hydrogen iodide decomposes reversibly into hydrogen and iodine vapour,\n",
    "\n",
    "$$2\\,\\mathrm{HI} \\;\\rightleftharpoons\\; \\mathrm{H_2} + \\mathrm{I_2},\\qquad\n",
    "  r = k_f(T)\\Big(c_\\mathrm{HI}^2 - \\frac{c_\\mathrm{H_2}c_\\mathrm{I_2}}{K(T)}\\Big),\\qquad\n",
    "  k_f = A\\,e^{-E_a/(R T)} .$$\n",
    "\n",
    "The gas fills a rigid, perfectly mixed vessel (0D). Only the forward rate constant is declared;\n",
    "the reverse rate follows from detailed balance with the equilibrium constant $K(T)$, which\n",
    "OneSimulation computes from the standard enthalpies, entropies and heat capacities of the three\n",
    "species. Because the mole number does not change, $K_c=K_p=K$:\n",
    "\n",
    "$$K(T)=\\exp\\!\\Big(-\\frac{\\Delta_r G^\\circ(T)}{RT}\\Big),\\qquad\n",
    "  \\Delta_r G^\\circ = \\Delta_r H^\\circ(T) - T\\,\\Delta_r S^\\circ(T) .$$\n",
    "\n",
    "Two operating modes are computed:\n",
    "\n",
    "| mode | temperature | energy balance |\n",
    "|---|---|---|\n",
    "| isothermal | held at 700 ... 800 K | none (thermostat) |\n",
    "| adiabatic | free, starts at 750 K | $\\sum_i c_i c_{v,i}\\,\\dot T = -\\Delta_r U\\,r$, ideal gas at constant volume |\n",
    "\n",
    "**Reference.** Arrhenius parameters of the decomposition $A = 9.17\\cdot10^{10}$ dm³/(mol s),\n",
    "$E_a = 186$ kJ/mol (Atkins & de Paula, *Physical Chemistry*, table of Arrhenius parameters);\n",
    "standard thermochemical data of HI, H₂ and I₂(g) from the NIST-JANAF tables (Chase, 1998).\n",
    "At fixed temperature the extent $x=c_\\mathrm{H_2}$ obeys $\\dot x = a\\,(x-x_1)(x-x_2)$ with\n",
    "$a=4k_f-k_f/K$ and $x_{1,2}=c_0/(2\\pm K^{-1/2})$, whose solution is\n",
    "\n",
    "$$x(t)=\\frac{x_1x_2\\,(1-e^{a(x_1-x_2)t})}{x_2-x_1\\,e^{a(x_1-x_2)t}} .$$\n",
    "\n",
    "For the adiabatic vessel, conservation of internal energy gives the temperature as a function\n",
    "of the extent, $T(x)=T_0-x\\,\\Delta_rH^\\circ(T_0)/(c_0c_{v,\\mathrm{HI}}+x\\,\\Delta c_p)$, and the\n",
    "final state is where $K(T(x))\\,(c_0-2x)^2=x^2$. The classic measurement of the synthesis\n",
    "equilibrium by Taylor & Crist (*J. Am. Chem. Soc.* 63, 1941) gives $1/K = 54.4$ at 698.6 K."
   ]
  },
  {
   "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.physics.multiphysics import AdiabaticReaction\n",
    "from onesim.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Species and reaction\n",
    "\n",
    "Each species carries its standard enthalpy of formation, standard entropy and a constant heat\n",
    "capacity at 298.15 K. The reaction is declared reversible, so its reverse branch is built from\n",
    "this thermochemistry."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "R = 8.314462618\n",
    "thermo = {\n",
    "    \"HI\": (26.50e3, 206.59, 29.16, {\"H\": 1, \"I\": 1}, 2.124e-25),\n",
    "    \"H2\": (0.0, 130.68, 28.84, {\"H\": 2}, 3.347e-27),\n",
    "    \"I2\": (62.42e3, 260.69, 36.90, {\"I\": 2}, 4.215e-25),\n",
    "}\n",
    "network = ReactionNetworkIR(\n",
    "    \"hydrogen_iodide\",\n",
    "    \"1\",\n",
    "    species=tuple(\n",
    "        SpeciesIR(\n",
    "            name,\n",
    "            0,\n",
    "            mass,\n",
    "            composition=atoms,\n",
    "            thermo={\n",
    "                \"model\": \"constant-cp\",\n",
    "                \"reference_temperature\": 298.15,\n",
    "                \"reference_enthalpy\": h,\n",
    "                \"reference_entropy\": s,\n",
    "                \"heat_capacity\": cp,\n",
    "            },\n",
    "        )\n",
    "        for name, (h, s, cp, atoms, mass) in thermo.items()\n",
    "    ),\n",
    "    reactions=(\n",
    "        ReactionIR(\n",
    "            \"decomposition\",\n",
    "            {\"HI\": 2},\n",
    "            {\"H2\": 1, \"I2\": 1},\n",
    "            {\n",
    "                \"kind\": \"arrhenius\",\n",
    "                \"pre_exponential\": 9.17e7,\n",
    "                \"activation_energy\": 186e3,\n",
    "                \"boltzmann_constant\": R,\n",
    "            },\n",
    "            reversible=True,\n",
    "        ),\n",
    "    ),\n",
    "    strict_balance=True,\n",
    ")\n",
    "\n",
    "pressure = 10e5\n",
    "dH, dS, dcp = (\n",
    "    62.42e3 - 2 * 26.50e3,\n",
    "    130.68 + 260.69 - 2 * 206.59,\n",
    "    28.84 + 36.90 - 2 * 29.16,\n",
    ")\n",
    "K = lambda T: np.exp(\n",
    "    -(dH + dcp * (T - 298.15) - T * (dS + dcp * np.log(T / 298.15))) / (R * T)\n",
    ")\n",
    "print(\n",
    "    f\"reaction enthalpy {dH / 1e3:.2f} kJ/mol at 298 K, heat capacity change {dcp:.2f} J/(mol K)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Isothermal runs\n",
    "\n",
    "Pure HI at 10 bar is charged at four temperatures. Each run covers fifteen relaxation times\n",
    "$\\tau = 1/\\lvert a\\,(x_1-x_2)\\rvert$ of the closed form in 600 classical Runge-Kutta steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "temperatures = (700.0, 725.0, 750.0, 800.0)\n",
    "models = {\n",
    "    T: ReactionKinetics(domain=domain.system, network=network, temperature=T)\n",
    "    for T in temperatures\n",
    "}\n",
    "c0 = {T: pressure / (R * T) for T in temperatures}\n",
    "kf = {T: 9.17e7 * np.exp(-186e3 / (R * T)) for T in temperatures}\n",
    "tau = {\n",
    "    T: 1\n",
    "    / (\n",
    "        kf[T]\n",
    "        * (1 / K(T) - 4)\n",
    "        * (c0[T] / (2 + K(T) ** -0.5) - c0[T] / (2 - K(T) ** -0.5))\n",
    "    )\n",
    "    for T in temperatures\n",
    "}\n",
    "runs = {\n",
    "    T: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"HI at {T:.0f} K\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.concentration(\"HI\"), c0[T]),\n",
    "                InitialValue(model.concentration(\"H2\"), 0.0),\n",
    "                InitialValue(model.concentration(\"I2\"), 0.0),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(domain),\n",
    "        numerics=Numerics(\n",
    "            spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=15 * tau[T], time_step=15 * tau[T] / 600)\n",
    "    for T, model in models.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed form\n",
    "\n",
    "The hydrogen history of every run is compared with the exact extent $x(t)$, and the final\n",
    "composition with the equilibrium constant."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "x1 = {T: c0[T] / (2 + K(T) ** -0.5) for T in temperatures}\n",
    "x2 = {T: c0[T] / (2 - K(T) ** -0.5) for T in temperatures}\n",
    "exact = (\n",
    "    lambda T, t: x1[T]\n",
    "    * x2[T]\n",
    "    * (1 - np.exp(kf[T] * (4 - 1 / K(T)) * (x1[T] - x2[T]) * t))\n",
    "    / (x2[T] - x1[T] * np.exp(kf[T] * (4 - 1 / K(T)) * (x1[T] - x2[T]) * t))\n",
    ")\n",
    "hydrogen = {\n",
    "    T: run.field(models[T].concentration(\"H2\")).time_series() for T, run in runs.items()\n",
    "}\n",
    "for T, (t, x) in hydrogen.items():\n",
    "    final_HI = runs[T].field(models[T].concentration(\"HI\")).values[0]\n",
    "    print(\n",
    "        f\"T = {T:.0f} K: largest deviation from x(t) {np.max(np.abs(x - exact(T, t))) / x1[T]:.1e} of the equilibrium extent, \"\n",
    "        f\"equilibrium conversion {2 * x[-1] / c0[T]:.4f}, 1/K from the final state {final_HI**2 / x[-1]**2:.2f} (thermochemistry {1 / K(T):.2f})\"\n",
    "    )\n",
    "print(f\"1/K at 698.6 K from the species data: {1 / K(698.6):.1f}  (measured: 54.4)\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adiabatic run\n",
    "\n",
    "Without the thermostat the reactor temperature becomes a state. With\n",
    "`volumetric_heat_capacity=None` the reactor treats the gas as ideal: its heat capacity at\n",
    "constant volume and the reaction energy come from the same species data. The endothermic\n",
    "decomposition cools the gas, which slows it down and shifts its equilibrium."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "T0 = 750.0\n",
    "adiabatic = AdiabaticReaction(\n",
    "    domain=domain.system, network=network, volumetric_heat_capacity=None\n",
    ")\n",
    "adiabatic_run = Simulation(\n",
    "    problem=Problem(\n",
    "        name=\"adiabatic HI\",\n",
    "        geometry=domain,\n",
    "        physics=(adiabatic,),\n",
    "        initial_conditions=(\n",
    "            InitialValue(adiabatic.concentration(\"HI\"), c0[T0]),\n",
    "            InitialValue(adiabatic.concentration(\"H2\"), 0.0),\n",
    "            InitialValue(adiabatic.concentration(\"I2\"), 0.0),\n",
    "            InitialValue(adiabatic.temperature, T0),\n",
    "        ),\n",
    "    ),\n",
    "    mesh=LumpedMesh(domain),\n",
    "    numerics=Numerics(\n",
    "        spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=120 * tau[T0], time_step=tau[T0] / 25)\n",
    "\n",
    "t_ad, T_ad = adiabatic_run.field(adiabatic.temperature).time_series()\n",
    "_, x_ad = adiabatic_run.field(adiabatic.concentration(\"H2\")).time_series()\n",
    "temperature_of = lambda x: T0 - x * (dH + dcp * (T0 - 298.15)) / (\n",
    "    c0[T0] * (29.16 - R) + x * dcp\n",
    ")\n",
    "x_end = brentq(\n",
    "    lambda x: K(temperature_of(x)) * (c0[T0] - 2 * x) ** 2 - x**2, 1e-9, x1[T0]\n",
    ")\n",
    "print(\n",
    "    f\"energy balance along the run: largest deviation of T from T(x) {np.max(np.abs(T_ad - temperature_of(x_ad))):.2e} K\"\n",
    ")\n",
    "print(\n",
    "    f\"final state: simulation T = {T_ad[-1]:.2f} K, x = {x_ad[-1]:.4f} mol/m^3;  \"\n",
    "    f\"energy balance + equilibrium T = {temperature_of(x_end):.2f} K, x = {x_end:.4f} mol/m^3\"\n",
    ")\n",
    "print(\n",
    "    f\"equilibrium conversion: adiabatic {2 * x_ad[-1] / c0[T0]:.4f}, isothermal at 750 K {2 * x1[T0] / c0[T0]:.4f}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Hydrogen formation at four temperatures against the exact solution, the adiabatic run against\n",
    "the isothermal one at the same start temperature, and the equilibrium constant over temperature."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "t_iso, x_iso = hydrogen[T0]\n",
    "T_line = np.linspace(650, 850, 200)\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"{T:.0f} K\": (t[::12] / tau[T], x[::12] / c0[T])\n",
    "        for T, (t, x) in hydrogen.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"{T:.0f} K\": (t / tau[T], exact(T, t) / c0[T])\n",
    "        for T, (t, x) in hydrogen.items()\n",
    "    },\n",
    "    xlabel=\"time / relaxation time\",\n",
    "    ylabel=\"H2 mole fraction\",\n",
    "    title=\"Isothermal runs, dashed: exact\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        \"H2 mole fraction, adiabatic\": (t_ad / 60, x_ad / c0[T0]),\n",
    "        \"H2 mole fraction, isothermal 750 K\": (t_iso / 60, x_iso / c0[T0]),\n",
    "    },\n",
    "    right={\"temperature, adiabatic\": (t_ad / 60, T_ad)},\n",
    "    hlines={\"equilibrium, adiabatic\": x_end / c0[T0]},\n",
    "    xlimits=(0, 60 * tau[T0] / 60),\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"H2 mole fraction\",\n",
    "    right_label=\"temperature [K]\",\n",
    "    title=\"Adiabatic run from 750 K\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"from species thermochemistry\": (T_line, 1 / K(T_line))},\n",
    "    points={\n",
    "        \"final state of the runs\": (\n",
    "            list(temperatures) + [T_ad[-1]],\n",
    "            [\n",
    "                runs[T].field(models[T].concentration(\"HI\")).values[0] ** 2\n",
    "                / hydrogen[T][1][-1] ** 2\n",
    "                for T in temperatures\n",
    "            ]\n",
    "            + [(c0[T0] - 2 * x_ad[-1]) ** 2 / x_ad[-1] ** 2],\n",
    "        ),\n",
    "        \"Taylor & Crist (1941)\": ([698.6], [54.4]),\n",
    "    },\n",
    "    xlabel=\"temperature [K]\",\n",
    "    ylabel=\"1/K = c_HI^2 / (c_H2 c_I2)\",\n",
    "    title=\"Equilibrium of H2 + I2 = 2 HI\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Raise the pressure: the equilibrium does not move, because the mole number is unchanged, but\n",
    "the reaction gets faster with $c_0^2$. Replace the constant heat capacities by NASA polynomials\n",
    "(`\"model\": \"NASA7\"`) for a wide temperature range, or start from H₂ and I₂ to run the\n",
    "synthesis direction towards the same equilibrium."
   ]
  }
 ]
}
