{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# Cell\n",
    "\n",
    "The core components of `Cell` include the following three parts:\n",
    "- `HHTypeNeuron`: The base class that provides the interface for HH-type neurons.\n",
    "- `SingleCompartment`: A single-compartment neuron model, suitable for neurons with simple structures.\n",
    "- `MultiCompartment`: A multi-compartment neuron model, suitable for neurons where spatial structure needs to be considered.\n",
    "\n",
    "Together, these three components form a modeling system that spans from local membrane regions to the complete neuronal structure. Through inheritance, they share a unified modeling interface and, with the acceleration and computational power of `brainstate`, provide strong support for neuronal modeling at the cellular level.\n",
    "\n",
    "## HHTypedNeuron\n",
    "\n",
    "### Electrophysiological Properties\n",
    "\n",
    "`HHTypedNeuron` is a fundamental abstract class in `braincell` for constructing Hodgkin–Huxley-type neuron models. In this modeling framework, the membrane potential of a neuron is determined by multiple currents:\n",
    "- Active currents: Controlled by sodium and potassium channels with voltage-gated properties.\n",
    "- Passive currents: Such as leak currents.\n",
    "- Capacitive currents: Arising from changes in membrane potential.\n",
    "\n",
    "This modeling approach was first proposed by Hodgkin and Huxley in 1952 to explain the mechanism of action potentials in the squid giant axon.\n",
    "The HH model not only laid the foundation of modern neuronal modeling but also remains a core component of many models today.\n",
    "\n",
    "The equivalent circuit diagram of the classical HH model is shown below:\n",
    "\n",
    "![Equivalent circuit diagram](../_static/hh.png)\n",
    "\n",
    "In the classical HH model, the membrane potential $V$ is governed by the following equation:\n",
    "\n",
    "$$\n",
    "C_m \\frac{dV}{dt} = - (I_{\\text{Na}} + I_{\\text{K}} + I_L) + I_{\\text{ext}}\n",
    "$$\n",
    "\n",
    "Where:\n",
    "- $C_m$: Membrane capacitance\n",
    "- $I_{\\text{Na}}, I_{\\text{K}}$: Ionic currents from sodium and potassium channels\n",
    "- $I_L$: Leak current\n",
    "- $I_{\\text{ext}}$: External injected current (e.g., current applied through a stimulating electrode)\n",
    "\n",
    "### Modeling Implementation\n",
    "\n",
    "`HHTypedNeuron` inherits from:\n",
    "- `Dynamics`: For defining state variables and differential equations.\n",
    "- `Container`: For managing modules.\n",
    "- `DiffEqModule`: A differential equation module that supports automatic modeling.\n",
    "\n",
    "With `HHTypedNeuron`, you can flexibly combine ion channels to construct diverse dynamical configurations.\n",
    "Moreover, since `HHTypedNeuron` is deeply integrated with `brainstate`, it also supports automatic differentiation and vectorized simulations, enabling batch simulations and model training.\n",
    "\n",
    "Notably, in `braincell`, all neuron models are built upon the HH framework.\n",
    "Specifically, both `SingleCompartment` and `MultiCompartment` inherit from `HHTypedNeuron`, sharing a unified interface and modeling framework. This allows us to reuse the same ion channel mechanisms and dynamical modeling strategies across neurons with different structural complexities.\n",
    "\n",
    "## SingleCompartment\n",
    "\n",
    "### Electrophysiological Properties\n",
    "\n",
    "`SingleCompartment` represents a neuron model without explicit spatial structure, used for modeling conductance-based neurons with a single compartment. Its membrane potential is governed by the following differential equation:\n",
    "\n",
    "$$\n",
    "C_m \\frac{dV}{dt} = \\sum_j g_j(E_j - V) + I_{\\text{ext}}\n",
    "$$\n",
    "\n",
    "Where:\n",
    "- $C_m$: Membrane capacitance\n",
    "- $V$: Membrane potential\n",
    "- $g_j$: Conductance of the $j$-th ion channel\n",
    "- $E_j$: Reversal potential of the $j$-th channel\n",
    "- $I_{\\text{ext}}$: External injected current\n",
    "\n",
    "The conductance $g_j$ of each channel is determined by its gating variables:\n",
    "\n",
    "$$\n",
    "g_j = \\bar{g}_j \\cdot M^x \\cdot N^y\n",
    "$$\n",
    "\n",
    "Where:\n",
    "- $\\bar{g}_j$: Maximum conductance\n",
    "- $M$: Activation variable\n",
    "- $N$: Inactivation variable\n",
    "- $x, y$: Exponents depending on channel type\n",
    "\n",
    "The gating variables follow first-order kinetics:\n",
    "\n",
    "$$\n",
    "\\frac{dx}{dt} = \\phi_x \\cdot \\frac{x_\\infty(V) - x}{\\tau_x(V)}\n",
    "$$\n",
    "\n",
    "Or equivalently:\n",
    "\n",
    "$$\n",
    "\\frac{dx}{dt} = \\phi_x \\left( \\alpha_x (1 - x) - \\beta_x x \\right)\n",
    "$$\n",
    "\n",
    "Where:\n",
    "- $x \\in \\{M, N\\}$\n",
    "- $\\phi_x$: Temperature factor\n",
    "- $x_\\infty$: Steady-state value\n",
    "- $\\tau_x$: Time constant\n",
    "- $\\alpha_x$, $\\beta_x$: Rate constants\n",
    "\n",
    "### Modeling Implementation\n",
    "\n",
    "The implementation of `SingleCompartment` is relatively straightforward: simply inherit from `HHTypedNeuron` and define the corresponding ion channels.\n",
    "\n",
    "Here is an example:\n",
    "\n",
    "```python\n",
    "class HH(braincell.SingleCompartment):\n",
    "    def __init__(self, size, solver='rk4'):\n",
    "        super().__init__(size, solver=solver)\n",
    "\n",
    "        self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)\n",
    "        self.na.add(INa=braincell.channel.INa_HH1952(size))\n",
    "\n",
    "        self.k = braincell.ion.PotassiumFixed(size, E=-77. * u.mV)\n",
    "        self.k.add(IK=braincell.channel.IK_HH1952(size))\n",
    "\n",
    "        self.IL = braincell.channel.IL(\n",
    "            size,\n",
    "            E=-54.387 * u.mV,\n",
    "            g_max=0.03 * (u.mS / u.cm **2)\n",
    "        )\n",
    "````\n",
    "\n",
    "In this example, we use `SingleCompartment` to construct a classical HH neuron with sodium (`INa`), potassium (`IK`), and leak (`IL`) currents, which together determine the electrophysiological properties of the neuron.\n",
    "\n",
    "As this example shows, `SingleCompartment` serves as a convenient modeling interface in `braincell`, greatly simplifying the construction of neurons and improving modeling efficiency.\n",
    "\n",
    "## MultiCompartment\n",
    "\n",
    "### Electrophysiological Properties\n",
    "\n",
    "In real neurons, the cell is not just a point-like structure but instead has complex spatial morphology—dendrites, axons, and soma—all of which strongly influence neuronal behavior. To simulate spatial propagation of electrical signals more accurately, we introduce `MultiCompartment`.\n",
    "\n",
    "A neuron is not simply a capacitor but behaves as a cable-like system with spatial structure. Cable theory describes how electrical signals propagate along thin neuronal processes such as dendrites or axons. Originating from engineering transmission line theory, in neuroscience it treats dendrites and axons as one-dimensional cables, allowing us to simulate spatiotemporal variations in signals.\n",
    "\n",
    "In computational models, cable theory is typically implemented through compartmental modeling: the neuron is divided into discrete compartments, each represented as an equivalent circuit unit. Neighboring compartments are coupled by axial resistances, approximating the spatial structure.\n",
    "This is precisely the core principle of `MultiCompartment` modeling.\n",
    "\n",
    "In this approach, the neuron is divided into multiple spatially connected compartments, each with independent membrane potentials and ionic currents, while being coupled via axial resistances:\n",
    "\n",
    "* Each compartment has its own distribution of ion channels and currents.\n",
    "* Compartments are interconnected via resistances that allow axial current flow.\n",
    "* This enables modeling of phenomena such as attenuation, delay, or reflection of signals along dendrites or axons.\n",
    "\n",
    "The schematic of cable theory is shown below:\n",
    "\n",
    "![Cable theory schematic](../_static/dianlan.png)\n",
    "\n",
    "The electrical behavior is governed by the cable equation:\n",
    "\n",
    "$$\n",
    "C_m \\frac{dV_i}{dt} = -I_{\\text{ion}, i} + \\sum_j \\frac{(V_j - V_i)}{R_{ij}} + I_{\\text{ext}, i}\n",
    "$$\n",
    "\n",
    "Where:\n",
    "\n",
    "* $C_m$: Membrane capacitance\n",
    "* $I_{\\text{ion}, i}$: Ionic current in the $i$-th compartment\n",
    "* $\\frac{(V_j - V_i)}{R_{ij}}$: Axial current flowing from neighboring compartment $j$ to $i$\n",
    "* $R_{ij}$: Axial resistance between compartments $i$ and $j$\n",
    "* $I_{\\text{ext}, i}$: External injected current into compartment $i$\n",
    "\n",
    "Thanks to its spatial modeling capabilities, the multi-compartment model is widely used to study dendritic integration, action potential propagation along axons, and other spatially dependent phenomena.\n",
    "\n",
    "### Modeling Implementation\n",
    "\n",
    "The implementation of `MultiCompartment` is conceptually similar to `SingleCompartment`, but requires specifying additional parameters, most importantly the morphology.\n",
    "\n",
    "Here is an example:\n",
    "\n",
    "```python\n",
    "class HTC(braincell.MultiCompartment):\n",
    "    def __init__(self, size, solver: str = 'staggered'):\n",
    "        morphology = braincell.Morphology.from_swc(...)\n",
    "        super().__init__(size,\n",
    "                         morphology=morphology,   # the only difference from SingleCompartment\n",
    "                         V_initializer=braintools.init.Constant(-65. * u.mV),\n",
    "                         V_th=20. * u.mV,\n",
    "                         solver=solver)\n",
    "\n",
    "        self.na = braincell.ion.SodiumFixed(size, E=50. * u.mV)\n",
    "        self.na.add(INa=braincell.channel.INa_Ba2002(size, V_sh=-30 * u.mV))\n",
    "\n",
    "        self.k = braincell.ion.PotassiumFixed(size, E=-90. * u.mV)\n",
    "        self.k.add(IDR=braincell.channel.IKDR_Ba2002(size, V_sh=-30. * u.mV, phi=0.25))\n",
    "```\n",
    "\n",
    "This example demonstrates how to construct a simple multi-compartment neuron model with sodium and potassium channels. Of course, the model can be extended further by adding additional channels or input currents.\n",
    "\n",
    "The critical difference between `SingleCompartment` and `MultiCompartment` lies in the introduction of morphology.\n",
    "\n",
    "In neuronal modeling, `morphology` refers to the spatial structure of the neuron, including:\n",
    "\n",
    "* Soma\n",
    "* Dendrites\n",
    "* Axon\n",
    "* Spatial connectivity\n",
    "\n",
    "In short:\n",
    "\n",
    "* In `SingleCompartment`, the neuron is modeled as a point.\n",
    "* In `MultiCompartment`, the neuron is modeled as a network of compartments defined by its morphology, allowing more realistic dynamical simulations.\n",
    "\n",
    "Through `MultiCompartment`, we can easily construct neuron models with detailed structures and diverse behaviors."
   ],
   "id": "8c8f2d9874f8753f"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
