{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Startup of a continuous stirred tank reactor\n",
    "\n",
    "Propylene glycol is produced from propylene oxide (PO) and water in a perfectly mixed tank\n",
    "reactor with a cooling coil; methanol is fed as an inert co-solvent:\n",
    "\n",
    "$$\\mathrm{C_3H_6O + H_2O \\longrightarrow C_3H_8O_2},\\qquad r = k(T)\\,c_\\mathrm{PO},\\qquad k(T)=A\\,e^{-E/(R_gT)} .$$\n",
    "\n",
    "This is the startup problem of Fogler's *Elements of Chemical Reaction Engineering* (Example\n",
    "9-4). The reactor is one well-mixed volume $V$ with the feed $v_f$, so every state depends on\n",
    "time only:\n",
    "\n",
    "$$V\\frac{dc_i}{dt} = v_f\\,c_{f,i} - v\\,c_i + \\nu_i\\,r\\,V ,\\qquad\n",
    "  V\\Big(\\sum_i c_iC_{p,i}\\Big)\\frac{dT}{dt}\n",
    "  = -V\\,\\Delta H_r\\,r + Q_\\mathrm{coil}(T) + v_f\\sum_i c_{f,i}C_{p,i}\\,(T_f-T) .$$\n",
    "\n",
    "**Reference.** The published solution reports a steady state of about 472 mol/m³ of propylene\n",
    "oxide at 337 K and, for the startup with 1400 mol/m³ at 340 K, a temperature overshoot to about\n",
    "362 K, above the safety limit of 355 K. The steady state also follows from the algebraic\n",
    "balances, solved here independently of the time integration."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.time import AdaptiveBDF, AdaptiveRungeKutta45, EventDefinition\n",
    "from onesim.visualization import plots, theme\n",
    "from scipy.optimize import brentq\n",
    "\n",
    "theme.set()\n",
    "\n",
    "volume, feed_flow, feed_temperature, coolant_temperature = 1.89, 3.47e-3, 297.0, 289.0\n",
    "feed = np.array([2903.0, 36291.0, 0.0, 3629.0])\n",
    "heat_capacity = np.array([146.5, 75.4, 192.6, 81.6])\n",
    "stoichiometry = np.array([-1.0, -1.0, 1.0, 0.0])\n",
    "contraction = stoichiometry @ (\n",
    "    np.array([58.08, 18.015, 76.095, 32.042])\n",
    "    * 1e-3\n",
    "    / np.array([830.0, 1000.0, 1036.0, 792.0])\n",
    ")\n",
    "coil = 126.0 * 75.4 * (1 - np.exp(-8441.0 / (126.0 * 75.4)))\n",
    "rate_constant = lambda T: 4.71e9 * np.exp(-75.358e3 / (8.314462618 * T))\n",
    "reaction_enthalpy = lambda T: stoichiometry @ np.array(\n",
    "    [-153.5e3, -286.1e3, -525.6e3, -238.6]\n",
    ") + stoichiometry @ heat_capacity * (T - 293.0)\n",
    "\n",
    "\n",
    "def reactor(time, state):\n",
    "    \"\"\"Rates of change of the four concentrations and the temperature.\"\"\"\n",
    "    concentration, T = state[:4], state[4]\n",
    "    rate = rate_constant(T) * concentration[0]\n",
    "    outflow = feed_flow + volume * contraction * rate\n",
    "    heat = (\n",
    "        -volume * reaction_enthalpy(T) * rate\n",
    "        + coil * (coolant_temperature - T)\n",
    "        + feed_flow * (feed @ heat_capacity) * (feed_temperature - T)\n",
    "    )\n",
    "    return np.r_[\n",
    "        (feed_flow * feed - outflow * concentration) / volume + stoichiometry * rate,\n",
    "        heat / (volume * (concentration @ heat_capacity)),\n",
    "    ]\n",
    "\n",
    "\n",
    "def steady_state():\n",
    "    \"\"\"Steady propylene-oxide concentration and temperature from the algebraic balances.\"\"\"\n",
    "\n",
    "    def oxide(T):\n",
    "        roots = np.roots(\n",
    "            [\n",
    "                volume * contraction * rate_constant(T),\n",
    "                feed_flow + rate_constant(T) * volume,\n",
    "                -feed_flow * feed[0],\n",
    "            ]\n",
    "        )\n",
    "        return roots[(roots.real >= 0) & (roots.real <= feed[0])].real[0]\n",
    "\n",
    "    balance = lambda T: (\n",
    "        -volume * reaction_enthalpy(T) * rate_constant(T) * oxide(T)\n",
    "        + coil * (coolant_temperature - T)\n",
    "        + feed_flow * (feed @ heat_capacity) * (feed_temperature - T)\n",
    "    )\n",
    "    T = brentq(balance, 300.0, 400.0, xtol=1e-12)\n",
    "    return oxide(T), T"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Startups\n",
    "\n",
    "Each startup begins with water and a given amount of propylene oxide at a given temperature and\n",
    "runs for four hours. An event marks the temperature maximum."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "startups = {\n",
    "    \"1400 mol/m³ PO, 340 K\": (1400.0, 340.0),\n",
    "    \"no PO, 340 K\": (0.0, 340.0),\n",
    "    \"no PO, 297 K\": (0.0, 297.0),\n",
    "}\n",
    "peak = EventDefinition(\n",
    "    \"temperature maximum\", lambda t, state: reactor(t, state)[4], direction=-1\n",
    ")\n",
    "integrator = AdaptiveRungeKutta45(\n",
    "    relative_tolerance=1e-9, absolute_tolerance=1e-9, maximum_step=5.0\n",
    ")\n",
    "runs = {\n",
    "    label: integrator.integrate(\n",
    "        reactor,\n",
    "        np.array([oxide, 55273.0, 0.0, 0.0, T]),\n",
    "        0.0,\n",
    "        4 * 3600.0,\n",
    "        initial_step=0.1,\n",
    "        events=(peak,),\n",
    "    )\n",
    "    for label, (oxide, T) in startups.items()\n",
    "}\n",
    "\n",
    "oxide, temperature = steady_state()\n",
    "base = runs[\"1400 mol/m³ PO, 340 K\"]\n",
    "print(\n",
    "    f\"steady state: simulation {base.states[-1, 0]:.1f} mol/m³ PO at {base.states[-1, 4]:.2f} K, \"\n",
    "    f\"algebraic balance {oxide:.1f} mol/m³ at {temperature:.2f} K, published about 472 mol/m³ at 337 K\"\n",
    ")\n",
    "for label, run in runs.items():\n",
    "    hottest = run.states[:, 4].max()\n",
    "    print(\n",
    "        f\"{label:22s} highest temperature {hottest:.1f} K  ({'above' if hottest > 355 else 'below'} the 355 K limit)\"\n",
    "    )\n",
    "print(\n",
    "    f\"overshoot of the first startup: {base.events[0].state[4]:.1f} K after {base.events[0].time / 60:.2f} min, published about 362 K\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Two time integrators\n",
    "\n",
    "The first startup again with the adaptive Runge-Kutta method and with an adaptive BDF method at\n",
    "several tolerances. The error is the deviation of the peak temperature from the run above."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "methods = {\n",
    "    \"Dormand-Prince (adaptive)\": [\n",
    "        AdaptiveRungeKutta45(relative_tolerance=tol, absolute_tolerance=tol)\n",
    "        for tol in (1e-4, 1e-6, 1e-8)\n",
    "    ],\n",
    "    \"BDF2 (adaptive)\": [\n",
    "        AdaptiveBDF(order=2, relative_tolerance=tol, absolute_tolerance=tol)\n",
    "        for tol in (1e-3, 1e-5, 1e-7)\n",
    "    ],\n",
    "}\n",
    "work = {}\n",
    "for name, solvers in methods.items():\n",
    "    results = [\n",
    "        solver.integrate(\n",
    "            reactor, base.states[0], 0.0, 4 * 3600.0, initial_step=0.1, events=(peak,)\n",
    "        )\n",
    "        for solver in solvers\n",
    "    ]\n",
    "    work[name] = (\n",
    "        [result.accepted_steps for result in results],\n",
    "        [\n",
    "            abs(result.events[0].state[4] - base.events[0].state[4])\n",
    "            for result in results\n",
    "        ],\n",
    "    )\n",
    "    print(\n",
    "        f\"{name:26s} steps {work[name][0]}   error of the peak temperature [K] \"\n",
    "        + \", \".join(f\"{e:.1e}\" for e in work[name][1])\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The reactor temperature for the three startups, the path of the first startup in the plane of\n",
    "concentration and temperature, and the accuracy of the two integrators against their work."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.line(\n",
    "    y={label: (run.times / 60, run.states[:, 4]) for label, run in runs.items()},\n",
    "    hlines={\"safety limit\": 355.0, \"steady state\": temperature},\n",
    "    xlimits=(0, 120),\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"reactor temperature [K]\",\n",
    "    title=\"Three startups\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={label: (run.states[:, 0], run.states[:, 4]) for label, run in runs.items()},\n",
    "    points={\"steady state\": ([oxide], [temperature])},\n",
    "    xlabel=\"propylene oxide [mol/m³]\",\n",
    "    ylabel=\"temperature [K]\",\n",
    "    title=\"Path to the steady state\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y=work,\n",
    "    markers=True,\n",
    "    scale=\"loglog\",\n",
    "    xlabel=\"time steps\",\n",
    "    ylabel=\"error of the peak temperature [K]\",\n",
    "    title=\"Accuracy against work\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lower the coolant flow and the steady state loses its stability: the reactor then oscillates\n",
    "for ever. Raise the feed temperature to find the ignition point, or add a controller that\n",
    "throttles the feed when the temperature approaches the limit."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
