{
 "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": [
    "# SEIR epidemic with Erlang-distributed stages\n",
    "\n",
    "A population of $N$ people is divided into susceptible $S$, exposed (infected but not\n",
    "yet infectious) $E$, infectious $I$ and removed $R$. Contacts with infectious people\n",
    "infect susceptibles at the rate $\\beta S I/N$; the latent period lasts on average\n",
    "$1/\\sigma$ and the infectious period $1/\\gamma$. In the classical SEIR model both\n",
    "periods are exponentially distributed, which overstates very short and very long\n",
    "stays. Splitting $E$ into $k$ and $I$ into $m$ consecutive compartments gives\n",
    "Erlang-distributed periods with the same means and a more realistic shape:\n",
    "\n",
    "$$\\dot S=-\\beta\\,\\frac{S\\,I}{N},\\qquad\n",
    "  \\dot E_1=\\beta\\,\\frac{S\\,I}{N}-k\\sigma E_1,\\quad \\dot E_j=k\\sigma\\,(E_{j-1}-E_j),$$\n",
    "\n",
    "$$\\dot I_1=k\\sigma E_k-m\\gamma I_1,\\quad \\dot I_j=m\\gamma\\,(I_{j-1}-I_j),\\qquad\n",
    "  \\dot R=m\\gamma\\,I_m,\\qquad I=\\textstyle\\sum_j I_j .$$\n",
    "\n",
    "OneSimulation builds the model as a signal-flow graph: one integrator per\n",
    "compartment, weighted sums for the stage transfers and one block for the infection\n",
    "term. The graph is integrated with the classical fourth-order Runge-Kutta method.\n",
    "\n",
    "**Reference.** H. J. Wearing, P. Rohani and M. J. Keeling, *Appropriate models for\n",
    "the management of infectious diseases*, PLoS Medicine 2, e174 (2005); O. Diekmann,\n",
    "H. Heesterbeek and T. Britton, *Mathematical Tools for Understanding Infectious\n",
    "Disease Dynamics*, Princeton 2013. With the basic reproduction number\n",
    "$R_0=\\beta/\\gamma$:\n",
    "\n",
    "- the early exponential growth rate $r$ solves\n",
    "  $\\dfrac{r}{\\gamma}\\left(1+\\dfrac{r}{k\\sigma}\\right)^k\\Big/\\left[1-\\left(1+\\dfrac{r}{m\\gamma}\\right)^{-m}\\right]=R_0$,\n",
    "  for $k=m=1$ simply $(1+r/\\sigma)(1+r/\\gamma)=R_0$;\n",
    "- the infection load $L=E+\\sum_j\\frac{m-j+1}{m}I_j$, which counts every infectious person\n",
    "  with the fraction of the infectious period still ahead, obeys $\\dot L=\\gamma I\\,(R_0S/N-1)$\n",
    "  and peaks exactly when $S/N=1/R_0$ (herd-immunity threshold); for $m=1$ it is $E+I$;\n",
    "- the final size follows from $\\dfrac{d\\ln S}{dR}=-\\dfrac{R_0}{N}$:\n",
    "  $\\ \\ln\\dfrac{S_0}{S_\\infty}=R_0\\,\\dfrac{N-S_\\infty}{N}$ (no one removed at the start).\n",
    "\n",
    "The last two hold for any stage numbers, the first one depends on them."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.time import DEFAULT_TIME_INTEGRATOR_REGISTRY\n",
    "from onesim.physics.systems import ControlSignalFlowProvider, SignalBlock\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": [
    "## Parameters\n",
    "\n",
    "A respiratory infection with $R_0=2.5$, a mean latent period of 4 days and a mean\n",
    "infectious period of 5 days, in a population of ten million with 20 exposed people\n",
    "on day 0. Two models: $k=m=1$ (classical SEIR) and $k=m=3$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "population, r0, latent, infectious = 1.0e7, 2.5, 4.0, 5.0\n",
    "sigma, gamma = 1.0 / latent, 1.0 / infectious\n",
    "beta = r0 * gamma\n",
    "stages = {\"exponential (k = m = 1)\": 1, \"Erlang (k = m = 3)\": 3}\n",
    "print(f\"β = {beta:.3f} per day, herd-immunity threshold 1 - 1/R0 = {1 - 1 / r0:.1%}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Signal-flow graph and simulation\n",
    "\n",
    "300 days with a step of 0.05 days. The block `infection` evaluates $\\beta S I/N$ from\n",
    "$S$ and all infectious stages; every stage is an integrator fed by a weighted sum."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "runs = {\n",
    "    name: ControlSignalFlowProvider(\n",
    "        blocks=(\n",
    "            SignalBlock(\n",
    "                \"S\",\n",
    "                \"integrator\",\n",
    "                inputs=(\"dS\",),\n",
    "                parameters={\"initial_value\": population - 20.0},\n",
    "            ),\n",
    "            SignalBlock(\"dS\", \"gain\", inputs=(\"infection\",), parameters={\"gain\": -1.0}),\n",
    "            SignalBlock(\n",
    "                \"infection\",\n",
    "                \"custom\",\n",
    "                inputs=(\"S\", *(f\"I{j}\" for j in range(1, n + 1))),\n",
    "                custom_evaluator=lambda s, t, p: beta * s[0] * sum(s[1:]) / population,\n",
    "                custom_derivative=lambda *a: (),\n",
    "            ),\n",
    "            *(\n",
    "                SignalBlock(\n",
    "                    f\"E{j}\",\n",
    "                    \"integrator\",\n",
    "                    inputs=(f\"dE{j}\",),\n",
    "                    parameters={\"initial_value\": 20.0 if j == 1 else 0.0},\n",
    "                )\n",
    "                for j in range(1, n + 1)\n",
    "            ),\n",
    "            *(\n",
    "                SignalBlock(\n",
    "                    f\"dE{j}\",\n",
    "                    \"sum\",\n",
    "                    inputs=(\"infection\" if j == 1 else f\"E{j - 1}\", f\"E{j}\"),\n",
    "                    parameters={\"weights\": (1.0 if j == 1 else n * sigma, -n * sigma)},\n",
    "                )\n",
    "                for j in range(1, n + 1)\n",
    "            ),\n",
    "            *(\n",
    "                SignalBlock(f\"I{j}\", \"integrator\", inputs=(f\"dI{j}\",))\n",
    "                for j in range(1, n + 1)\n",
    "            ),\n",
    "            *(\n",
    "                SignalBlock(\n",
    "                    f\"dI{j}\",\n",
    "                    \"sum\",\n",
    "                    inputs=(f\"E{n}\" if j == 1 else f\"I{j - 1}\", f\"I{j}\"),\n",
    "                    parameters={\n",
    "                        \"weights\": (n * sigma if j == 1 else n * gamma, -n * gamma)\n",
    "                    },\n",
    "                )\n",
    "                for j in range(1, n + 1)\n",
    "            ),\n",
    "            SignalBlock(\"R\", \"integrator\", inputs=(\"dR\",)),\n",
    "            SignalBlock(\n",
    "                \"dR\", \"gain\", inputs=(f\"I{n}\",), parameters={\"gain\": n * gamma}\n",
    "            ),\n",
    "        ),\n",
    "        final_time=300.0,\n",
    "        time_step=0.05,\n",
    "        time_integrator=DEFAULT_TIME_INTEGRATOR_REGISTRY.resolve_id(\"classical_rk4\"),\n",
    "    ).execute()\n",
    "    for name, n in stages.items()\n",
    "}\n",
    "days = np.asarray(next(iter(runs.values())).times)\n",
    "groups = {\n",
    "    name: {\n",
    "        c: sum(np.asarray(run.signals[f\"{c}{j}\"]) for j in range(1, stages[name] + 1))\n",
    "        for c in \"EI\"\n",
    "    }\n",
    "    | {c: np.asarray(run.signals[c]) for c in \"SR\"}\n",
    "    for name, run in runs.items()\n",
    "}\n",
    "load = {\n",
    "    name: groups[name][\"E\"]\n",
    "    + sum(\n",
    "        (n - j + 1) / n * np.asarray(runs[name].signals[f\"I{j}\"])\n",
    "        for j in range(1, n + 1)\n",
    "    )\n",
    "    for name, n in stages.items()\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the exact results\n",
    "\n",
    "The growth rate is fitted to $\\ln(E+I)$ in the rising phase while fewer than 0.1 % of\n",
    "the population are infected (after a two-week start-up of the stage distribution);\n",
    "the threshold is $S/N$ at the maximum of the load $L$; the final size is the removed\n",
    "fraction after 300 days."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "growth = lambda n: brentq(\n",
    "    lambda r: r / gamma * (1 + r / (n * sigma)) ** n / (1 - (1 + r / (n * gamma)) ** -n)\n",
    "    - r0,\n",
    "    1e-6,\n",
    "    2.0,\n",
    ")\n",
    "final = brentq(\n",
    "    lambda s: np.log((population - 20.0) / s) - r0 * (population - s) / population,\n",
    "    1.0,\n",
    "    population / r0,\n",
    ")\n",
    "print(\n",
    "    \"model                      growth rate [1/day]       doubling  S/N at peak of L     peak day   final size\"\n",
    ")\n",
    "for name, g in groups.items():\n",
    "    infected = g[\"E\"] + g[\"I\"]\n",
    "    peak = np.argmax(load[name])\n",
    "    early = (days > 14.0) & (days < days[peak]) & (infected < 1e-3 * population)\n",
    "    rate = np.polyfit(days[early], np.log(infected[early]), 1)[0]\n",
    "    print(\n",
    "        f\"{name:24s} {rate:7.4f} (exact {growth(stages[name]):.4f}) {np.log(2) / rate:7.2f} d \"\n",
    "        f\"{g['S'][peak] / population:9.4f} (1/R0 {1 / r0:.4f}) {days[peak]:8.1f} \"\n",
    "        f\"{g['R'][-1] / population:9.4f} (exact {1 - final / population:.4f})\"\n",
    "    )\n",
    "print(\n",
    "    f\"population conserved: largest |S + E + I + R - N| = \"\n",
    "    f\"{max(np.abs(sum(g.values()) - population).max() for g in groups.values()):.1e}\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The four compartments of both models; the infection load with the moment the\n",
    "herd-immunity threshold is crossed; and the early phase on a logarithmic scale\n",
    "against the exact growth rates."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 3, size=(17, 5))\n",
    "plots.line(\n",
    "    days,\n",
    "    {\n",
    "        f\"{c}, {'k = m = 1' if n == 1 else 'k = m = 3'}\": groups[name][c] / population\n",
    "        for name, n in stages.items()\n",
    "        for c in \"SEIR\"\n",
    "    },\n",
    "    styles={f\"{c}, k = m = 1\": \"dashdot\" for c in \"SEIR\"},\n",
    "    colors={\n",
    "        f\"{c}, {lab}\": i\n",
    "        for c, i in zip(\"SEIR\", (0, 5, 3, 6))\n",
    "        for lab in (\"k = m = 1\", \"k = m = 3\")\n",
    "    },\n",
    "    xlimits=(0.0, 250.0),\n",
    "    xlabel=\"time [days]\",\n",
    "    ylabel=\"fraction of the population\",\n",
    "    title=\"Compartments (dash-dot: k = m = 1)\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    days,\n",
    "    {name: value / population for name, value in load.items()},\n",
    "    vlines={\n",
    "        f\"S/N = 1/R0 ({name.split()[0]})\": days[np.argmax(g[\"S\"] < population / r0)]\n",
    "        for name, g in groups.items()\n",
    "    },\n",
    "    xlimits=(0.0, 200.0),\n",
    "    xlabel=\"time [days]\",\n",
    "    ylabel=\"infection load L / N\",\n",
    "    title=\"Peak at the herd-immunity threshold\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    days,\n",
    "    {name: g[\"E\"] + g[\"I\"] for name, g in groups.items()},\n",
    "    reference={\n",
    "        name: (groups[name][\"E\"] + groups[name][\"I\"])[600]\n",
    "        * np.exp(growth(n) * (days - days[600]))\n",
    "        for name, n in stages.items()\n",
    "    },\n",
    "    scale=\"logy\",\n",
    "    xlimits=(0.0, 100.0),\n",
    "    ylimits=(5.0, 2e6),\n",
    "    xlabel=\"time [days]\",\n",
    "    ylabel=\"infected people E + I\",\n",
    "    title=\"Early growth (dashed: exact rate)\",\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",
    "Reduce `beta` from day 40 on with a `source` block (contact reduction) and watch the\n",
    "peak flatten and shift; the final size relation then no longer holds with a single\n",
    "$R_0$. Raise the stage numbers further and the periods approach fixed durations: the\n",
    "growth rate tends to the root of $\\dfrac{r}{\\gamma}\\,e^{r/\\sigma}\\big/\\left(1-e^{-r/\\gamma}\\right)=R_0$. Add a death\n",
    "compartment fed from the last infectious stage to compare with reported fatality\n",
    "curves."
   ]
  }
 ]
}
