{
 "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": [
    "# Hydration of ethylene: chemical equilibrium in the gas phase\n",
    "\n",
    "Synthetic ethanol is made by the direct hydration of ethylene over an acid catalyst,\n",
    "\n",
    "$$\\mathrm{C_2H_4 + H_2O \\;\\rightleftharpoons\\; C_2H_5OH},\\qquad\n",
    "  \\Delta_rH^\\circ_{298} \\approx -45.5\\ \\mathrm{kJ/mol} .$$\n",
    "\n",
    "The reaction is exothermic and lowers the mole number, so low temperature and high pressure\n",
    "favour ethanol, while the catalyst needs a high temperature to be fast. The industrial process\n",
    "compromises at about 300 °C and 70 bar with a water-to-ethylene ratio near 0.6.\n",
    "\n",
    "Here the mixture is charged into a closed, isothermal vessel (0D) and the reversible reaction is\n",
    "integrated until it comes to rest. Only a forward rate constant is declared; OneSimulation builds\n",
    "the reverse rate from the equilibrium constant of the species thermochemistry, so the state the\n",
    "kinetics reaches must be the chemical equilibrium:\n",
    "\n",
    "$$r = k\\Big(c_\\mathrm{E}c_\\mathrm{W} - \\frac{c_\\mathrm{EtOH}}{K_c}\\Big),\\qquad\n",
    "  K_c = K(T)\\,\\frac{RT}{p^\\circ},\\qquad K(T)=\\exp\\!\\Big(-\\frac{\\Delta_rG^\\circ(T)}{RT}\\Big).$$\n",
    "\n",
    "**Reference.** Standard enthalpies of formation, entropies and heat capacities at 298.15 K from\n",
    "the NIST Chemistry WebBook (Linstrom & Mallard, NIST SRD 69). The equilibrium extent $x$ in the\n",
    "rigid vessel solves $K_c\\,(c_{\\mathrm E,0}-x)(c_{\\mathrm W,0}-x)=x$; it is computed here\n",
    "independently with a root finder, the procedure of Smith, Van Ness & Abbott, *Introduction to\n",
    "Chemical Engineering Thermodynamics*, chapter 13."
   ]
  },
  {
   "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",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Species and reaction\n",
    "\n",
    "Standard enthalpy of formation [J/mol], standard entropy and heat capacity [J/(mol K)] of each\n",
    "gas. The forward rate constant only sets how fast the vessel comes to rest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "R = 8.314462618\n",
    "thermo = {\n",
    "    \"C2H4\": (52.4e3, 219.32, 42.90, {\"C\": 2, \"H\": 4}, 4.66e-26),\n",
    "    \"H2O\": (-241.826e3, 188.835, 33.58, {\"H\": 2, \"O\": 1}, 2.99e-26),\n",
    "    \"C2H5OH\": (-234.95e3, 281.64, 65.21, {\"C\": 2, \"H\": 6, \"O\": 1}, 7.65e-26),\n",
    "}\n",
    "rate_constant = 1e-4\n",
    "network = ReactionNetworkIR(\n",
    "    \"ethylene_hydration\",\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",
    "            \"hydration\",\n",
    "            {\"C2H4\": 1, \"H2O\": 1},\n",
    "            {\"C2H5OH\": 1},\n",
    "            {\"kind\": \"constant\", \"value\": rate_constant},\n",
    "            reversible=True,\n",
    "        ),\n",
    "    ),\n",
    "    strict_balance=True,\n",
    ")\n",
    "dH = thermo[\"C2H5OH\"][0] - thermo[\"C2H4\"][0] - thermo[\"H2O\"][0]\n",
    "dS = thermo[\"C2H5OH\"][1] - thermo[\"C2H4\"][1] - thermo[\"H2O\"][1]\n",
    "dcp = thermo[\"C2H5OH\"][2] - thermo[\"C2H4\"][2] - thermo[\"H2O\"][2]\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, reaction entropy {dS:.2f} J/(mol K), K(298 K) = {K(298.15):.1f}, K(573 K) = {K(573.15):.2e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Runs\n",
    "\n",
    "Two studies, each a list of closed vessels: a temperature sweep at a charge pressure of 70 bar,\n",
    "and a pressure sweep at 300 °C, both with 0.6 mol of water per mol of ethylene. Every run lasts\n",
    "25 relaxation times $1/\\lambda$ with $\\lambda = k\\,(c_0 + 1/K_c)$ in 500 classical Runge-Kutta\n",
    "steps."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "water_ratio = 0.6\n",
    "cases = [(T, 70e5) for T in np.linspace(448.15, 698.15, 11)] + [\n",
    "    (573.15, p) for p in (5e5, 10e5, 20e5, 40e5, 100e5, 150e5)\n",
    "]\n",
    "models = [\n",
    "    ReactionKinetics(domain=domain.system, network=network, temperature=T)\n",
    "    for T, p in cases\n",
    "]\n",
    "total = [p / (R * T) for T, p in cases]\n",
    "relaxation = [rate_constant * (p / (R * T) + 1e5 / (K(T) * R * T)) for T, p in cases]\n",
    "runs = [\n",
    "    Simulation(\n",
    "        problem=Problem(\n",
    "            name=\"ethylene hydration\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.concentration(\"C2H4\"), c / (1 + water_ratio)),\n",
    "                InitialValue(\n",
    "                    model.concentration(\"H2O\"), c * water_ratio / (1 + water_ratio)\n",
    "                ),\n",
    "                InitialValue(model.concentration(\"C2H5OH\"), 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=25 / rate, time_step=0.05 / rate)\n",
    "    for model, c, rate in zip(models, total, relaxation)\n",
    "]"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the equilibrium\n",
    "\n",
    "The ethylene conversion at the end of each run against the root of the equilibrium condition.\n",
    "At the industrial point only about 6 % of the ethylene can react per pass, which is why the\n",
    "process recycles the unconverted gas."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "conversion = np.array(\n",
    "    [\n",
    "        run.field(model.concentration(\"C2H5OH\")).values[0] / (c / (1 + water_ratio))\n",
    "        for run, model, c in zip(runs, models, total)\n",
    "    ]\n",
    ")\n",
    "equilibrium = lambda T, c: brentq(\n",
    "    lambda x: K(T) * R * T / 1e5 * (1 - x) * (water_ratio - x) * c / (1 + water_ratio)\n",
    "    - x,\n",
    "    0.0,\n",
    "    water_ratio,\n",
    ")\n",
    "reference = np.array([equilibrium(T, c) for (T, p), c in zip(cases, total)])\n",
    "for (T, p), simulated, exact in zip(cases, conversion, reference):\n",
    "    print(\n",
    "        f\"T = {T - 273.15:5.1f} C, charge {p / 1e5:5.0f} bar: conversion simulated {simulated:.5f}, equilibrium {exact:.5f}, \"\n",
    "        f\"difference {abs(simulated - exact):.1e}\"\n",
    "    )\n",
    "final_pressure = [\n",
    "    sum(run.field(model.concentration(name)).values[0] for name in thermo) * R * T\n",
    "    for run, model, (T, p) in zip(runs, models, cases)\n",
    "]\n",
    "print(\n",
    "    f\"pressure at 300 C and 70 bar charge falls to {final_pressure[5] / 1e5:.1f} bar as two moles become one\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Equilibrium conversion over temperature at 70 bar charge pressure and over pressure at 300 °C,\n",
    "and the composition history of the vessel at the industrial operating point."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "history = runs[5]\n",
    "times = history.field(models[5].concentration(\"C2H4\")).times\n",
    "T_line, p_line = np.linspace(440.0, 710.0, 200), np.geomspace(4e5, 1.6e7, 200)\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"OneSimulation, final state\": (\n",
    "            np.array([T for T, p in cases[:11]]) - 273.15,\n",
    "            conversion[:11],\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"equilibrium from K(T)\": (\n",
    "            T_line - 273.15,\n",
    "            [equilibrium(T, 70e5 / (R * T)) for T in T_line],\n",
    "        )\n",
    "    },\n",
    "    xlabel=\"temperature [C]\",\n",
    "    ylabel=\"ethylene conversion\",\n",
    "    title=\"Charge at 70 bar\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        \"OneSimulation, final state\": (\n",
    "            np.array([p for T, p in cases[11:]] + [70e5]) / 1e5,\n",
    "            np.r_[conversion[11:], conversion[5]],\n",
    "        )\n",
    "    },\n",
    "    reference={\n",
    "        \"equilibrium from K(T)\": (\n",
    "            p_line / 1e5,\n",
    "            [equilibrium(573.15, p / (R * 573.15)) for p in p_line],\n",
    "        )\n",
    "    },\n",
    "    scale=\"logx\",\n",
    "    xlabel=\"charge pressure [bar]\",\n",
    "    ylabel=\"ethylene conversion\",\n",
    "    title=\"At 300 C\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        name: (\n",
    "            relaxation[5] * np.asarray(times),\n",
    "            history.field(models[5].concentration(name)).time_series()[1] / total[5],\n",
    "        )\n",
    "        for name in thermo\n",
    "    },\n",
    "    xlabel=\"time / relaxation time\",\n",
    "    xlimits=(0, 10),\n",
    "    ylabel=\"concentration / charge concentration\",\n",
    "    title=\"History at 300 C and 70 bar\",\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",
    "Raise the water-to-ethylene ratio and watch the conversion per pass grow while the ethanol in the\n",
    "product gets more dilute. Replace the constant heat capacities with NASA polynomials for a\n",
    "wider temperature range, or let the vessel run adiabatically with `AdiabaticReaction` to see the\n",
    "reaction heat push the equilibrium back."
   ]
  }
 ]
}
