{
 "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": [
    "# Fermentation in beer brewing\n",
    "\n",
    "After the wort is cooled it is pitched with yeast. The yeast multiplies on the fermentable\n",
    "sugars (mostly maltose) and turns them into ethanol and carbon dioxide; the temperature decides\n",
    "how fast. Lager is fermented cold, near 10 °C, ale warmer. The fermenter is a closed, well-mixed\n",
    "vessel (0D) held at constant temperature.\n",
    "\n",
    "The kinetics are those of Monod with growth-associated product formation:\n",
    "\n",
    "$$\\frac{dX}{dt}=\\mu X,\\quad \\frac{dS}{dt}=-\\frac{\\mu X}{Y_{X/S}},\\quad\n",
    "  \\frac{dE}{dt}=Y_{E/S}\\,\\frac{\\mu X}{Y_{X/S}},\\quad \\frac{dC}{dt}=Y_{C/S}\\,\\frac{\\mu X}{Y_{X/S}},\\qquad\n",
    "  \\mu=\\mu_\\mathrm{max}(T)\\,\\frac{S}{K_S+S},$$\n",
    "\n",
    "with the maximum growth rate following an Arrhenius law,\n",
    "$\\mu_\\mathrm{max}(T)=\\mu_\\mathrm{ref}\\,e^{-\\frac{E_a}{R}\\left(\\frac1T-\\frac1{T_\\mathrm{ref}}\\right)}$.\n",
    "\n",
    "| quantity | symbol | value |\n",
    "|---|---|---|\n",
    "| fermentable sugar in the wort (about 12 °Plato) | $S_0$ | 100 kg/m³ |\n",
    "| pitched yeast (dry mass) | $X_0$ | 0.25 kg/m³ |\n",
    "| yeast yield on sugar | $Y_{X/S}$ | 0.05 |\n",
    "| ethanol and CO₂ yield on sugar | $Y_{E/S},\\ Y_{C/S}$ | 0.46, 0.44 |\n",
    "| maximum growth rate at 12 °C, activation energy | $\\mu_\\mathrm{ref},\\ E_a$ | 0.025 1/h, 70 kJ/mol |\n",
    "| half-saturation constant | $K_S$ | 5 kg/m³ |\n",
    "\n",
    "The vessel is a process unit of OneSimulation whose reaction law returns the four production\n",
    "rates; the balances are integrated with the classical Runge-Kutta method.\n",
    "\n",
    "**Reference.** J. Monod, *Annu. Rev. Microbiol.* 3 (1949) 371; for the yields see Bailey &\n",
    "Ollis, *Biochemical Engineering Fundamentals*, chapter 7, and for brewing practice Briggs et\n",
    "al., *Brewing: Science and Practice*. Because $X+Y_{X/S}S=M$ is constant, the Monod equation\n",
    "integrates exactly:\n",
    "\n",
    "$$\\mu_\\mathrm{max}\\,t=\\Big(1+\\frac{K_SY_{X/S}}{M}\\Big)\\ln\\frac{X}{X_0}-\\frac{K_SY_{X/S}}{M}\\ln\\frac{S}{S_0},$$\n",
    "\n",
    "and the products follow the sugar stoichiometrically, $E=Y_{E/S}\\,(S_0-S)$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.physics.systems import (\n",
    "    ProcessModelsConfiguration,\n",
    "    ProcessModelsPublicApi,\n",
    "    ProcessUnit,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Kinetics\n",
    "\n",
    "The reaction law receives the concentrations (here in kg/m³), the temperature and the time,\n",
    "and returns the production rates and the heat release (zero: the fermenter is held at its\n",
    "temperature by its cooling jacket)."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "S0, X0, Y, Y_E, Y_C, Ks = 100.0, 0.25, 0.05, 0.46, 0.44, 5.0\n",
    "mu_max = lambda T: 0.025 / 3600 * np.exp(-70e3 / 8.314 * (1 / T - 1 / 285.15))\n",
    "\n",
    "\n",
    "def fermentation(c, T, t):\n",
    "    growth = mu_max(T) * c[\"S\"] / (Ks + c[\"S\"]) * c[\"X\"]\n",
    "    return {\n",
    "        \"X\": growth,\n",
    "        \"S\": -growth / Y,\n",
    "        \"E\": Y_E * growth / Y,\n",
    "        \"CO2\": Y_C * growth / Y,\n",
    "    }, 0.0"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fermentations at three temperatures\n",
    "\n",
    "Lager at 10 and 12 °C and an ale at 18 °C, each followed for fourteen days in steps of two minutes."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "temperatures = {\"10 C lager\": 283.15, \"12 C lager\": 285.15, \"18 C ale\": 291.15}\n",
    "runs = {\n",
    "    label: ProcessModelsPublicApi().run(\n",
    "        ProcessModelsConfiguration(\n",
    "            parameters=dict(\n",
    "                component_ids=(\"X\", \"S\", \"E\", \"CO2\"),\n",
    "                units=(\n",
    "                    ProcessUnit(\n",
    "                        \"fermenter\",\n",
    "                        initial_concentrations={\"X\": X0, \"S\": S0, \"E\": 0.0, \"CO2\": 0.0},\n",
    "                        initial_temperature=T,\n",
    "                        reaction_law=fermentation,\n",
    "                    ),\n",
    "                ),\n",
    "                final_time=14 * 86400.0,\n",
    "                time_step=120.0,\n",
    "            )\n",
    "        )\n",
    "    )\n",
    "    for label, T in temperatures.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the integrated Monod equation\n",
    "\n",
    "For every stored state the exact time at which the yeast reaches its simulated amount is\n",
    "computed; the deviation from the simulated time measures the error. The ethanol is compared\n",
    "with the stoichiometry and the attenuation (share of sugar fermented) is reported."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "M = X0 + Y * S0\n",
    "for label, run in runs.items():\n",
    "    c, t = run.concentrations[\"fermenter\"], run.times\n",
    "    exact_time = (\n",
    "        (1 + Ks * Y / M) * np.log(c[\"X\"] / X0) - Ks * Y / M * np.log(c[\"S\"] / S0)\n",
    "    ) / mu_max(temperatures[label])\n",
    "    active = c[\"S\"] > 1e-3 * S0\n",
    "    day_95 = t[np.argmax(c[\"S\"] < 0.05 * S0)] / 86400\n",
    "    print(\n",
    "        f\"{label}: largest time deviation from the integrated Monod law {np.max(np.abs(exact_time[active] - t[active])):.2e} s, \"\n",
    "        f\"ethanol deviation {np.max(np.abs(c['E'] - Y_E * (S0 - c['S']))):.1e} kg/m^3, \"\n",
    "        f\"95 % of the sugar fermented after {day_95:.2f} days, final ethanol {c['E'][-1]:.1f} kg/m^3 ({c['E'][-1] / 789 * 100:.1f} % by volume), CO2 released {c['CO2'][-1] / 1.83:.1f} m^3 per m^3 of wort\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Sugar, yeast against the integrated Monod law, and alcohol content for the three temperatures."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "days = {label: run.times / 86400 for label, run in runs.items()}\n",
    "X_line = np.linspace(X0, M * 0.9999, 400)\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    y={\n",
    "        label: (days[label], run.concentrations[\"fermenter\"][\"S\"])\n",
    "        for label, run in runs.items()\n",
    "    },\n",
    "    xlimits=(0, 10),\n",
    "    xlabel=\"time [days]\",\n",
    "    ylabel=\"sugar [kg/m3]\",\n",
    "    title=\"Fermentable sugar\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    points={\n",
    "        label: (days[label][::90], run.concentrations[\"fermenter\"][\"X\"][::90])\n",
    "        for label, run in runs.items()\n",
    "    },\n",
    "    reference={\n",
    "        label: (\n",
    "            (\n",
    "                (1 + Ks * Y / M) * np.log(X_line / X0)\n",
    "                - Ks * Y / M * np.log((M - X_line) / Y / S0)\n",
    "            )\n",
    "            / mu_max(T)\n",
    "            / 86400,\n",
    "            X_line,\n",
    "        )\n",
    "        for label, T in temperatures.items()\n",
    "    },\n",
    "    xlimits=(0, 10),\n",
    "    xlabel=\"time [days]\",\n",
    "    ylabel=\"yeast [kg/m3]\",\n",
    "    title=\"Yeast, dashed: integrated Monod law\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\n",
    "        label: (days[label], run.concentrations[\"fermenter\"][\"E\"] / 789 * 100)\n",
    "        for label, run in runs.items()\n",
    "    },\n",
    "    xlimits=(0, 10),\n",
    "    xlabel=\"time [days]\",\n",
    "    ylabel=\"ethanol [% by volume]\",\n",
    "    title=\"Alcohol\",\n",
    "    legend=\"lower right\",\n",
    "    ax=fig[2],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Give the vessel a heat release of about 0.6 MJ per kg of sugar and a jacket with finite\n",
    "cooling power to see how warm a fermenter runs. Add ethanol inhibition to the growth rate, or\n",
    "schedule the temperature in time (a warm diacetyl rest at the end of a lager fermentation)."
   ]
  }
 ]
}
