{
 "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": [
    "# Oscillations in a metabolic reaction network\n",
    "\n",
    "In glycolysis the enzyme phosphofructokinase is activated by its own product ADP. This positive\n",
    "feedback can make the concentrations of the intermediates oscillate with a period of minutes,\n",
    "as observed in yeast extracts. Sel'kov reduced the mechanism to two species, the substrate $Y$\n",
    "(fructose-6-phosphate) and the product $X$ (ADP), in a reactor with a steady supply of $Y$:\n",
    "\n",
    "| step | reaction | rate (dimensionless) |\n",
    "|---|---|---|\n",
    "| supply | $\\varnothing \\to Y$ | $b$ |\n",
    "| uncatalysed conversion | $Y \\to X$ | $a\\,y$ |\n",
    "| autocatalytic conversion | $Y + 2X \\to 3X$ | $x^2y$ |\n",
    "| removal | $X \\to \\varnothing$ | $x$ |\n",
    "\n",
    "$$\\dot x = -x + a\\,y + x^2y,\\qquad \\dot y = b - a\\,y - x^2y .$$\n",
    "\n",
    "OneSimulation integrates the network on a well-mixed (0D) volume; the cubic step is an ordinary\n",
    "mass-action law of total order three.\n",
    "\n",
    "**Reference.** E. E. Sel'kov, *Self-oscillations in glycolysis*, Eur. J. Biochem. 4 (1968) 79;\n",
    "the analysis follows S. H. Strogatz, *Nonlinear Dynamics and Chaos*, section 7.3. The single\n",
    "steady state is $x^\\ast=b$, $y^\\ast=b/(a+b^2)$. Its Jacobian has the trace and determinant\n",
    "\n",
    "$$\\tau = -\\frac{b^4+(2a-1)\\,b^2+a+a^2}{a+b^2},\\qquad \\Delta = a+b^2 ,$$\n",
    "\n",
    "so small disturbances grow or decay like $e^{\\lambda t}$ with $\\lambda=\\tau/2\\pm i\\sqrt{\\Delta-\\tau^2/4}$.\n",
    "The steady state loses stability in a Hopf bifurcation where $\\tau=0$,\n",
    "$b^2=\\tfrac12\\big(1-2a\\pm\\sqrt{1-8a}\\big)$, and the oscillation is born with the angular\n",
    "frequency $\\sqrt{\\Delta}$."
   ]
  },
  {
   "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.results import oscillation_fit\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": [
    "## Reaction network\n",
    "\n",
    "The supply enters as a constant species source of $Y$; the removal of $X$ is a reaction without\n",
    "products, so the element balance is not enforced."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "a = 0.08\n",
    "network = ReactionNetworkIR(\n",
    "    \"selkov_glycolysis\",\n",
    "    \"1\",\n",
    "    species=(SpeciesIR(\"X\", 0, 1e-25), SpeciesIR(\"Y\", 0, 1e-25)),\n",
    "    reactions=(\n",
    "        ReactionIR(\"uncatalysed\", {\"Y\": 1}, {\"X\": 1}, {\"kind\": \"constant\", \"value\": a}),\n",
    "        ReactionIR(\n",
    "            \"autocatalytic\",\n",
    "            {\"Y\": 1, \"X\": 2},\n",
    "            {\"X\": 3},\n",
    "            {\"kind\": \"constant\", \"value\": 1.0},\n",
    "        ),\n",
    "        ReactionIR(\"removal\", {\"X\": 1}, {}, {\"kind\": \"constant\", \"value\": 1.0}),\n",
    "    ),\n",
    "    strict_balance=False,\n",
    ")\n",
    "hopf = np.sqrt(0.5 * (1 - 2 * a + np.array([-1, 1]) * np.sqrt(1 - 8 * a)))\n",
    "print(f\"a = {a}: oscillations expected for {hopf[0]:.4f} < b < {hopf[1]:.4f}\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Linear stability from the simulation\n",
    "\n",
    "For a sweep over the supply rate $b$ the network starts a small distance $10^{-4}$ away from the\n",
    "steady state. While the disturbance is small it is a single complex mode; projecting it onto the\n",
    "left eigenvector of the Jacobian gives a signal $\\propto e^{\\lambda t}$, whose growth rate and\n",
    "frequency `oscillation_fit` measures."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "domain = LumpedDomain()\n",
    "supplies = np.linspace(0.2, 1.1, 19)\n",
    "models = {\n",
    "    b: ReactionKinetics(domain=domain.system, network=network, species_sources={\"Y\": b})\n",
    "    for b in supplies\n",
    "}\n",
    "runs = {\n",
    "    b: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Selkov b={b:.2f}\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.concentration(\"X\"), b + 1e-4),\n",
    "                InitialValue(model.concentration(\"Y\"), b / (a + b**2)),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(domain),\n",
    "        numerics=Numerics(\n",
    "            spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=30.0, time_step=0.05)\n",
    "    for b, model in models.items()\n",
    "}\n",
    "\n",
    "jacobian = {\n",
    "    b: np.array(\n",
    "        [[-1 + 2 * b**2 / (a + b**2), a + b**2], [-2 * b**2 / (a + b**2), -(a + b**2)]]\n",
    "    )\n",
    "    for b in supplies\n",
    "}\n",
    "eigen = {b: np.linalg.eig(J.T) for b, J in jacobian.items()}\n",
    "left = {\n",
    "    b: values_vectors[1][:, np.argmax(values_vectors[0].imag)]\n",
    "    for b, values_vectors in eigen.items()\n",
    "}\n",
    "fits = {\n",
    "    b: oscillation_fit(\n",
    "        run.field(models[b].concentration(\"X\")).times,\n",
    "        left[b][0] * (run.field(models[b].concentration(\"X\")).time_series()[1] - b)\n",
    "        + left[b][1]\n",
    "        * (run.field(models[b].concentration(\"Y\")).time_series()[1] - b / (a + b**2)),\n",
    "    )\n",
    "    for b, run in runs.items()\n",
    "}\n",
    "exact = {\n",
    "    b: values_vectors[0][np.argmax(values_vectors[0].imag)]\n",
    "    for b, values_vectors in eigen.items()\n",
    "}\n",
    "for b in supplies:\n",
    "    print(\n",
    "        f\"b = {b:.3f}: growth rate {fits[b].growth_rate:+.5f} (eigenvalue {exact[b].real:+.5f}),  \"\n",
    "        f\"frequency {abs(fits[b].frequency):.5f} (eigenvalue {abs(exact[b].imag):.5f})\"\n",
    "    )\n",
    "growth = np.array([fits[b].growth_rate for b in supplies])\n",
    "crossings = [\n",
    "    supplies[i]\n",
    "    - growth[i] * (supplies[i + 1] - supplies[i]) / (growth[i + 1] - growth[i])\n",
    "    for i in np.flatnonzero(np.diff(np.sign(growth)))\n",
    "]\n",
    "print(\n",
    "    \"Hopf points from the measured growth rates: \"\n",
    "    + \", \".join(f\"{value:.4f}\" for value in crossings)\n",
    "    + f\"   (analytic {hopf[0]:.4f}, {hopf[1]:.4f})\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Limit cycles\n",
    "\n",
    "Inside the unstable range the disturbance grows until the nonlinearity limits it: the network\n",
    "settles on a closed orbit. Three supply rates are followed from the same small disturbance over\n",
    "400 time units. The period of the cycle is the mean spacing of the maxima of $x$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "cycles = {\n",
    "    b: ReactionKinetics(domain=domain.system, network=network, species_sources={\"Y\": b})\n",
    "    for b in (0.40, 0.60, 0.80)\n",
    "}\n",
    "cycle_runs = {\n",
    "    b: Simulation(\n",
    "        problem=Problem(\n",
    "            name=f\"Selkov cycle b={b:.2f}\",\n",
    "            geometry=domain,\n",
    "            physics=(model,),\n",
    "            initial_conditions=(\n",
    "                InitialValue(model.concentration(\"X\"), b + 0.01),\n",
    "                InitialValue(model.concentration(\"Y\"), b / (a + b**2)),\n",
    "            ),\n",
    "        ),\n",
    "        mesh=LumpedMesh(domain),\n",
    "        numerics=Numerics(\n",
    "            spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()\n",
    "        ),\n",
    "    ).run(start_time=0.0, end_time=400.0, time_step=0.05)\n",
    "    for b, model in cycles.items()\n",
    "}\n",
    "orbits = {\n",
    "    b: (\n",
    "        run.field(cycles[b].concentration(\"X\")).time_series(),\n",
    "        run.field(cycles[b].concentration(\"Y\")).time_series()[1],\n",
    "    )\n",
    "    for b, run in cycle_runs.items()\n",
    "}\n",
    "for b, ((t, x), y) in orbits.items():\n",
    "    late = t > 330\n",
    "    peaks = t[1:-1][(x[1:-1] > x[:-2]) & (x[1:-1] > x[2:]) & late[1:-1]]\n",
    "    print(\n",
    "        f\"b = {b:.2f}: x oscillates between {x[late].min():.3f} and {x[late].max():.3f}, period {np.diff(peaks).mean():.3f}, \"\n",
    "        f\"linear estimate at onset 2 pi / sqrt(a + b^2) = {2 * np.pi / np.sqrt(a + b**2):.3f}\"\n",
    "    )"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "Growth rate and frequency of the steady state over the supply rate, the limit cycles in the\n",
    "phase plane, and the oscillation of the substrate and product at $b = 0.6$."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "b_line = np.linspace(0.2, 1.1, 300)\n",
    "trace = -(b_line**4 + (2 * a - 1) * b_line**2 + a + a**2) / (a + b_line**2)\n",
    "(t6, x6), y6 = orbits[0.60]\n",
    "fig = plots.figure(1, 3, size=(18, 5))\n",
    "plots.line(\n",
    "    points={\n",
    "        \"growth rate, OneSimulation\": (supplies, growth),\n",
    "        \"frequency, OneSimulation\": (\n",
    "            supplies,\n",
    "            [abs(fits[b].frequency) for b in supplies],\n",
    "        ),\n",
    "    },\n",
    "    reference={\n",
    "        \"growth rate, eigenvalue\": (b_line, trace / 2),\n",
    "        \"frequency, eigenvalue\": (\n",
    "            b_line,\n",
    "            np.sqrt(np.maximum(a + b_line**2 - trace**2 / 4, 0)),\n",
    "        ),\n",
    "    },\n",
    "    hlines={\"neutral\": 0.0},\n",
    "    vlines={\"Hopf point\": hopf[0], \"Hopf point \": hopf[1]},\n",
    "    xlabel=\"supply rate b\",\n",
    "    ylabel=\"Re and Im of lambda\",\n",
    "    title=\"Stability of the steady state\",\n",
    "    legend=\"upper left\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    y={f\"b = {b:.2f}\": (x[t > 330], y[t > 330]) for b, ((t, x), y) in orbits.items()},\n",
    "    points={\"steady states\": (list(orbits), [b / (a + b**2) for b in orbits])},\n",
    "    xlabel=\"product x (ADP)\",\n",
    "    ylabel=\"substrate y (F6P)\",\n",
    "    title=\"Limit cycles\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.line(\n",
    "    y={\"product x (ADP)\": (t6, x6), \"substrate y (F6P)\": (t6, y6)},\n",
    "    xlimits=(0, 120),\n",
    "    xlabel=\"time\",\n",
    "    ylabel=\"concentration\",\n",
    "    title=\"Oscillation at b = 0.6\",\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",
    "Approach the upper Hopf point from inside and watch the cycle shrink to zero amplitude while its\n",
    "period tends to $2\\pi/\\sqrt{\\Delta}$. Couple two such reactors through a slow exchange of $X$\n",
    "to study synchronisation, or replace the constant supply by a periodic one to drive the\n",
    "network into resonance or chaos."
   ]
  }
 ]
}
