{
 "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": [
    "# The Hodgkin-Huxley membrane action potential\n",
    "\n",
    "Hodgkin and Huxley (1952) described the membrane of the squid giant axon by a capacitor in\n",
    "parallel with a voltage-gated sodium channel ($m^3h$), a voltage-gated potassium channel ($n^4$)\n",
    "and a passive leak. With the whole membrane at one potential (a space-clamped \"membrane action\n",
    "potential\", no propagation along the axon) the model is a system of four ordinary differential\n",
    "equations:\n",
    "\n",
    "$$C_m\\,\\frac{dV}{dt} = -\\bar g_\\mathrm{Na}\\,m^3h\\,(V-E_\\mathrm{Na})\n",
    "   - \\bar g_\\mathrm{K}\\,n^4\\,(V-E_\\mathrm{K}) - g_L\\,(V-E_L),\\qquad\n",
    "  \\frac{dy}{dt}=\\alpha_y(V)\\,(1-y)-\\beta_y(V)\\,y,\\quad y\\in\\{m,h,n\\}.$$\n",
    "\n",
    "| quantity | value |\n",
    "|---|---|\n",
    "| membrane capacitance $C_m$ | 1 µF/cm² |\n",
    "| sodium: $\\bar g_\\mathrm{Na}$, $E_\\mathrm{Na}$ | 120 mS/cm², +50 mV |\n",
    "| potassium: $\\bar g_\\mathrm{K}$, $E_\\mathrm{K}$ | 36 mS/cm², -77 mV |\n",
    "| leak: $g_L$, $E_L$ | 0.3 mS/cm², -54.4 mV |\n",
    "| resting potential, temperature | -65 mV, 6.3 °C |\n",
    "\n",
    "OneSimulation ships these channels with their rate functions $\\alpha_y$, $\\beta_y$ as\n",
    "`HodgkinHuxley1952`. The four equations are assembled as a signal-flow graph: an integrator\n",
    "block holds each state, and custom blocks evaluate the gate kinetics and the ionic current\n",
    "from the channel set. The membrane starts at rest with the gates at their resting values, and\n",
    "the potential is displaced suddenly by $\\Delta V$ (a short shock that charges the membrane), as\n",
    "in the original computation. The graph is integrated with the classical fourth-order\n",
    "Runge-Kutta method.\n",
    "\n",
    "**Reference.** A. L. Hodgkin and A. F. Huxley, \"A quantitative description of membrane current\n",
    "and its application to conduction and excitation in nerve\", J. Physiol. 117, 500-544 (1952),\n",
    "Part V and Fig. 12: membrane action potentials computed at 6 °C for initial depolarisations of\n",
    "6, 7, 15 and 90 mV. A displacement of 6 mV dies away, 7 mV and more give a full action\n",
    "potential: the threshold lies between 6 and 7 mV. The spike overshoots zero, lasts a few\n",
    "milliseconds at this temperature and ends with an after-hyperpolarisation below rest."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "from onesim.numerics.time import DEFAULT_TIME_INTEGRATOR_REGISTRY\n",
    "from onesim.physics.biophysics import HodgkinHuxley1952\n",
    "from onesim.physics.systems import ControlSignalFlowProvider, SignalBlock\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model\n",
    "\n",
    "The channel set gives the conductances, the reversal potentials, the gate exponents and the rate\n",
    "functions. The ionic current is summed over the channels, so the same graph runs any channel set\n",
    "of the same form. Each run starts from rest displaced by $\\Delta V$ and lasts 20 ms."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "membrane = HodgkinHuxley1952()\n",
    "capacitance, rest = 0.01, -0.065\n",
    "state = (\"V\",) + tuple(gate.name for gate in membrane.gates)\n",
    "ionic = lambda s: sum(\n",
    "    channel.conductance\n",
    "    * np.prod([s[state.index(g)] ** power for g, power in channel.gate_powers.items()])\n",
    "    * (s[0] - channel.reversal_potential)\n",
    "    for channel in membrane.channels\n",
    ")\n",
    "action_potential = lambda shift: ControlSignalFlowProvider(\n",
    "    blocks=(\n",
    "        SignalBlock(\n",
    "            \"V\",\n",
    "            \"integrator\",\n",
    "            inputs=(\"dV\",),\n",
    "            parameters={\"initial_value\": rest + shift},\n",
    "        ),\n",
    "        SignalBlock(\n",
    "            \"dV\",\n",
    "            \"custom\",\n",
    "            inputs=state,\n",
    "            custom_evaluator=lambda s, t, p: -ionic(s) / capacitance,\n",
    "            custom_derivative=lambda *a: (),\n",
    "        ),\n",
    "    )\n",
    "    + tuple(\n",
    "        block\n",
    "        for gate in membrane.gates\n",
    "        for block in (\n",
    "            SignalBlock(\n",
    "                gate.name,\n",
    "                \"integrator\",\n",
    "                inputs=(\"d\" + gate.name,),\n",
    "                parameters={\"initial_value\": gate.initial_value},\n",
    "            ),\n",
    "            SignalBlock(\n",
    "                \"d\" + gate.name,\n",
    "                \"custom\",\n",
    "                inputs=(\"V\", gate.name),\n",
    "                custom_evaluator=lambda s, t, p, rate=gate.rate: float(\n",
    "                    np.dot(rate(np.asarray(s[0])), (1 - s[1], -s[1]))\n",
    "                ),\n",
    "                custom_derivative=lambda *a: (),\n",
    "            ),\n",
    "        )\n",
    "    ),\n",
    "    final_time=0.02,\n",
    "    time_step=1e-5,\n",
    "    time_integrator=DEFAULT_TIME_INTEGRATOR_REGISTRY.resolve_id(\"classical_rk4\"),\n",
    ").execute()\n",
    "\n",
    "print(\n",
    "    \"channels:\",\n",
    "    \", \".join(f\"{c.name} {c.conductance / 10:g} mS/cm²\" for c in membrane.channels),\n",
    "    \"| gates at rest:\",\n",
    "    \", \".join(f\"{g.name} = {g.initial_value:.4f}\" for g in membrane.gates),\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Results\n",
    "\n",
    "The four displacements of the original figure, and a scan between 6 and 7 mV that locates the\n",
    "threshold: a run counts as an action potential when the potential overshoots 0 mV."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "shifts = (0.006, 0.007, 0.015, 0.090)\n",
    "runs = {shift: action_potential(shift) for shift in shifts}\n",
    "scan = {\n",
    "    shift: max(action_potential(shift).signals[\"V\"])\n",
    "    for shift in np.round(np.arange(0.0060, 0.00701, 0.0001), 4)\n",
    "}\n",
    "times = 1e3 * np.asarray(runs[shifts[0]].times)\n",
    "voltage = {shift: 1e3 * np.asarray(run.signals[\"V\"]) for shift, run in runs.items()}\n",
    "threshold = min(shift for shift, peak in scan.items() if peak > 0.0)\n",
    "\n",
    "print(\n",
    "    \"ΔV [mV]   peak [mV]   time of peak [ms]   after-hyperpolarisation [mV]   duration above -40 mV [ms]\"\n",
    ")\n",
    "for shift, v in voltage.items():\n",
    "    above = times[v > -40.0]\n",
    "    print(\n",
    "        f\"{1e3 * shift:7.0f} {v.max():11.1f} {times[v.argmax()]:19.2f} {v.min():30.1f} \"\n",
    "        f\"{(above[-1] - above[0]) if len(above) else 0.0:27.2f}\"\n",
    "    )\n",
    "print(\n",
    "    f\"threshold from the scan: between {1e3 * (threshold - 0.0001):.1f} and {1e3 * threshold:.1f} mV \"\n",
    "    f\"(Hodgkin and Huxley 1952: between 6 and 7 mV)\"\n",
    ")\n",
    "print(\n",
    "    f\"potential 20 ms after a 6 mV displacement: {voltage[0.006][-1]:.2f} mV (rest {1e3 * rest:.0f} mV)\"\n",
    ")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure\n",
    "\n",
    "The membrane potential after the four displacements, as in Fig. 12 of the original paper, and\n",
    "the sodium and potassium gates during the action potential after 15 mV."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig = plots.figure(1, 2, size=(14, 5.2))\n",
    "plots.line(\n",
    "    times,\n",
    "    {f\"ΔV = {1e3 * shift:.0f} mV\": v for shift, v in voltage.items()},\n",
    "    hlines={\"rest\": 1e3 * rest},\n",
    "    xlabel=\"time [ms]\",\n",
    "    ylabel=\"membrane potential [mV]\",\n",
    "    title=f\"Membrane action potentials, threshold {1e3 * threshold:.1f} mV\",\n",
    "    legend=\"upper right\",\n",
    "    ax=fig[0],\n",
    ")\n",
    "plots.line(\n",
    "    times,\n",
    "    {f\"gate {name}\": runs[0.015].signals[name] for name in state[1:]},\n",
    "    xlabel=\"time [ms]\",\n",
    "    ylabel=\"gate opening\",\n",
    "    title=\"Gates during the action potential (ΔV = 15 mV)\",\n",
    "    legend=\"center right\",\n",
    "    ax=fig[1],\n",
    ")\n",
    "plots.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Replace the initial displacement by a constant stimulus current (a `source` block added to\n",
    "the current balance): above about 6 µA/cm² the membrane fires repetitively. Raise the temperature\n",
    "with `HodgkinHuxley1952(temperature=...)` and the spike becomes shorter and smaller through the\n",
    "built-in $Q_{10}=3$ of the rates. The propagating action potential along the axon is the\n",
    "monodomain cable equation with the same channel set (`Monodomain`)."
   ]
  }
 ]
}
