{
 "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": [
    "# Neutralisation of chlorine in a scrubber\n",
    "\n",
    "Chlorine is removed from waste gas by absorption in caustic soda. In the liquid the dissolved\n",
    "chlorine is destroyed by hydroxide,\n",
    "\n",
    "$$\\mathrm{Cl_2 + 2\\,OH^- \\longrightarrow Cl^- + OCl^- + H_2O},\\qquad r = k\\,c_\\mathrm{Cl_2}\\,c_\\mathrm{OH^-},$$\n",
    "\n",
    "a reaction of first order in each reactant although two hydroxide ions are consumed. The liquid\n",
    "volume is taken as perfectly mixed and constant (0D), and the chlorine is assumed to have\n",
    "dissolved almost to saturation, $c_\\mathrm{Cl_2,0}=10^{-2}$ mol/m³, before it reacts. The rate\n",
    "constant is of the order of the diffusion limit, $k=10^7$ m³/(mol s), so the liquid must be\n",
    "followed on a microsecond scale.\n",
    "\n",
    "| species | start [mol/m³] | role |\n",
    "|---|---|---|\n",
    "| Cl₂ | 0.01 | dissolved chlorine |\n",
    "| OH⁻ | 0.025 ... 1 | hydroxide of the washing liquid |\n",
    "| Cl⁻, OCl⁻ | 0 | products |\n",
    "\n",
    "**Reference.** With the extent $x$, $c_\\mathrm{Cl_2}=A_0-x$ and $c_\\mathrm{OH^-}=B_0-2x$; separating\n",
    "$\\dot x = k(A_0-x)(B_0-2x)$ gives the closed form (Levenspiel, *Chemical Reaction Engineering*,\n",
    "chapter 3, irreversible second-order reactions with unequal reactant ratio)\n",
    "\n",
    "$$x(t)=\\frac{B_0\\,(1-E)}{2-(B_0/A_0)\\,E},\\qquad E=e^{(B_0-2A_0)\\,k\\,t} .$$\n",
    "\n",
    "For a large hydroxide excess this reduces to the pseudo-first-order decay $A_0e^{-kB_0t}$."
   ]
  },
  {
   "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.simulation import Problem, Simulation\n",
    "from onesim.simulation.initial_conditions import InitialValue\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The reaction order in hydroxide is declared separately from its stoichiometric coefficient.\n",
    "Water is the solvent and is not tracked, so the element balance is switched off."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "k = 1e7\n",
    "network = ReactionNetworkIR(\n",
    "    \"chlorine_neutralisation\",\n",
    "    \"1\",\n",
    "    species=(\n",
    "        SpeciesIR(\"Cl2\", 0, 1.18e-25),\n",
    "        SpeciesIR(\"OH\", -1, 2.82e-26),\n",
    "        SpeciesIR(\"Cl\", -1, 5.89e-26),\n",
    "        SpeciesIR(\"OCl\", -1, 8.55e-26),\n",
    "    ),\n",
    "    reactions=(\n",
    "        ReactionIR(\n",
    "            \"neutralisation\",\n",
    "            {\"Cl2\": 1, \"OH\": 2},\n",
    "            {\"Cl\": 1, \"OCl\": 1},\n",
    "            {\"kind\": \"constant\", \"value\": k},\n",
    "            forward_orders={\"OH\": 1},\n",
    "        ),\n",
    "    ),\n",
    "    strict_balance=False,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Runs\n",
    "\n",
    "Four washing liquids, from a slight hydroxide excess over the stoichiometric 0.02 mol/m³ to a\n",
    "strong caustic of 1 mol/m³. Each run lasts until 99.9 % of the chlorine is gone, with 800\n",
    "Runge-Kutta steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "chlorine = 0.01\n",
    "hydroxide = (0.025, 0.05, 0.2, 1.0)\n",
    "models = {\n",
    "    B0: ReactionKinetics(domain=domain.system, network=network) for B0 in hydroxide\n",
    "}\n",
    "end = {\n",
    "    B0: np.log((B0 - 1.998 * chlorine) / (0.001 * B0)) / ((B0 - 2 * chlorine) * k)\n",
    "    for B0 in hydroxide\n",
    "}\n",
    "runs = {\n",
    "    B0: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"scrubber with {B0} mol/m3 OH\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.concentration(\"Cl2\"), chlorine),\n",
    "                InitialValue(model.concentration(\"OH\"), B0),\n",
    "                InitialValue(model.concentration(\"Cl\"), 0.0),\n",
    "                InitialValue(model.concentration(\"OCl\"), 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=end[B0], time_step=end[B0] / 800)\n",
    "    for B0, model in models.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed form\n",
    "\n",
    "The chlorine history of every run against $A_0-x(t)$, and the hydroxide left at the end against\n",
    "the stoichiometry."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "extent = (\n",
    "    lambda B0, t: B0\n",
    "    * (1 - np.exp((B0 - 2 * chlorine) * k * t))\n",
    "    / (2 - B0 / chlorine * np.exp((B0 - 2 * chlorine) * k * t))\n",
    ")\n",
    "histories = {\n",
    "    B0: run.field(models[B0].concentration(\"Cl2\")).time_series()\n",
    "    for B0, run in runs.items()\n",
    "}\n",
    "for B0, (t, c) in histories.items():\n",
    "    hydroxide_left = runs[B0].field(models[B0].concentration(\"OH\")).values[0]\n",
    "    print(\n",
    "        f\"OH0 = {B0:5.3f} mol/m^3: largest deviation from the closed form {np.max(np.abs(c - (chlorine - extent(B0, t)))) / chlorine:.1e} of Cl2_0; \"\n",
    "        f\"time to 99 % removal {t[np.argmax(c < 0.01 * chlorine)] * 1e6:6.2f} us (closed form \"\n",
    "        f\"{np.log((B0 - 1.98 * chlorine) / (0.01 * B0)) / ((B0 - 2 * chlorine) * k) * 1e6:6.2f} us); OH left {hydroxide_left:.5f} (stoichiometry {B0 - 2 * chlorine * (1 - c[-1] / chlorine):.5f})\"\n",
    "    )\n",
    "t_ex, c_ex = histories[1.0]\n",
    "print(\n",
    "    f\"strong caustic: largest deviation from the pseudo-first-order decay {np.max(np.abs(c_ex - chlorine * np.exp(-k * 1.0 * t_ex))) / chlorine:.1e} of Cl2_0\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Dissolved chlorine over time for the four washing liquids against the closed form, and the\n",
    "hydroxide consumed together with the products formed in the liquid with the smallest excess."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "t_fine = {B0: np.geomspace(end[B0] / 1000, end[B0], 400) for B0 in hydroxide}\n",
    "t25 = runs[0.025].field(models[0.025].concentration(\"OH\")).times\n",
    "fig = plots.figure(1, 2, size=(14, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        f\"OH0 = {B0} mol/m3\": (t[10::20] * 1e6, c[10::20] / chlorine)\n",
    "        for B0, (t, c) in histories.items()\n",
    "    },\n",
    "    reference={\n",
    "        f\"OH0 = {B0} mol/m3\": (t_fine[B0] * 1e6, 1 - extent(B0, t_fine[B0]) / chlorine)\n",
    "        for B0 in hydroxide\n",
    "    },\n",
    "    scale=\"loglog\",\n",
    "    ylimits=(1e-3, 1.5),\n",
    "    xlabel=\"time [us]\",\n",
    "    ylabel=\"Cl2 / Cl2 at start\",\n",
    "    title=\"Dissolved chlorine, dashed: closed form\",\n",
    "    legend=\"lower left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        name: (\n",
    "            np.asarray(t25) * 1e6,\n",
    "            runs[0.025].field(models[0.025].concentration(name)).time_series()[1],\n",
    "        )\n",
    "        for name in (\"Cl2\", \"OH\", \"Cl\", \"OCl\")\n",
    "    },\n",
    "    xlabel=\"time [us]\",\n",
    "    ylabel=\"concentration [mol/m3]\",\n",
    "    title=\"Liquid with OH0 = 0.025 mol/m3\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Couple the liquid to a gas phase with a mass-transfer coefficient to see when absorption, not\n",
    "reaction, limits the scrubber; at these rate constants the reaction happens inside the liquid\n",
    "film, which is the regime of the enhancement factor. Lower the hydroxide below the\n",
    "stoichiometric amount to see the chlorine break through."
   ]
  }
 ]
}
