Skip to content

Neuron

The immutable neuron model: ion channels, membrane properties, ion concentrations, temperature, and optional calcium dynamics.

neuroclamp.Neuron dataclass

Conductance-based neuron model for simulating action potentials.

All parameters are fixed at construction time. The class is immutable (frozen) to prevent accidental mutation of parameters after the reversal potentials have been computed.

Attributes:

Name Type Description
channels tuple[IonChannel, ...]

Tuple of ion channels carried by the membrane. Each channel is fully configured with its own g_max and kinetics; there is no separate "core" Na/K slot. Channel names must be unique.

C_m float

Membrane capacitance in uF/cm^2.

v_rest float

Resting potential in mV.

Na_out float

Extracellular sodium concentration in mM.

Na_in float

Intracellular sodium concentration in mM.

K_out float

Extracellular potassium concentration in mM.

K_in float

Intracellular potassium concentration in mM.

Ca_out float

Extracellular calcium concentration in mM.

Ca_in float

Intracellular calcium concentration in mM.

T float

Temperature in Kelvin.

Q10 float

Q10 temperature coefficient for gating kinetics (dimensionless). Gating rate constants are scaled by Q10^((T - T_ref) / 10). A value of 1.0 disables temperature scaling entirely.

T_ref float

Reference temperature in Kelvin at which the gating rate constants were measured. Defaults to 295.15 K (22 °C), matching the original HH52 squid axon experimental conditions.

calcium_dynamics CalciumDynamics | None

Optional calcium dynamics model.

area_cm2 float | None

Total membrane surface area in cm². Optional physical attribute of the cell that is not read by the ODE solver — HH dynamics in this single-compartment model are scale-invariant in the per-area units (mS/cm², µF/cm², µA/cm²) used everywhere else. Surface area is consumed by the analysis layer to convert the per-area passive properties (R_in in kΩ·cm², C_m in µF/cm²) into absolute MΩ / pF for display. None means absolute units are not available for this neuron.

Cached properties (built on first access): all_gating_variables: Flat tuple of every gating variable across all channels, in channel-declaration order. q10_factor: Dimensionless scaling factor Q10^((T - T_ref) / 10) applied to all gating rate constants at simulation time. reversal_potentials: Dict mapping each non-Ca²⁺ channel name to its reversal potential in mV, computed once on first access.

Source code in neuroclamp/neuron.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
@dataclass(frozen=True)
class Neuron:
    """Conductance-based neuron model for simulating action potentials.

    All parameters are fixed at construction time. The class is immutable
    (frozen) to prevent accidental mutation of parameters after the reversal
    potentials have been computed.

    Attributes:
        channels: Tuple of ion channels carried by the membrane. Each channel
            is fully configured with its own ``g_max`` and kinetics; there is
            no separate "core" Na/K slot.  Channel names must be unique.
        C_m: Membrane capacitance in uF/cm^2.
        v_rest: Resting potential in mV.
        Na_out: Extracellular sodium concentration in mM.
        Na_in: Intracellular sodium concentration in mM.
        K_out: Extracellular potassium concentration in mM.
        K_in: Intracellular potassium concentration in mM.
        Ca_out: Extracellular calcium concentration in mM.
        Ca_in: Intracellular calcium concentration in mM.
        T: Temperature in Kelvin.
        Q10: Q10 temperature coefficient for gating kinetics (dimensionless).
            Gating rate constants are scaled by ``Q10^((T - T_ref) / 10)``.
            A value of 1.0 disables temperature scaling entirely.
        T_ref: Reference temperature in Kelvin at which the gating rate
            constants were measured.  Defaults to 295.15 K (22 °C), matching
            the original HH52 squid axon experimental conditions.
        calcium_dynamics: Optional calcium dynamics model.
        area_cm2: Total membrane surface area in cm².  Optional physical
            attribute of the cell that is **not** read by the ODE solver —
            HH dynamics in this single-compartment model are scale-invariant
            in the per-area units (mS/cm², µF/cm², µA/cm²) used everywhere
            else.  Surface area is consumed by the analysis layer to convert
            the per-area passive properties (R_in in kΩ·cm², C_m in µF/cm²)
            into absolute MΩ / pF for display.  ``None`` means absolute units
            are not available for this neuron.

    Cached properties (built on first access):
        all_gating_variables: Flat tuple of every gating variable across all
            channels, in channel-declaration order.
        q10_factor: Dimensionless scaling factor ``Q10^((T - T_ref) / 10)``
            applied to all gating rate constants at simulation time.
        reversal_potentials: Dict mapping each non-Ca²⁺ channel name to its
            reversal potential in mV, computed once on first access.
    """

    # Ion channels — empty by default; presets supply the full list.
    channels: tuple[IonChannel, ...] = ()

    # Membrane properties
    C_m: float = DEFAULT_C_M
    v_rest: float = DEFAULT_V_REST

    # Ion concentrations (in mM)
    Na_out: float = DEFAULT_NA_OUT
    Na_in: float = DEFAULT_NA_IN
    K_out: float = DEFAULT_K_OUT
    K_in: float = DEFAULT_K_IN
    Ca_out: float = DEFAULT_CA_OUT
    Ca_in: float = DEFAULT_CA_IN

    # Temperature in Kelvin (37°C for mammalian cells)
    T: float = DEFAULT_T

    # Q10 temperature scaling for gating kinetics
    Q10: float = DEFAULT_Q10
    T_ref: float = DEFAULT_T_REF

    # Calcium dynamics — None by default for backward compatibility
    calcium_dynamics: CalciumDynamics | None = field(default=None)

    # Total membrane surface area in cm² — analysis-only metadata, not read
    # by the ODE solver.  Used by the passive-property analysis layer to
    # report absolute MΩ / pF instead of per-area density units.
    area_cm2: float | None = None

    def __post_init__(self) -> None:
        """Validate parameter values on construction."""
        if self.C_m <= 0:
            raise ValueError("Membrane capacitance (C_m) must be positive.")
        if self.T <= 0:
            raise ValueError("Temperature (T) must be positive (in Kelvin).")
        if self.Q10 <= 0:
            raise ValueError("Q10 must be positive.")
        if self.T_ref <= 0:
            raise ValueError("T_ref must be positive (in Kelvin).")
        if self.area_cm2 is not None and self.area_cm2 <= 0:
            raise ValueError("area_cm2 must be positive when provided.")
        for name, value in [
            ("Na_out", self.Na_out),
            ("Na_in", self.Na_in),
            ("K_out", self.K_out),
            ("K_in", self.K_in),
            ("Ca_out", self.Ca_out),
            ("Ca_in", self.Ca_in),
        ]:
            if value <= 0:
                raise ValueError(f"Ion concentration ({name}) must be positive.")
        ch_names = [ch.name for ch in self.channels]
        if len(ch_names) != len(set(ch_names)):
            raise ValueError(f"Channel names must be unique, got {ch_names}.")
        logger.debug(
            "Neuron: C_m=%.2f T=%.1f K Q10=%.1f T_ref=%.1f K channels=%s calcium=%s",
            self.C_m,
            self.T,
            self.Q10,
            self.T_ref,
            ch_names if ch_names else "none",
            "enabled" if self.calcium_dynamics is not None else "disabled",
        )

    @cached_property
    def q10_factor(self) -> float:
        """Return the Q10 temperature scaling factor for gating rate constants.

        Computes ``Q10^((T - T_ref) / 10)`` where both temperatures are in
        Kelvin.  A value of 1.0 (obtained when ``T == T_ref`` or ``Q10 == 1``)
        means no scaling is applied.

        Returns:
            Dimensionless multiplicative factor applied to all gating alpha/beta
            rate constants during simulation.
        """
        return self.Q10 ** ((self.T - self.T_ref) / 10.0)

    @cached_property
    def all_gating_variables(self) -> tuple[GatingVariable, ...]:
        """Return a flat tuple of all gating variables across all channels.

        Returns:
            Tuple of GatingVariable objects from all channels, in the order
            the channels and their gating variables are declared.
        """
        result: list[GatingVariable] = []
        for ch in self.channels:
            result.extend(ch.gating_variables)
        return tuple(result)

    @cached_property
    def reversal_potentials(self) -> dict[str, float]:
        """Return constant reversal potentials for all non-Ca²⁺ channels.

        Because this dataclass is frozen, ion concentrations and temperature
        are constant over the neuron's lifetime, so non-Ca²⁺ channels always
        have the same reversal potential.  Building the map lazily here
        eliminates a ``numpy.log`` call per channel per RK4 substep.

        Ca²⁺-carrying channels are excluded because their reversal potential
        depends on the live intracellular Ca²⁺ concentration, which changes
        each substep.  :meth:`~neuroclamp.IonChannel.compute_current` recomputes
        E_Ca from live ``ca_i`` for those channels.

        Returns:
            Dict mapping each non-Ca²⁺ channel name to its reversal potential
            in mV.
        """
        return {
            ch.name: ch.reversal_potential(self)
            for ch in self.channels
            if not ch.carries_calcium
        }

    def ion_concentrations(self, species: IonSpecies) -> tuple[float, float]:
        """Return the extracellular and intracellular concentrations for an ion.

        Used by :class:`~neuroclamp.channels.IonChannel` to look up the
        concentrations needed for dynamic reversal potential computation.

        Args:
            species: The ion species to look up.

        Returns:
            A ``(C_out, C_in)`` tuple of concentrations in mM.

        Raises:
            ValueError: If *species* is not recognized.
        """
        if species is IonSpecies.SODIUM:
            return self.Na_out, self.Na_in
        if species is IonSpecies.POTASSIUM:
            return self.K_out, self.K_in
        if species is IonSpecies.CALCIUM:
            return self.Ca_out, self.Ca_in
        raise ValueError(f"Unknown ion species: {species!r}")  # pragma: no cover

q10_factor cached property

q10_factor

Return the Q10 temperature scaling factor for gating rate constants.

Computes Q10^((T - T_ref) / 10) where both temperatures are in Kelvin. A value of 1.0 (obtained when T == T_ref or Q10 == 1) means no scaling is applied.

Returns:

Type Description
float

Dimensionless multiplicative factor applied to all gating alpha/beta

float

rate constants during simulation.

all_gating_variables cached property

all_gating_variables

Return a flat tuple of all gating variables across all channels.

Returns:

Type Description
GatingVariable

Tuple of GatingVariable objects from all channels, in the order

...

the channels and their gating variables are declared.

reversal_potentials cached property

reversal_potentials

Return constant reversal potentials for all non-Ca²⁺ channels.

Because this dataclass is frozen, ion concentrations and temperature are constant over the neuron's lifetime, so non-Ca²⁺ channels always have the same reversal potential. Building the map lazily here eliminates a numpy.log call per channel per RK4 substep.

Ca²⁺-carrying channels are excluded because their reversal potential depends on the live intracellular Ca²⁺ concentration, which changes each substep. :meth:~neuroclamp.IonChannel.compute_current recomputes E_Ca from live ca_i for those channels.

Returns:

Type Description
dict[str, float]

Dict mapping each non-Ca²⁺ channel name to its reversal potential

dict[str, float]

in mV.

__post_init__

__post_init__()

Validate parameter values on construction.

Source code in neuroclamp/neuron.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def __post_init__(self) -> None:
    """Validate parameter values on construction."""
    if self.C_m <= 0:
        raise ValueError("Membrane capacitance (C_m) must be positive.")
    if self.T <= 0:
        raise ValueError("Temperature (T) must be positive (in Kelvin).")
    if self.Q10 <= 0:
        raise ValueError("Q10 must be positive.")
    if self.T_ref <= 0:
        raise ValueError("T_ref must be positive (in Kelvin).")
    if self.area_cm2 is not None and self.area_cm2 <= 0:
        raise ValueError("area_cm2 must be positive when provided.")
    for name, value in [
        ("Na_out", self.Na_out),
        ("Na_in", self.Na_in),
        ("K_out", self.K_out),
        ("K_in", self.K_in),
        ("Ca_out", self.Ca_out),
        ("Ca_in", self.Ca_in),
    ]:
        if value <= 0:
            raise ValueError(f"Ion concentration ({name}) must be positive.")
    ch_names = [ch.name for ch in self.channels]
    if len(ch_names) != len(set(ch_names)):
        raise ValueError(f"Channel names must be unique, got {ch_names}.")
    logger.debug(
        "Neuron: C_m=%.2f T=%.1f K Q10=%.1f T_ref=%.1f K channels=%s calcium=%s",
        self.C_m,
        self.T,
        self.Q10,
        self.T_ref,
        ch_names if ch_names else "none",
        "enabled" if self.calcium_dynamics is not None else "disabled",
    )

ion_concentrations

ion_concentrations(species)

Return the extracellular and intracellular concentrations for an ion.

Used by :class:~neuroclamp.channels.IonChannel to look up the concentrations needed for dynamic reversal potential computation.

Parameters:

Name Type Description Default
species IonSpecies

The ion species to look up.

required

Returns:

Type Description
tuple[float, float]

A (C_out, C_in) tuple of concentrations in mM.

Raises:

Type Description
ValueError

If species is not recognized.

Source code in neuroclamp/neuron.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def ion_concentrations(self, species: IonSpecies) -> tuple[float, float]:
    """Return the extracellular and intracellular concentrations for an ion.

    Used by :class:`~neuroclamp.channels.IonChannel` to look up the
    concentrations needed for dynamic reversal potential computation.

    Args:
        species: The ion species to look up.

    Returns:
        A ``(C_out, C_in)`` tuple of concentrations in mM.

    Raises:
        ValueError: If *species* is not recognized.
    """
    if species is IonSpecies.SODIUM:
        return self.Na_out, self.Na_in
    if species is IonSpecies.POTASSIUM:
        return self.K_out, self.K_in
    if species is IonSpecies.CALCIUM:
        return self.Ca_out, self.Ca_in
    raise ValueError(f"Unknown ion species: {species!r}")  # pragma: no cover

neuroclamp.CalciumDynamics dataclass

Parameters and ODE for intracellular Ca2+ concentration dynamics.

Models the change in intracellular Ca2+ concentration as::

d[Ca2+]/dt = -alpha_ca * I_Ca - ([Ca2+] - ca_rest) / tau_ca

Sign convention: positive current is outward (HH convention), so an inward Ca2+ current is negative, making -alpha_ca * I_Ca positive (increasing [Ca2+]_i).

Attributes:

Name Type Description
alpha_ca float

Scaling factor converting Ca2+ current to concentration change in mM / (µA/cm² · ms).

tau_ca float

Time constant for Ca2+ removal/buffering in ms.

ca_rest float

Resting intracellular Ca2+ concentration in mM. This is the ODE equilibrium target (the concentration the pumps/buffers maintain in the absence of Ca2+ current) and is NOT necessarily equal to the true simulation starting concentration when window currents are present at rest. See ca_init below.

ca_init float | None

Initial intracellular Ca2+ concentration in mM used at the start of :func:~neuroclamp.simulate_current_clamp. When None (default), ca_rest is used. Set this explicitly when the true resting Ca2+ concentration differs from ca_rest due to persistent window currents at the resting potential (i.e. the coupled (V, Ca2+) equilibrium has ca_i > ca_rest). Use :func:~neuroclamp.find_coupled_equilibrium to compute the correct value.

Raises:

Type Description
ValueError

If alpha_ca <= 0, tau_ca <= 0, ca_rest < 0, or ca_init < 0.

Source code in neuroclamp/calcium.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@dataclass(frozen=True)
class CalciumDynamics:
    """Parameters and ODE for intracellular Ca2+ concentration dynamics.

    Models the change in intracellular Ca2+ concentration as::

        d[Ca2+]/dt = -alpha_ca * I_Ca - ([Ca2+] - ca_rest) / tau_ca

    Sign convention: positive current is outward (HH convention), so an
    inward Ca2+ current is negative, making ``-alpha_ca * I_Ca`` positive
    (increasing [Ca2+]_i).

    Attributes:
        alpha_ca: Scaling factor converting Ca2+ current to concentration
            change in mM / (µA/cm² · ms).
        tau_ca: Time constant for Ca2+ removal/buffering in ms.
        ca_rest: Resting intracellular Ca2+ concentration in mM.  This is
            the ODE equilibrium target (the concentration the pumps/buffers
            maintain in the absence of Ca2+ current) and is NOT necessarily
            equal to the true simulation starting concentration when window
            currents are present at rest.  See *ca_init* below.
        ca_init: Initial intracellular Ca2+ concentration in mM used at the
            start of :func:`~neuroclamp.simulate_current_clamp`.  When
            ``None`` (default), *ca_rest* is used.  Set this explicitly when
            the true resting Ca2+ concentration differs from *ca_rest* due to
            persistent window currents at the resting potential (i.e. the
            coupled (V, Ca2+) equilibrium has ca_i > ca_rest).  Use
            :func:`~neuroclamp.find_coupled_equilibrium` to compute the
            correct value.

    Raises:
        ValueError: If ``alpha_ca <= 0``, ``tau_ca <= 0``, ``ca_rest < 0``,
            or ``ca_init < 0``.
    """

    alpha_ca: float = DEFAULT_ALPHA_CA
    tau_ca: float = DEFAULT_TAU_CA
    ca_rest: float = DEFAULT_CA_REST
    ca_init: float | None = None

    def __post_init__(self) -> None:
        """Validate calcium dynamics parameters on construction."""
        if self.alpha_ca <= 0:
            raise ValueError(f"alpha_ca must be positive, got {self.alpha_ca}.")
        if self.tau_ca <= 0:
            raise ValueError(f"tau_ca must be positive, got {self.tau_ca}.")
        if self.ca_rest < 0:
            raise ValueError(f"ca_rest must be non-negative, got {self.ca_rest}.")
        if self.ca_init is not None and self.ca_init < 0:
            raise ValueError(f"ca_init must be non-negative, got {self.ca_init}.")

    def derivative(self, I_Ca: float, ca_i: float) -> float:
        """Compute the rate of change of intracellular Ca2+ concentration.

        Implements: d[Ca2+]/dt = -alpha_ca * I_Ca - (ca_i - ca_rest) / tau_ca

        Args:
            I_Ca: Total calcium current in µA/cm² (positive = outward).
            ca_i: Current intracellular Ca2+ concentration in mM.

        Returns:
            d[Ca2+]/dt in mM/ms.
        """
        return -self.alpha_ca * I_Ca - (ca_i - self.ca_rest) / self.tau_ca

__post_init__

__post_init__()

Validate calcium dynamics parameters on construction.

Source code in neuroclamp/calcium.py
52
53
54
55
56
57
58
59
60
61
def __post_init__(self) -> None:
    """Validate calcium dynamics parameters on construction."""
    if self.alpha_ca <= 0:
        raise ValueError(f"alpha_ca must be positive, got {self.alpha_ca}.")
    if self.tau_ca <= 0:
        raise ValueError(f"tau_ca must be positive, got {self.tau_ca}.")
    if self.ca_rest < 0:
        raise ValueError(f"ca_rest must be non-negative, got {self.ca_rest}.")
    if self.ca_init is not None and self.ca_init < 0:
        raise ValueError(f"ca_init must be non-negative, got {self.ca_init}.")

derivative

derivative(I_Ca, ca_i)

Compute the rate of change of intracellular Ca2+ concentration.

Implements: d[Ca2+]/dt = -alpha_ca * I_Ca - (ca_i - ca_rest) / tau_ca

Parameters:

Name Type Description Default
I_Ca float

Total calcium current in µA/cm² (positive = outward).

required
ca_i float

Current intracellular Ca2+ concentration in mM.

required

Returns:

Type Description
float

d[Ca2+]/dt in mM/ms.

Source code in neuroclamp/calcium.py
63
64
65
66
67
68
69
70
71
72
73
74
75
def derivative(self, I_Ca: float, ca_i: float) -> float:
    """Compute the rate of change of intracellular Ca2+ concentration.

    Implements: d[Ca2+]/dt = -alpha_ca * I_Ca - (ca_i - ca_rest) / tau_ca

    Args:
        I_Ca: Total calcium current in µA/cm² (positive = outward).
        ca_i: Current intracellular Ca2+ concentration in mM.

    Returns:
        d[Ca2+]/dt in mM/ms.
    """
    return -self.alpha_ca * I_Ca - (ca_i - self.ca_rest) / self.tau_ca