{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Electrotonic decay along a passive cable\n",
    "\n",
    "A long, thin passive nerve fibre (a \"cable\") is held at a fixed membrane\n",
    "potential $V_0$ at one end ($x=0$). The other end is **sealed** (no current\n",
    "leaves it). Away from the clamped end the potential decays smoothly because\n",
    "current leaks steadily across the membrane while it spreads along the fibre.\n",
    "\n",
    "The passive membrane is modelled as a monodomain cable with a single linear\n",
    "**leak channel** of conductance $g_L$ and reversal potential $E_L$:\n",
    "\n",
    "$$C_m\\,\\frac{\\partial V}{\\partial t}\n",
    "   = \\frac{\\sigma}{\\beta}\\,\\frac{\\partial^2 V}{\\partial x^2}\n",
    "     - g_L\\,(V-E_L),$$\n",
    "\n",
    "with axial conductivity $\\sigma$, surface-to-volume ratio $\\beta$ and membrane\n",
    "capacitance $C_m$. OneSimulation integrates this in time on a real 1D line\n",
    "mesh until the transient has died out and only the steady profile remains.\n",
    "\n",
    "**Reference.** In steady state ($\\partial_t V=0$) the deviation\n",
    "$v=V-E_L$ obeys $\\lambda^2 v''-v=0$ with the **space constant**\n",
    "\n",
    "$$\\lambda=\\sqrt{\\dfrac{\\sigma}{\\beta\\,g_L}}\\;=\\;\\sqrt{\\dfrac{r_m}{r_i}}.$$\n",
    "\n",
    "For a clamp $v(0)=v_0$ at $x=0$ and a sealed end $v'(L)=0$ at $x=L$ the\n",
    "closed-form solution is the hyperbolic-cosine profile\n",
    "\n",
    "$$v(x)=v_0\\,\\frac{\\cosh\\!\\big((L-x)/\\lambda\\big)}{\\cosh(L/\\lambda)}.$$\n",
    "\n",
    "We check the computed steady profile against this form and also recover the\n",
    "space constant $\\lambda$ from a fit of the numerical solution."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from onesim.cad.d1 import Line\n",
    "from onesim.meshing import StructuredLineMesher\n",
    "from onesim.physics.biophysics import (\n",
    "    MembraneChannel,\n",
    "    MembraneCurrentElectrode,\n",
    "    MembraneKinetics,\n",
    "    MembraneVoltageClamp,\n",
    "    Monodomain,\n",
    ")\n",
    "from onesim.visualization import plots, theme\n",
    "\n",
    "theme.set()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "The values are freely adjustable and in SI units. They are chosen so that the\n",
    "cable is several space constants long, which makes the electrotonic decay\n",
    "clearly visible while the sealed end still has a small, non-zero potential."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "L = 0.06\n",
    "cells = 240\n",
    "sigma = 1.0\n",
    "beta = 2000.0\n",
    "C_m = 0.01\n",
    "g_L = 2.0\n",
    "E_L = -0.065\n",
    "delta = 0.025\n",
    "V0 = E_L + delta\n",
    "\n",
    "lam = np.sqrt(sigma / (beta * g_L))\n",
    "print(f\"space constant lambda = {lam*1000:.3f} mm,  L/lambda = {L/lam:.2f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Characteristic times: membrane charging C_m/g_L and axial spreading L^2 * beta\n",
    "* C_m / sigma. The run must be long enough for both to settle."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "D = sigma / (beta * C_m)\n",
    "tau = max(C_m / g_L, L * L / D)\n",
    "end_time = 25.0 * tau\n",
    "print(\n",
    "    f\"diffusivity = {D:.3e} m^2/s,  settling time ~ {tau:.3f} s,  end time = {end_time:.3f} s\"\n",
    ")\n",
    "\n",
    "line = Line(start=(0.0, 0.0, 0.0), end=(L, 0.0, 0.0))\n",
    "mesh = StructuredLineMesher(cells=cells).generate(line)\n",
    "\n",
    "model = Monodomain(\n",
    "    conductivity=sigma,\n",
    "    capacitance=C_m,\n",
    "    surface_to_volume=beta,\n",
    "    membrane=MembraneKinetics(\n",
    "        channels=(\n",
    "            MembraneChannel(name=\"leak\", conductance=g_L, reversal_potential=E_L),\n",
    "        ),\n",
    "    ),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both ends carry an explicit boundary condition: a voltage clamp at x = 0 and a\n",
    "sealed (zero-current) electrode at x = L."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "electrodes = (\n",
    "    MembraneVoltageClamp(boundary=line.boundaries.start, voltage=lambda t: V0),\n",
    "    MembraneCurrentElectrode(boundary=line.boundaries.end, current_density=0.0),\n",
    ")\n",
    "\n",
    "times = np.linspace(0.0, end_time, 60)\n",
    "result = model.solve(\n",
    "    mesh=mesh,\n",
    "    times=times,\n",
    "    max_step=tau / 50.0,\n",
    "    initial_voltage=E_L,\n",
    "    electrodes=electrodes,\n",
    ")\n",
    "print(\"Mesh nodes:\", result.voltage.shape[1], \" stored times:\", len(result.times))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison with the closed-form steady profile\n",
    "\n",
    "The last stored time is deep in the steady regime. We compare the computed\n",
    "deviation from rest with the hyperbolic-cosine reference and also fit the space\n",
    "constant."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "x = result.coordinates[:, 0]\n",
    "order = np.argsort(x)\n",
    "x = x[order]\n",
    "v_num = result.voltage[-1][order] - E_L\n",
    "\n",
    "\n",
    "def reference(xx):\n",
    "    return delta * np.cosh((L - xx) / lam) / np.cosh(L / lam)\n",
    "\n",
    "\n",
    "v_ref = reference(x)\n",
    "max_abs_error = float(np.max(np.abs(v_num - v_ref)))\n",
    "rel_error = max_abs_error / delta\n",
    "print(\n",
    "    f\"maximum deviation from the cosh reference: {max_abs_error*1000:.4f} mV  ({100*rel_error:.2f} % of the clamp step)\"\n",
    ")\n",
    "\n",
    "drift = float(np.max(np.abs(result.voltage[-1] - result.voltage[-2])))\n",
    "print(f\"change over the last stored interval: {drift*1e6:.3f} uV\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recover the space constant from the numerical profile. Over the interior, away\n",
    "from the sealed end, the decay is essentially a pure exponential e^{-x/lambda}."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "interior = x < 0.6 * L\n",
    "slope = np.polyfit(x[interior], np.log(v_num[interior]), 1)[0]\n",
    "lam_fit = -1.0 / slope\n",
    "print(f\"fitted space constant: {lam_fit*1000:.3f} mm  (reference {lam*1000:.3f} mm)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Figure"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "xs = np.linspace(0.0, L, 400)\n",
    "plots.line(\n",
    "    points={\"OneSimulation\": (x * 1000, v_num * 1000)},\n",
    "    reference={\"cable equation (cosh)\": (xs * 1000, reference(xs) * 1000)},\n",
    "    vlines={f\"length constant = {lam * 1000:.2f} mm\": lam * 1000},\n",
    "    xlabel=\"position x [mm]\",\n",
    "    ylabel=\"depolarisation V - E_L [mV]\",\n",
    "    title=\"Steady passive cable\",\n",
    ")\n",
    "plots.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Going further\n",
    "\n",
    "Lengthen the cable and the sealed-end potential drops toward zero, recovering\n",
    "the semi-infinite result $v(x)=v_0 e^{-x/\\lambda}$. Raise the leak conductance\n",
    "$g_L$ (a leakier membrane) and the space constant $\\lambda$ shrinks, so the\n",
    "signal decays over a shorter distance."
   ]
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "OneSimulation (venv)",
   "language": "python",
   "name": "onesim"
  },
  "language_info": {
   "name": "python"
  }
 }
}
