{
 "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": [
    "# Degradation of plasmid DNA in blood plasma\n",
    "\n",
    "Gene therapy with naked plasmid DNA depends on how long the plasmid survives in the blood. Only\n",
    "the supercoiled form (SC) is fully active; a single-strand nick relaxes it into the open-circular\n",
    "form (OC), a double-strand cut makes it linear (L), and further cuts digest it into fragments\n",
    "(F). In a plasma sample each step is a first-order reaction,\n",
    "\n",
    "$$\\mathrm{SC}\\xrightarrow{k_1}\\mathrm{OC}\\xrightarrow{k_2}\\mathrm{L}\\xrightarrow{k_3}\\mathrm F ,$$\n",
    "\n",
    "$$\\frac{dc_\\mathrm{SC}}{dt}=-k_1c_\\mathrm{SC},\\quad \\frac{dc_\\mathrm{OC}}{dt}=k_1c_\\mathrm{SC}-k_2c_\\mathrm{OC},\\quad\n",
    "  \\frac{dc_\\mathrm L}{dt}=k_2c_\\mathrm{OC}-k_3c_\\mathrm L,\\quad \\frac{dc_\\mathrm F}{dt}=k_3c_\\mathrm L .$$\n",
    "\n",
    "**Setup.** The sample starts with 100 % supercoiled plasmid. The rate constants are\n",
    "$k_1=0.3$, $k_2=0.03$ and $k_3=0.07$ per minute, illustrative values of the magnitude found for\n",
    "plasmid DNA in rat plasma (B.E. Houk, G. Hochhaus, J.A. Hughes, *AAPS PharmSci* 1 (1999) E9):\n",
    "the supercoiled form is lost within minutes, the open-circular form persists for half an hour.\n",
    "\n",
    "**Reference.** The chain of first-order steps has the exact Bateman solution\n",
    "\n",
    "$$c_\\mathrm{SC}=c_0e^{-k_1t},\\qquad c_\\mathrm{OC}=\\frac{c_0k_1}{k_2-k_1}\\big(e^{-k_1t}-e^{-k_2t}\\big),$$\n",
    "\n",
    "$$c_\\mathrm L=c_0k_1k_2\\sum_{i=1}^{3}\\frac{e^{-k_it}}{\\prod_{j\\ne i}(k_j-k_i)},$$\n",
    "\n",
    "and the open-circular form peaks at $t^*=\\ln(k_2/k_1)/(k_2-k_1)$ (H. Bateman, *Proc. Cambridge\n",
    "Phil. Soc.* 15 (1910) 423; O. Levenspiel, *Chemical Reaction Engineering*, 3rd ed., §8)."
   ]
  },
  {
   "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",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "Four forms of the same molecule (equal composition, so the network is mass-balanced) and three\n",
    "irreversible reactions with constant rate coefficients in 1/s. The plasma sample is one lumped\n",
    "volume; the fractions are of the initial dose, $c_0=1$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "minute = 60.0\n",
    "k1, k2, k3 = 0.3 / minute, 0.03 / minute, 0.07 / minute\n",
    "forms = (\"SC\", \"OC\", \"L\", \"F\")\n",
    "network = ReactionNetworkIR(\n",
    "    \"plasmid_degradation\",\n",
    "    \"1\",\n",
    "    species=tuple(SpeciesIR(name, 0, 1e-27, composition={\"H\": 1}) for name in forms),\n",
    "    reactions=(\n",
    "        ReactionIR(\"nicking\", {\"SC\": 1}, {\"OC\": 1}, {\"kind\": \"constant\", \"value\": k1}),\n",
    "        ReactionIR(\n",
    "            \"linearisation\", {\"OC\": 1}, {\"L\": 1}, {\"kind\": \"constant\", \"value\": k2}\n",
    "        ),\n",
    "        ReactionIR(\"digestion\", {\"L\": 1}, {\"F\": 1}, {\"kind\": \"constant\", \"value\": k3}),\n",
    "    ),\n",
    "    strict_balance=True,\n",
    ")\n",
    "\n",
    "domain = LumpedDomain()\n",
    "model = ReactionKinetics(domain=domain.system, temperature=310.15, network=network)\n",
    "problem = Problem(\n",
    "    name=\"Plasmid DNA in plasma\",\n",
    "    geometry=domain,\n",
    "    physics=(model,),\n",
    "    initial_conditions=tuple(\n",
    "        InitialValue(model.concentration(name), 1.0 if name == \"SC\" else 0.0)\n",
    "        for name in forms\n",
    "    ),\n",
    ")\n",
    "result = Simulation(\n",
    "    problem=problem,\n",
    "    mesh=LumpedMesh(domain),\n",
    "    numerics=Numerics(\n",
    "        spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "    ),\n",
    ").run(start_time=0.0, end_time=180 * minute, time_step=6.0)\n",
    "times = result.field(model.concentration(\"SC\")).time_series()[0]\n",
    "fractions = {\n",
    "    name: result.field(model.concentration(name)).time_series()[1] for name in forms\n",
    "}"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the Bateman solution\n",
    "\n",
    "The exact fractions at the same times, the largest deviation of each form, the maximum of the\n",
    "open-circular form and the half-lives of the supercoiled and of the total circular plasmid."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "rates = np.array([k1, k2, k3])\n",
    "exact = {\n",
    "    \"SC\": np.exp(-k1 * times),\n",
    "    \"OC\": k1 / (k2 - k1) * (np.exp(-k1 * times) - np.exp(-k2 * times)),\n",
    "    \"L\": k1\n",
    "    * k2\n",
    "    * sum(\n",
    "        np.exp(-k * times) / np.prod([other - k for other in rates if other != k])\n",
    "        for k in rates\n",
    "    ),\n",
    "}\n",
    "exact[\"F\"] = 1.0 - exact[\"SC\"] - exact[\"OC\"] - exact[\"L\"]\n",
    "for name in forms:\n",
    "    print(\n",
    "        f\"{name:>3s}: largest deviation from the exact solution {np.abs(fractions[name] - exact[name]).max():.2e}\"\n",
    "    )\n",
    "print(\n",
    "    f\"mass balance: largest |sum - 1| = {np.abs(sum(fractions.values()) - 1.0).max():.2e}\"\n",
    ")\n",
    "peak = np.argmax(fractions[\"OC\"])\n",
    "t_star = np.log(k2 / k1) / (k2 - k1)\n",
    "print(\n",
    "    f\"open-circular maximum: {fractions['OC'][peak]:.4f} at {times[peak] / minute:.1f} min; exact \"\n",
    "    f\"{k1 / (k2 - k1) * (np.exp(-k1 * t_star) - np.exp(-k2 * t_star)):.4f} at {t_star / minute:.2f} min\"\n",
    ")\n",
    "circular = fractions[\"SC\"] + fractions[\"OC\"]\n",
    "print(\n",
    "    f\"half-life of the supercoiled form: {np.interp(0.5, fractions['SC'][::-1], times[::-1]) / minute:.2f} min (ln 2 / k1 = {np.log(2) / k1 / minute:.2f} min)\"\n",
    ")\n",
    "print(\n",
    "    f\"circular plasmid (SC + OC) falls to half after {np.interp(0.5, circular[::-1], times[::-1]) / minute:.1f} min, \"\n",
    "    f\"to 10 % after {np.interp(0.1, circular[::-1], times[::-1]) / minute:.1f} min\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The four forms over three hours, OneSimulation as markers and the Bateman solution as lines."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shown = slice(None, None, 30)\n",
    "plots.line(\n",
    "    points={name: (times[shown] / minute, fractions[name][shown]) for name in forms},\n",
    "    reference={name: (times / minute, exact[name]) for name in forms},\n",
    "    xlabel=\"time [min]\",\n",
    "    ylabel=\"fraction of the dose\",\n",
    "    ylimits=(0, 1.02),\n",
    "    title=\"Plasmid forms in plasma: OneSimulation (markers), Bateman (lines)\",\n",
    "    legend=\"center right\",\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Fit $k_1$, $k_2$ and $k_3$ to measured band intensities of an agarose gel with the\n",
    "least-squares study of `SimulationStudyService.fit`. A direct branch SC → L (double-strand\n",
    "cut of the supercoiled form) is one more `ReactionIR`; an Arrhenius rate law shows how fast the\n",
    "plasmid disappears at room temperature instead of 37 °C."
   ]
  }
 ]
}
