{
 "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": [
    "# Semibatch polymerisation with volume shrinkage\n",
    "\n",
    "In a free-radical polymerisation the initiator I decays into radicals that add monomer M to\n",
    "growing chains. With the quasi-steady radical concentration $[R^\\bullet]=\\sqrt{f k_d[\\mathrm I]/k_t}$\n",
    "the rates per volume are\n",
    "\n",
    "$$r_\\mathrm I=-k_d[\\mathrm I],\\qquad r_\\mathrm M=-r_\\mathrm P=-k_p[\\mathrm M]\\sqrt{\\frac{f k_d[\\mathrm I]}{k_t}} ,$$\n",
    "\n",
    "where P counts the monomer units built into polymer. Styrene (0.862 g/cm³ at 70 °C) turns into\n",
    "polystyrene (1.04 g/cm³): the molar volume of a unit falls from $v_\\mathrm M=120.8$ to\n",
    "$v_\\mathrm P=100.1$ cm³/mol, 17 % shrinkage at full conversion. In a well-mixed tank with the\n",
    "amounts $n_i$ and an additive volume $V=\\sum_i n_iv_i$,\n",
    "\n",
    "$$\\frac{dn_i}{dt}=q\\,c_{i,\\mathrm{feed}}+V\\,r_i,\\qquad \\frac{dV}{dt}=q+V\\sum_i v_i\\,r_i .$$\n",
    "\n",
    "**Setup.** 2 L of styrene with 20 mol/m³ AIBN at 70 °C; the same mixture is fed at 0.5 L/h for\n",
    "two hours, then the batch is held for two more hours. $k_p=480$ L/(mol s) (IUPAC benchmark,\n",
    "M. Buback et al., *Macromol. Chem. Phys.* 196 (1995) 3267), $k_t=10^8$ L/(mol s),\n",
    "$k_d=3.78\\cdot10^{-5}$ 1/s and $f=0.6$ for AIBN (*Polymer Handbook*, 4th ed., Wiley 1999).\n",
    "\n",
    "**Reference.** For a batch at constant volume the monomer conversion has the closed form of\n",
    "A.V. Tobolsky, *J. Am. Chem. Soc.* 80 (1958) 5927,\n",
    "\n",
    "$$-\\ln(1-X)=2k_p\\sqrt{\\frac{f[\\mathrm I]_0}{k_dk_t}}\\Big(1-e^{-k_dt/2}\\Big),$$\n",
    "\n",
    "and with shrinkage the volume must equal $\\sum_i n_iv_i$ at every time."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import ProcessModelsProvider, ProcessStream, ProcessUnit\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Kinetics and molar volumes\n",
    "\n",
    "The reaction law returns the rates of the three components (and no heat: the jacket holds the\n",
    "temperature). `molar_volumes` lets these rates change the volume of a `dynamic_volume` unit;\n",
    "the volume of the dissolved initiator (0.1 % of the liquid) is neglected."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "hour, temperature = 3600.0, 343.15\n",
    "kp, kt, kd, efficiency = 0.480, 1.0e5, 3.78e-5, 0.6\n",
    "monomer, initiator = 862.0 / 0.10415, 20.0\n",
    "volumes = {\"M\": 0.10415 / 862.0, \"P\": 0.10415 / 1040.0, \"I\": 0.0}\n",
    "reaction = lambda c, T, t: (\n",
    "    {\n",
    "        \"I\": -kd * c[\"I\"],\n",
    "        \"M\": -kp * c[\"M\"] * np.sqrt(efficiency * kd * max(c[\"I\"], 0.0) / kt),\n",
    "        \"P\": kp * c[\"M\"] * np.sqrt(efficiency * kd * max(c[\"I\"], 0.0) / kt),\n",
    "    },\n",
    "    0.0,\n",
    ")\n",
    "charge = {\"M\": monomer, \"P\": 0.0, \"I\": initiator}\n",
    "rk4 = ProcessModelsProvider.bind_provider_parameters(\n",
    "    {\"time_integration\": \"classical_rk4\"}\n",
    ")\n",
    "print(\n",
    "    f\"styrene {monomer:.0f} mol/m³, shrinkage at full conversion {1 - volumes['P'] / volumes['M']:.1%}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Batch at constant volume: the kinetics against Tobolsky\n",
    "\n",
    "Four hours without feed and without shrinkage."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "batch = ProcessModelsProvider(\n",
    "    component_ids=(\"M\", \"P\", \"I\"),\n",
    "    units=(\n",
    "        ProcessUnit(\n",
    "            \"reactor\",\n",
    "            volume=2e-3,\n",
    "            initial_concentrations=charge,\n",
    "            initial_temperature=temperature,\n",
    "            reaction_law=reaction,\n",
    "        ),\n",
    "    ),\n",
    "    streams=(),\n",
    "    final_time=4 * hour,\n",
    "    time_step=10.0,\n",
    "    **rk4,\n",
    ").execute()\n",
    "t = batch.times\n",
    "conversion = 1 - batch.concentrations[\"reactor\"][\"M\"] / monomer\n",
    "tobolsky = 1 - np.exp(\n",
    "    -2 * kp * np.sqrt(efficiency * initiator / (kd * kt)) * (1 - np.exp(-kd * t / 2))\n",
    ")\n",
    "for hours in (1, 2, 4):\n",
    "    k = np.argmin(np.abs(t - hours * hour))\n",
    "    print(\n",
    "        f\"batch, constant volume, {hours} h: conversion {conversion[k]:.5f}, Tobolsky {tobolsky[k]:.5f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"largest deviation from Tobolsky over 4 h: {np.abs(conversion - tobolsky).max():.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Semibatch with and without shrinkage\n",
    "\n",
    "The feed stream carries the charge composition at 0.5 L/h for two hours. The first run treats\n",
    "the volume as additive; the second lets it follow only the feed, the usual constant-density\n",
    "assumption."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "feed = ProcessStream(\n",
    "    \"feed\",\n",
    "    None,\n",
    "    \"reactor\",\n",
    "    lambda time: 0.5e-3 / hour if time < 2 * hour else 0.0,\n",
    "    charge,\n",
    "    feed_temperature=temperature,\n",
    ")\n",
    "runs = {\n",
    "    label: ProcessModelsProvider(\n",
    "        component_ids=(\"M\", \"P\", \"I\"),\n",
    "        units=(\n",
    "            ProcessUnit(\n",
    "                \"reactor\",\n",
    "                volume=2e-3,\n",
    "                initial_concentrations=charge,\n",
    "                initial_temperature=temperature,\n",
    "                reaction_law=reaction,\n",
    "                dynamic_volume=True,\n",
    "                molar_volumes=molar,\n",
    "            ),\n",
    "        ),\n",
    "        streams=(feed,),\n",
    "        final_time=4 * hour,\n",
    "        time_step=10.0,\n",
    "        **rk4\n",
    "    ).execute()\n",
    "    for label, molar in ((\"additive volume\", volumes), (\"constant density\", None))\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "Volume, amounts and conversion after the feed and at the end; the additive rule\n",
    "$V=\\sum n_iv_i$ for the shrinking run."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for label, run in runs.items():\n",
    "    V, c = run.volumes[\"reactor\"], run.concentrations[\"reactor\"]\n",
    "    amounts = {i: c[i] * V for i in (\"M\", \"P\", \"I\")}\n",
    "    fed = monomer * np.minimum(run.times, 2 * hour) * 0.5e-3 / hour\n",
    "    print(\n",
    "        f\"{label:17s}: V(2 h) = {np.interp(2 * hour, run.times, V) * 1e3:.4f} L, V(4 h) = {V[-1] * 1e3:.4f} L, \"\n",
    "        f\"polymer {amounts['P'][-1] * 0.10415:.4f} kg, conversion {amounts['P'][-1] / (monomer * 2e-3 + fed[-1]):.4f}\"\n",
    "    )\n",
    "V, c = (\n",
    "    runs[\"additive volume\"].volumes[\"reactor\"],\n",
    "    runs[\"additive volume\"].concentrations[\"reactor\"],\n",
    ")\n",
    "print(\n",
    "    f\"additive rule: largest |V - sum n_i v_i| / V = {np.abs(V - sum(c[i] * V * volumes[i] for i in volumes)).max() / V.max():.1e}\"\n",
    ")\n",
    "print(\n",
    "    f\"the constant-density model underestimates the polymer after 4 h by \"\n",
    "    f\"{1 - runs['constant density'].concentrations['reactor']['P'][-1] * runs['constant density'].volumes['reactor'][-1] / (c['P'][-1] * V[-1]):.2%} \"\n",
    "    f\"and overestimates the final volume by {runs['constant density'].volumes['reactor'][-1] / V[-1] - 1:.2%}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Batch conversion against Tobolsky, and the semibatch volume and conversion of both models."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(18, 5.2))\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (t[::60] / hour, conversion[::60])},\n",
    "    reference={\"Tobolsky\": (t / hour, tobolsky)},\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"monomer conversion\",\n",
    "    title=\"Batch at constant volume\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        label: (run.times / hour, run.volumes[\"reactor\"] * 1e3)\n",
    "        for label, run in runs.items()\n",
    "    },\n",
    "    vlines={\"feed stops\": 2.0},\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"liquid volume [L]\",\n",
    "    title=\"Semibatch: volume\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        label: (\n",
    "            run.times / hour,\n",
    "            run.concentrations[\"reactor\"][\"P\"]\n",
    "            / (run.concentrations[\"reactor\"][\"P\"] + run.concentrations[\"reactor\"][\"M\"]),\n",
    "        )\n",
    "        for label, run in runs.items()\n",
    "    },\n",
    "    vlines={\"feed stops\": 2.0},\n",
    "    xlabel=\"time [h]\",\n",
    "    ylabel=\"polymer fraction P / (P + M)\",\n",
    "    title=\"Semibatch: conversion\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Add the gel effect (a termination constant that drops with conversion) through the reaction\n",
    "law, or release the heat of polymerisation (−70 kJ/mol) with a cooling jacket in `heat_source`\n",
    "to see the temperature rise that the shrinkage hides."
   ]
  }
 ]
}
