{
 "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": [
    "# Ibuprofen synthesis: carbonylation kinetics with gas absorption\n",
    "\n",
    "In the three-step BHC process ibuprofen is made from 1-(4-isobutylphenyl)ethanol (IBPE) and\n",
    "carbon monoxide over a homogeneous palladium catalyst in acidic solution. Under the acid the\n",
    "alcohol first dehydrates to 4-isobutylstyrene (IBS), which is then carbonylated to the branched\n",
    "acid, ibuprofen (IBU), or, as by-product, to the linear 3-(4-isobutylphenyl)propanoic acid\n",
    "(3-IPPA):\n",
    "\n",
    "| step | reaction | rate law |\n",
    "|---|---|---|\n",
    "| dehydration | IBPE → IBS + H₂O | $r_1 = k_1\\,c_\\mathrm{IBPE}$ |\n",
    "| branched carbonylation | IBS + CO + H₂O → IBU | $r_2 = k_2\\,c_\\mathrm{IBS}\\,c_\\mathrm{CO}$ |\n",
    "| linear carbonylation | IBS + CO + H₂O → 3-IPPA | $r_3 = k_3\\,c_\\mathrm{IBS}\\,c_\\mathrm{CO}$ |\n",
    "| absorption | CO(gas) → CO(liquid) | $N = k_La\\,(c^\\ast_\\mathrm{CO} - c_\\mathrm{CO})$ |\n",
    "\n",
    "Water is present in excess, so the rates are of zero order in water. The gas cap is held at\n",
    "constant CO pressure, which fixes the saturation concentration $c^\\ast_\\mathrm{CO}$ by Henry's\n",
    "law; the absorption enters the liquid as a constant supply $k_La\\,c^\\ast$ and a first-order\n",
    "loss $k_La\\,c_\\mathrm{CO}$. The liquid is perfectly mixed (0D). The rate constants are\n",
    "representative values for illustration, not a fit to a particular catalyst.\n",
    "\n",
    "**Reference.** Process: Elango et al., US patent 4,981,995 (1991); kinetic analysis of the\n",
    "carbonylation network: Seayad, Jayasree & Chaudhari, *Org. Lett.* 1 (1999) 459. Two results\n",
    "hold exactly for every absorption rate, because the dehydration does not involve CO and both\n",
    "carbonylations are of first order in CO:\n",
    "\n",
    "$$c_\\mathrm{IBPE}=c_0e^{-k_1t},\\qquad S=\\frac{c_\\mathrm{IBU}}{c_\\mathrm{IBU}+c_\\mathrm{IPPA}}=\\frac{k_2}{k_2+k_3} .$$\n",
    "\n",
    "If the liquid stays saturated, $k' = (k_2+k_3)\\,c^\\ast$ and the network has the closed form of\n",
    "two consecutive first-order steps,\n",
    "$c_\\mathrm{IBS} = c_0\\,\\frac{k_1}{k'-k_1}\\big(e^{-k_1t}-e^{-k't}\\big)$."
   ]
  },
  {
   "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.linear import SparseDirect\n",
    "from onesim.numerics.nonlinear import Newton\n",
    "from onesim.numerics.time import BDF, BackwardEuler\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": [
    "## Reaction network\n",
    "\n",
    "Concentrations in mol/m³, time in seconds. Each species carries its elemental composition, so\n",
    "the three reactions are checked for element balance; the absorption term is a supply, which is\n",
    "why the strict network check is switched off."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "c0, saturation = 500.0, 100.0\n",
    "k1, k2, k3 = 3.0e-4, 4.8e-5, 2.0e-6\n",
    "composition = {\n",
    "    \"IBPE\": {\"C\": 12, \"H\": 18, \"O\": 1},\n",
    "    \"IBS\": {\"C\": 12, \"H\": 16},\n",
    "    \"H2O\": {\"H\": 2, \"O\": 1},\n",
    "    \"CO\": {\"C\": 1, \"O\": 1},\n",
    "    \"IBU\": {\"C\": 13, \"H\": 18, \"O\": 2},\n",
    "    \"IPPA\": {\"C\": 13, \"H\": 18, \"O\": 2},\n",
    "}\n",
    "reactions = (\n",
    "    ReactionIR(\n",
    "        \"dehydration\",\n",
    "        {\"IBPE\": 1},\n",
    "        {\"IBS\": 1, \"H2O\": 1},\n",
    "        {\"kind\": \"constant\", \"value\": k1},\n",
    "    ),\n",
    "    ReactionIR(\n",
    "        \"branched\",\n",
    "        {\"IBS\": 1, \"CO\": 1, \"H2O\": 1},\n",
    "        {\"IBU\": 1},\n",
    "        {\"kind\": \"constant\", \"value\": k2},\n",
    "        forward_orders={\"H2O\": 0},\n",
    "    ),\n",
    "    ReactionIR(\n",
    "        \"linear\",\n",
    "        {\"IBS\": 1, \"CO\": 1, \"H2O\": 1},\n",
    "        {\"IPPA\": 1},\n",
    "        {\"kind\": \"constant\", \"value\": k3},\n",
    "        forward_orders={\"H2O\": 0},\n",
    "    ),\n",
    ")\n",
    "species = tuple(\n",
    "    SpeciesIR(name, 0, 1e-25, composition=atoms) for name, atoms in composition.items()\n",
    ")\n",
    "print(\n",
    "    \"element balance of the three reactions:\",\n",
    "    ReactionNetworkIR(\n",
    "        \"check\", \"1\", species=species, reactions=reactions, strict_balance=True\n",
    "    ).strict_balance,\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Autoclave runs\n",
    "\n",
    "Four stirring intensities, from a gas-liquid transfer that keeps the liquid saturated to one that\n",
    "starves it. Each run covers four hours with the second-order BDF method and Newton's method."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "transfer = (1.0, 3e-3, 1e-3, 3e-4)\n",
    "networks = {\n",
    "    kLa: ReactionNetworkIR(\n",
    "        \"ibuprofen\",\n",
    "        \"1\",\n",
    "        species=species,\n",
    "        reactions=reactions\n",
    "        + (\n",
    "            ReactionIR(\"desorption\", {\"CO\": 1}, {}, {\"kind\": \"constant\", \"value\": kLa}),\n",
    "        ),\n",
    "    )\n",
    "    for kLa in transfer\n",
    "}\n",
    "models = {\n",
    "    kLa: ReactionKinetics(\n",
    "        domain=domain.system, network=network, species_sources={\"CO\": kLa * saturation}\n",
    "    )\n",
    "    for kLa, network in networks.items()\n",
    "}\n",
    "start = {\n",
    "    \"IBPE\": c0,\n",
    "    \"IBS\": 0.0,\n",
    "    \"H2O\": 2000.0,\n",
    "    \"CO\": saturation,\n",
    "    \"IBU\": 0.0,\n",
    "    \"IPPA\": 0.0,\n",
    "}\n",
    "numerics = Numerics(\n",
    "    spatial=LumpedParameters(),\n",
    "    time_integrator=BDF(order=2, startup=BackwardEuler()),\n",
    "    nonlinear_solver=Newton(\n",
    "        linear_solver=SparseDirect(),\n",
    "        jacobian=\"analytic\",\n",
    "        absolute_tolerance=1e-10,\n",
    "        relative_tolerance=1e-10,\n",
    "    ),\n",
    ")\n",
    "runs = {\n",
    "    kLa: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"carbonylation kLa={kLa}\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=tuple(\n",
    "                InitialValue(model.concentration(name), value)\n",
    "                for name, value in start.items()\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(domain),\n",
    "        numerics=numerics,\n",
    "    ).run(start_time=0.0, end_time=4 * 3600.0, time_step=10.0)\n",
    "    for kLa, model in models.items()\n",
    "}\n",
    "history = {\n",
    "    kLa: {\n",
    "        name: run.field(models[kLa].concentration(name)).time_series()[1]\n",
    "        for name in start\n",
    "    }\n",
    "    for kLa, run in runs.items()\n",
    "}\n",
    "times = runs[transfer[0]].field(models[transfer[0]].concentration(\"IBPE\")).times"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed forms\n",
    "\n",
    "IBPE decay and selectivity for every run, and the intermediate IBS of the best-stirred run\n",
    "against the consecutive-reaction solution of a saturated liquid."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fast = (k2 + k3) * saturation\n",
    "styrene = lambda t: c0 * k1 / (fast - k1) * (np.exp(-k1 * t) - np.exp(-fast * t))\n",
    "for kLa, c in history.items():\n",
    "    selectivity = c[\"IBU\"][-1] / (c[\"IBU\"][-1] + c[\"IPPA\"][-1])\n",
    "    print(\n",
    "        f\"kLa = {kLa:g} 1/s: IBPE deviation from c0 exp(-k1 t) {np.max(np.abs(c['IBPE'] - c0 * np.exp(-k1 * times))) / c0:.1e}, \"\n",
    "        f\"selectivity {selectivity:.6f} (exact {k2 / (k2 + k3):.6f}), ibuprofen yield after 1 h {c['IBU'][times <= 3600][-1] / c0:.3f}, after 4 h {c['IBU'][-1] / c0:.3f}, \"\n",
    "        f\"lowest dissolved CO {c['CO'].min() / saturation:.2f} c*\"\n",
    "    )\n",
    "print(\n",
    "    f\"best-stirred run: IBS deviation from the saturated closed form {np.max(np.abs(history[1.0]['IBS'] - styrene(times))) / c0:.1e} of c0, \"\n",
    "    f\"peak IBS {history[1.0]['IBS'].max():.1f} mol/m^3 at {times[np.argmax(history[1.0]['IBS'])] / 60:.0f} min \"\n",
    "    f\"(closed form {styrene(np.log(fast / k1) / (fast - k1)):.1f} at {np.log(fast / k1) / (fast - k1) / 60:.0f} min)\"\n",
    ")\n",
    "print(\n",
    "    f\"carbon monoxide balance of the starved run: absorbed {np.trapezoid(3e-4 * (saturation - history[3e-4]['CO']), times):.2f} mol/m^3, \"\n",
    "    f\"bound in acids plus dissolved change {history[3e-4]['IBU'][-1] + history[3e-4]['IPPA'][-1] + history[3e-4]['CO'][-1] - saturation:.2f} mol/m^3\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The species of the best-stirred run against the closed forms, ibuprofen yield for the four\n",
    "stirring intensities, and the dissolved CO that limits the slow runs."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "minutes = times / 60\n",
    "shown = slice(None, None, 48)\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        name: (minutes[shown], history[1.0][name][shown] / c0)\n",
    "        for name in (\"IBPE\", \"IBS\", \"IBU\")\n",
    "    },\n",
    "    reference={\n",
    "        \"IBPE\": (minutes, np.exp(-k1 * times)),\n",
    "        \"IBS\": (minutes, styrene(times) / c0),\n",
    "        \"IBU\": (\n",
    "            minutes,\n",
    "            k2 / (k2 + k3) * (1 - np.exp(-k1 * times) - styrene(times) / c0),\n",
    "        ),\n",
    "    },\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"c / c0\",\n",
    "    title=\"Saturated liquid, dashed: closed form\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={f\"kLa = {kLa} 1/s\": (minutes, c[\"IBU\"] / c0) for kLa, c in history.items()},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"ibuprofen yield\",\n",
    "    title=\"Yield and gas absorption\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        f\"kLa = {kLa} 1/s\": (minutes, c[\"CO\"] / saturation)\n",
    "        for kLa, c in history.items()\n",
    "    },\n",
    "    ylimits=(0, 1.05),\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"dissolved CO / saturation\",\n",
    "    title=\"Carbon monoxide in the liquid\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Make the dehydration reversible with the water concentration as a second-order term, or let the\n",
    "CO pressure fall in a closed autoclave by adding the gas cap as a species with a constant\n",
    "volume. With an Arrhenius rate law per step the same network gives the temperature window in\n",
    "which the carbonylation outruns the dehydration."
   ]
  }
 ]
}
