Skip to content

Hodgkin-Huxley

The Hodgkin-Huxley neuron.

  • Class: HodgkinHuxleySystem
  • Import: from skcomplex.systems.biology.neuroscience import HodgkinHuxleySystem
  • Field: biology/neuroscience
  • Topics: neuron, excitability, spiking, conductance
  • References:
    • Hodgkin and Huxley 1952
    • Rinzel and Miller 1980
    • Trzaska 2023
    • arXiv:2112.12147

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.biology.neuroscience import HodgkinHuxleySystem

trajectory = HodgkinHuxleySystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
v -65.0
I 10.0
C 1.0
g_na 120.0
g_k 36.0
g_l 0.3
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time continuous
Space none
Laws rate, update
Randomness unknown
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class HodgkinHuxleySystem(BaseSystem):
    """The Hodgkin-Huxley neuron.

    Its sodium and potassium channels produce action potentials.

    The gates start at their steady state at the initial potential, and the current is switched on at the start. A
    constant current above about 6.2 µA/cm² makes the neuron fire periodically, and a weaker one gives at most a few
    spikes before it settles. The system has the potential `neuron.v`, the gates `neuron.n`, `neuron.m`, and `neuron.h`,
    and its spikes as `spike` events.

    Args:
        v:
            The initial membrane potential in mV.

        I:
            The applied current in µA/cm².

        C:
            The membrane capacitance in µF/cm².

        g_na:
            The maximal sodium conductance in mS/cm².

        g_k:
            The maximal potassium conductance in mS/cm².

        g_l:
            The leak conductance in mS/cm².

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.biology.neuroscience import HodgkinHuxleySystem
        >>> round(HodgkinHuxleySystem().prepare().system_.elements[0].h, 4)
        0.5961
    """

    field = 'biology/neuroscience'
    topics = ('neuron', 'excitability', 'spiking', 'conductance')
    references = ('Hodgkin and Huxley 1952', 'Rinzel and Miller 1980', 'Trzaska 2023', 'arXiv:2112.12147')
    until = 50.0
    dt = 0.1

    def __init__(
        self,
        v: float = -65.0,
        *,
        I: float = 10.0,
        C: float = 1.0,
        g_na: float = 120.0,
        g_k: float = 36.0,
        g_l: float = 0.3,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.v = v
        self.I = I
        self.C = C
        self.g_na = g_na
        self.g_k = g_k
        self.g_l = g_l

    @staticmethod
    def _get_gate_rates(v: Expression) -> GateRates:
        """Return the opening and closing rates per ms of the gates `n`, `m`, and `h`.

        The rates are at a potential in mV.
        """
        return {
            'n': (0.01 * (v + 55) / (1 - exp(-(v + 55) / 10)), 0.125 * exp(-(v + 65) / 80)),
            'm': (0.1 * (v + 40) / (1 - exp(-(v + 40) / 10)), 4 * exp(-(v + 65) / 18)),
            'h': (0.07 * exp(-(v + 65) / 20), 1 / (1 + exp(-(v + 35) / 10))),
        }

    def _get_gate_kinetics(self, gate: str) -> Callable[[SimpleNamespace], list[BaseLaw]]:
        """Return the rate `alpha(v) (1 - x) - beta(v) x` of a gate `x`.

        The rate is a function of the namespace of the neuron.
        """

        def kinetics(s: SimpleNamespace) -> list[BaseLaw]:
            opening, closing = self._get_gate_rates(s.target.v)[gate]
            x = getattr(s.target, gate)
            return [RateLaw(x, opening * (1 - x) - closing * x)]

        return kinetics

    def _get_resting_gates(self, v: float) -> dict[str, float]:
        """Return the steady-state opening of every gate at a fixed potential in mV."""
        return {
            gate: float(opening / (opening + closing)) for gate, (opening, closing) in self._get_gate_rates(v).items()
        }

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the Hodgkin-Huxley neuron.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        gates = self._get_resting_gates(self.v)
        self.system_ = System(
            self.label,
            elements=[
                HodgkinHuxleyElement(
                    'neuron',
                    v=self.v,
                    I=self.I,
                    C=self.C,
                    g_na=self.g_na,
                    g_k=self.g_k,
                    g_l=self.g_l,
                    n=gates['n'],
                    m=gates['m'],
                    h=gates['h'],
                ),
            ],
            interactions=[
                Interaction(
                    'applied_current',
                    roles={'target': 'neuron'},
                    laws=lambda s: [RateLaw(s.target.v, s.target.I / s.target.C)],
                ),
                Interaction(
                    'sodium_current',
                    roles={'target': 'neuron'},
                    laws=lambda s: [
                        RateLaw(
                            s.target.v,
                            -s.target.g_na * s.target.m**3 * s.target.h * (s.target.v - s.target.e_na) / s.target.C,
                        ),
                    ],
                ),
                Interaction(
                    'potassium_current',
                    roles={'target': 'neuron'},
                    laws=lambda s: [
                        RateLaw(s.target.v, -s.target.g_k * s.target.n**4 * (s.target.v - s.target.e_k) / s.target.C),
                    ],
                ),
                Interaction(
                    'leak_current',
                    roles={'target': 'neuron'},
                    laws=lambda s: [RateLaw(s.target.v, -s.target.g_l * (s.target.v - s.target.e_l) / s.target.C)],
                ),
                *[
                    Interaction(f'{gate}_gating', roles={'target': 'neuron'}, laws=self._get_gate_kinetics(gate))
                    for gate in ('n', 'm', 'h')
                ],
                Interaction(
                    'spike',
                    roles={'target': 'neuron'},
                    laws=lambda s: [EventLaw(SR(s.target.v), None, 1, False, label='spike')],
                ),
            ],
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

  • HodgkinHuxleyElement, from Element

Interactions:

  • Interaction
class HodgkinHuxleyElement(Element):
    """Squid giant axon membrane of Hodgkin and Huxley.

    The membrane has sodium, potassium, and leak currents.

    The potential follows `C v' = I - g_Na m³ h (v - E_Na) - g_K n⁴ (v - E_K) - g_L (v - E_L)`, and each gate `x` of
    `n`, `m`, and `h` relaxes as `x' = alpha_x(v) (1 - x) - beta_x(v) x`, in the modern convention with rest near -65
    mV. Upward crossings of 0 mV are recorded as `spike` events. Units are mV, ms, mS/cm², and µA/cm². The element holds
    the states and parameters and has no laws of its own: the current, gating, and crossing interactions of
    `HodgkinHuxleySystem` read its parameters.

    Args:
        label:
            The label of the neuron.

        v:
            The initial membrane potential.

        n:
            The initial potassium activation.

        m:
            The initial sodium activation.

        h:
            The initial sodium inactivation.

        C:
            The membrane capacitance.

        g_na:
            The maximal sodium conductance.

        g_k:
            The maximal potassium conductance.

        g_l:
            The leak conductance.

        e_na:
            The sodium reversal potential.

        e_k:
            The potassium reversal potential.

        e_l:
            The leak reversal potential.

        I:
            The applied current.

    Examples:
        >>> from skcomplex.systems.biology.neuroscience import HodgkinHuxleyElement
        >>> HodgkinHuxleyElement('axon', I=10.0).g_na
        120.0
    """

    def __init__(
        self,
        label: str,
        *,
        v: float = -65.0,
        n: Annotated[float, RealSet.closed_open(0, oo)] = 0.3177,
        m: Annotated[float, RealSet.closed_open(0, oo)] = 0.0529,
        h: Annotated[float, RealSet.closed_open(0, oo)] = 0.5961,
        C: Annotated[float, RealSet.open(0, oo)] = 1.0,
        g_na: Annotated[float, RealSet.closed_open(0, oo)] = 120.0,
        g_k: Annotated[float, RealSet.closed_open(0, oo)] = 36.0,
        g_l: Annotated[float, RealSet.closed_open(0, oo)] = 0.3,
        e_na: float = 50.0,
        e_k: float = -77.0,
        e_l: float = -54.387,
        I: float = 10.0,
    ) -> None:
        super().__init__(label)
        self.v = v
        self.n = n
        self.m = m
        self.h = h
        self.C = C
        self.g_na = g_na
        self.g_k = g_k
        self.g_l = g_l
        self.e_na = e_na
        self.e_k = e_k
        self.e_l = e_l
        self.I = I

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None

Equations

The equations are those that symbolic returns for the system with its default parameters.

neuron.v: diff(v_neuron(t), t) == (e_na_neuron - v_neuron(t))*g_na_neuron*h_neuron(t)*m_neuron(t)^3/C_neuron + (e_k_neuron - v_neuron(t))*g_k_neuron*n_neuron(t)^4/C_neuron + (e_l_neuron - v_neuron(t))*g_l_neuron/C_neuron + I_neuron/C_neuron
neuron.n: diff(n_neuron(t), t) == -0.125*e^(-1/80*v_neuron(t) - 13/16)*n_neuron(t) + (n_neuron(t) - 1)*(0.01*v_neuron(t) + 0.55)/(e^(-1/10*v_neuron(t) - 11/2) - 1)
neuron.m: diff(m_neuron(t), t) == -4*e^(-1/18*v_neuron(t) - 65/18)*m_neuron(t) + (m_neuron(t) - 1)*(0.1*v_neuron(t) + 4.0)/(e^(-1/10*v_neuron(t) - 4) - 1)
neuron.h: diff(h_neuron(t), t) == -0.07*(h_neuron(t) - 1)*e^(-1/20*v_neuron(t) - 13/4) - h_neuron(t)/(e^(-1/10*v_neuron(t) - 7/2) + 1)