Skip to content

Simulation

The current- and voltage-clamp runners and their structured-array result type, plus the electrochemistry and equilibrium helpers.

Runners

neuroclamp.simulate_current_clamp

simulate_current_clamp(neuron, current_external)

Simulate a current clamp experiment using the conductance-based neuron model.

In a current clamp experiment, current is injected into the cell membrane and the resulting voltage changes are recorded. This function simulates this process by computing the membrane voltage over time in response to the specified external current.

The simulation always uses :data:SIM_SAMPLING_FREQ (40 kHz, dt = 0.025 ms) as the integration time step.

All ion channels — core (INa, IK, INaL, IKL) and additional — are handled via a single unified loop. The result includes a field named after each channel for every channel (including core channels) and "Itotal".

When the neuron has calcium_dynamics configured, a ca_i field containing intracellular Ca²⁺ concentration in mM is included.

Parameters:

Name Type Description Default
neuron Neuron

The conductance-based neuron model to simulate.

required
current_external ndarray

External current in µA/cm² for a time-varying current waveform. The length of the array determines the simulation duration.

required

Returns:

Type Description
SimulationResult

Structured array with one element per time step. Field "time" holds

SimulationResult

the time axis in milliseconds. Remaining fields: "voltage",

SimulationResult

per-channel current fields, "Itotal", gating variable fields, and

SimulationResult

optionally "ca_i".

Source code in neuroclamp/clamp_simulations.py
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
def simulate_current_clamp(
    neuron: "Neuron",
    current_external: np.ndarray,
) -> SimulationResult:
    """Simulate a current clamp experiment using the conductance-based neuron model.

    In a current clamp experiment, current is injected into the cell membrane and
    the resulting voltage changes are recorded. This function simulates this process
    by computing the membrane voltage over time in response to the specified
    external current.

    The simulation always uses :data:`SIM_SAMPLING_FREQ` (40 kHz, dt = 0.025 ms)
    as the integration time step.

    All ion channels — core (INa, IK, INaL, IKL) and additional — are handled via a
    single unified loop. The result includes a field named after each channel
    for every channel (including core channels) and ``"Itotal"``.

    When the neuron has ``calcium_dynamics`` configured, a ``ca_i`` field
    containing intracellular Ca²⁺ concentration in mM is included.

    Args:
        neuron: The conductance-based neuron model to simulate.
        current_external: External current in µA/cm² for a time-varying current
            waveform. The length of the array determines the simulation duration.

    Returns:
        Structured array with one element per time step. Field ``"time"`` holds
        the time axis in milliseconds. Remaining fields: ``"voltage"``,
        per-channel current fields, ``"Itotal"``, gating variable fields, and
        optionally ``"ca_i"``.
    """
    if len(current_external) == 0:
        raise ValueError("current_external must not be empty.")
    if not np.all(np.isfinite(current_external)):
        raise ValueError("current_external must not contain NaN or Inf values.")

    cd = neuron.calcium_dynamics
    ca_i: float = (
        (cd.ca_init if cd.ca_init is not None else cd.ca_rest)
        if cd is not None
        else 0.0
    )
    gating_state = _initialize_gating_variables(neuron, neuron.v_rest, ca_i)
    return _simulate_current_clamp_core(
        neuron, current_external, neuron.v_rest, gating_state, ca_i
    )

neuroclamp.simulate_voltage_clamp

simulate_voltage_clamp(neuron, voltage_protocol)

Simulate a voltage clamp experiment using the conductance-based neuron model.

In a voltage clamp experiment, the membrane potential is held at specified values and the current required to maintain those voltages is measured. This function simulates this process by computing the ionic currents that would flow at each voltage step in the protocol.

The simulation always uses :data:SIM_SAMPLING_FREQ (40 kHz, dt = 0.025 ms) as the integration time step.

All ion channels — core (INa, IK, INaL, IKL) and additional — are handled via a single unified loop. The result includes a field named after each channel for every channel and a field for every gating variable.

When the neuron has calcium_dynamics configured, a ca_i field containing intracellular Ca²⁺ concentration in mM is included.

Parameters:

Name Type Description Default
neuron Neuron

The conductance-based neuron model to simulate.

required
voltage_protocol ndarray

Voltage values in mV to clamp the membrane at for each time step. The length of the array determines the simulation duration.

required

Returns:

Type Description
SimulationResult

Structured array with one element per time step. Field "time" holds

SimulationResult

the time axis in milliseconds. Remaining fields: "voltage",

SimulationResult

"Itotal", per-channel current fields, gating variable fields, and

SimulationResult

optionally "ca_i".

Source code in neuroclamp/clamp_simulations.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def simulate_voltage_clamp(
    neuron: "Neuron",
    voltage_protocol: np.ndarray,
) -> SimulationResult:
    """Simulate a voltage clamp experiment using the conductance-based neuron model.

    In a voltage clamp experiment, the membrane potential is held at specified
    values and the current required to maintain those voltages is measured. This
    function simulates this process by computing the ionic currents that would
    flow at each voltage step in the protocol.

    The simulation always uses :data:`SIM_SAMPLING_FREQ` (40 kHz, dt = 0.025 ms)
    as the integration time step.

    All ion channels — core (INa, IK, INaL, IKL) and additional — are handled via a
    single unified loop. The result includes a field named after each channel
    for every channel and a field for every gating variable.

    When the neuron has ``calcium_dynamics`` configured, a ``ca_i`` field
    containing intracellular Ca²⁺ concentration in mM is included.

    Args:
        neuron: The conductance-based neuron model to simulate.
        voltage_protocol: Voltage values in mV to clamp the membrane at for each
            time step. The length of the array determines the simulation duration.

    Returns:
        Structured array with one element per time step. Field ``"time"`` holds
        the time axis in milliseconds. Remaining fields: ``"voltage"``,
        ``"Itotal"``, per-channel current fields, gating variable fields, and
        optionally ``"ca_i"``.
    """
    if len(voltage_protocol) == 0:
        raise ValueError("voltage_protocol must not be empty.")
    if not np.all(np.isfinite(voltage_protocol)):
        raise ValueError("voltage_protocol must not contain NaN or Inf values.")

    ca_i: float = (
        neuron.calcium_dynamics.ca_rest if neuron.calcium_dynamics is not None else 0.0
    )
    gating_state = _initialize_gating_variables(neuron, voltage_protocol[0], ca_i)
    return _simulate_voltage_clamp_core(neuron, voltage_protocol, gating_state, ca_i)

neuroclamp.simulate_current_clamp_from_state

simulate_current_clamp_from_state(neuron, current_external, initial_V, initial_gating_state, initial_ca_i=0.0)

Simulate a current clamp experiment starting from an explicit neuron state.

Identical to :func:simulate_current_clamp except the initial membrane voltage, gating variables, and Ca²⁺ concentration are provided by the caller rather than initialized from neuron.v_rest. This is used by continuous simulation mode to carry neuron state across loop iterations.

Parameters:

Name Type Description Default
neuron Neuron

The conductance-based neuron model to simulate.

required
current_external ndarray

External current in µA/cm² for a time-varying current waveform.

required
initial_V float

Initial membrane voltage in mV.

required
initial_gating_state dict[str, float]

Gating variable values at the start of the run, keyed by variable name (e.g. {"m": 0.05, "h": 0.6, "n": 0.3}).

required
initial_ca_i float

Initial intracellular Ca²⁺ concentration in mM.

0.0

Returns:

Type Description
SimulationResult

Structured array with the same fields as :func:simulate_current_clamp.

Source code in neuroclamp/clamp_simulations.py
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
def simulate_current_clamp_from_state(
    neuron: "Neuron",
    current_external: np.ndarray,
    initial_V: float,
    initial_gating_state: dict[str, float],
    initial_ca_i: float = 0.0,
) -> SimulationResult:
    """Simulate a current clamp experiment starting from an explicit neuron state.

    Identical to :func:`simulate_current_clamp` except the initial membrane
    voltage, gating variables, and Ca²⁺ concentration are provided by the
    caller rather than initialized from ``neuron.v_rest``.  This is used by
    continuous simulation mode to carry neuron state across loop iterations.

    Args:
        neuron: The conductance-based neuron model to simulate.
        current_external: External current in µA/cm² for a time-varying current
            waveform.
        initial_V: Initial membrane voltage in mV.
        initial_gating_state: Gating variable values at the start of the run,
            keyed by variable name (e.g. ``{"m": 0.05, "h": 0.6, "n": 0.3}``).
        initial_ca_i: Initial intracellular Ca²⁺ concentration in mM.

    Returns:
        Structured array with the same fields as :func:`simulate_current_clamp`.
    """
    if len(current_external) == 0:
        raise ValueError("current_external must not be empty.")
    if not np.all(np.isfinite(current_external)):
        raise ValueError("current_external must not contain NaN or Inf values.")

    num_time_steps = len(current_external)
    duration_ms = (num_time_steps - 1) / SIM_SAMPLING_FREQ * 1000.0
    logger.debug(
        "simulate_current_clamp_from_state: start — %d steps, %.2f ms, %d channels",
        num_time_steps,
        duration_ms,
        len(neuron.channels),
    )
    result = _simulate_current_clamp_core(
        neuron, current_external, initial_V, dict(initial_gating_state), initial_ca_i
    )
    logger.debug(
        "simulate_current_clamp_from_state: complete — %d steps", num_time_steps
    )
    return result

neuroclamp.simulate_voltage_clamp_from_state

simulate_voltage_clamp_from_state(neuron, voltage_protocol, initial_gating_state, initial_ca_i=0.0)

Simulate a voltage clamp experiment starting from an explicit gating state.

Identical to :func:simulate_voltage_clamp except the initial gating variables and Ca²⁺ concentration are provided by the caller rather than initialized to steady-state at the first protocol voltage. This is used by continuous simulation mode to carry neuron state across loop iterations.

Parameters:

Name Type Description Default
neuron Neuron

The conductance-based neuron model to simulate.

required
voltage_protocol ndarray

Voltage values in mV to clamp the membrane at for each time step.

required
initial_gating_state dict[str, float]

Gating variable values at the start of the run, keyed by variable name (e.g. {"m": 0.05, "h": 0.6, "n": 0.3}).

required
initial_ca_i float

Initial intracellular Ca²⁺ concentration in mM.

0.0

Returns:

Type Description
SimulationResult

Structured array with the same fields as :func:simulate_voltage_clamp.

Source code in neuroclamp/clamp_simulations.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
def simulate_voltage_clamp_from_state(
    neuron: "Neuron",
    voltage_protocol: np.ndarray,
    initial_gating_state: dict[str, float],
    initial_ca_i: float = 0.0,
) -> SimulationResult:
    """Simulate a voltage clamp experiment starting from an explicit gating state.

    Identical to :func:`simulate_voltage_clamp` except the initial gating
    variables and Ca²⁺ concentration are provided by the caller rather than
    initialized to steady-state at the first protocol voltage.  This is used
    by continuous simulation mode to carry neuron state across loop iterations.

    Args:
        neuron: The conductance-based neuron model to simulate.
        voltage_protocol: Voltage values in mV to clamp the membrane at for
            each time step.
        initial_gating_state: Gating variable values at the start of the run,
            keyed by variable name (e.g. ``{"m": 0.05, "h": 0.6, "n": 0.3}``).
        initial_ca_i: Initial intracellular Ca²⁺ concentration in mM.

    Returns:
        Structured array with the same fields as :func:`simulate_voltage_clamp`.
    """
    if len(voltage_protocol) == 0:
        raise ValueError("voltage_protocol must not be empty.")
    if not np.all(np.isfinite(voltage_protocol)):
        raise ValueError("voltage_protocol must not contain NaN or Inf values.")

    num_time_steps = len(voltage_protocol)
    duration_ms = (num_time_steps - 1) / SIM_SAMPLING_FREQ * 1000.0
    logger.debug(
        "simulate_voltage_clamp_from_state: start — %d steps, %.2f ms, %d channels",
        num_time_steps,
        duration_ms,
        len(neuron.channels),
    )
    result = _simulate_voltage_clamp_core(
        neuron, voltage_protocol, dict(initial_gating_state), initial_ca_i
    )
    logger.debug(
        "simulate_voltage_clamp_from_state: complete — %d steps", num_time_steps
    )
    return result

neuroclamp.simulate_batch

simulate_batch(neuron, protocols, simulate_fn=simulate_voltage_clamp, max_workers=None)

Run multiple simulation protocols in parallel and yield results in order.

Each protocol is submitted to a process pool and executed independently (fresh initial conditions per protocol). Results are yielded in submission order so callers can process them progressively as simulations complete.

An empty protocols sequence yields nothing. A single-element sequence is equivalent to calling simulate_fn directly, but still routed through the pool.

Parameters:

Name Type Description Default
neuron Neuron

The conductance-based neuron model to simulate.

required
protocols Sequence[ndarray]

Sequence of protocol arrays, each passed individually to simulate_fn.

required
simulate_fn Callable[[Neuron, ndarray], SimulationResult]

The simulation function to apply to each protocol. Defaults to :func:simulate_voltage_clamp; pass :func:simulate_current_clamp for current-clamp batch runs.

simulate_voltage_clamp
max_workers int | None

Maximum number of worker processes. None (default) uses the CPU count.

None

Yields:

Type Description
SimulationResult

Structured arrays in the same order as protocols, one per protocol.

Source code in neuroclamp/clamp_simulations.py
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def simulate_batch(
    neuron: "Neuron",
    protocols: Sequence[np.ndarray],
    simulate_fn: Callable[
        ["Neuron", np.ndarray], SimulationResult
    ] = simulate_voltage_clamp,
    max_workers: int | None = None,
) -> Iterator[SimulationResult]:
    """Run multiple simulation protocols in parallel and yield results in order.

    Each protocol is submitted to a process pool and executed independently
    (fresh initial conditions per protocol).  Results are yielded in submission
    order so callers can process them progressively as simulations complete.

    An empty *protocols* sequence yields nothing.  A single-element sequence
    is equivalent to calling *simulate_fn* directly, but still routed through
    the pool.

    Args:
        neuron: The conductance-based neuron model to simulate.
        protocols: Sequence of protocol arrays, each passed individually to
            *simulate_fn*.
        simulate_fn: The simulation function to apply to each protocol.
            Defaults to :func:`simulate_voltage_clamp`; pass
            :func:`simulate_current_clamp` for current-clamp batch runs.
        max_workers: Maximum number of worker processes.  ``None`` (default)
            uses the CPU count.

    Yields:
        Structured arrays in the same order as *protocols*, one per protocol.
    """
    if not protocols:
        return

    with ProcessPoolExecutor(max_workers=max_workers) as executor:
        futures = [
            executor.submit(simulate_fn, neuron, protocol) for protocol in protocols
        ]
        for future in futures:
            yield future.result()

Result

neuroclamp.SimulationResult

Bases: ndarray[Any, Any]

A NumPy structured array with named dtype fields.

Each element represents one time step. Fields include "time", "voltage", "Itotal", per-channel currents (e.g. "INa", "IK"), gating variables, and optionally "ca_i".

Source code in neuroclamp/clamp_simulations.py
29
30
31
32
33
34
35
36
37
class SimulationResult(np.ndarray[Any, Any]):
    """A NumPy structured array with named dtype fields.

    Each element represents one time step. Fields include ``"time"``,
    ``"voltage"``, ``"Itotal"``, per-channel currents (e.g. ``"INa"``,
    ``"IK"``), gating variables, and optionally ``"ca_i"``.
    """

    dtype: _StructuredDtype  # type: ignore[assignment]

Electrochemistry and equilibrium

neuroclamp.nernst_potential

nernst_potential(z, T, ion_concentration_out, ion_concentration_in)

Calculate the Nernst potential for a given ion.

Parameters:

Name Type Description Default
z int

Valence of the ion (e.g., +1 for K+, +2 for Ca2+).

required
T float

Temperature in Kelvin.

required
ion_concentration_out float

Extracellular ion concentration (mM).

required
ion_concentration_in float

Intracellular ion concentration (mM).

required

Returns:

Type Description
float

Nernst potential in millivolts (mV).

Source code in neuroclamp/electrochemistry.py
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
def nernst_potential(
    z: int, T: float, ion_concentration_out: float, ion_concentration_in: float
) -> float:
    """Calculate the Nernst potential for a given ion.

    Args:
        z: Valence of the ion (e.g., +1 for K+, +2 for Ca2+).
        T: Temperature in Kelvin.
        ion_concentration_out: Extracellular ion concentration (mM).
        ion_concentration_in: Intracellular ion concentration (mM).

    Returns:
        Nernst potential in millivolts (mV).
    """
    if z == 0:
        raise ValueError("Valence (z) must not be zero.")
    if T <= 0:
        raise ValueError("Temperature (T) must be positive (in Kelvin).")
    if ion_concentration_out <= 0:
        raise ValueError("Extracellular ion concentration must be positive.")
    if ion_concentration_in <= 0:
        raise ValueError("Intracellular ion concentration must be positive.")

    # Convert to millivolts
    return (
        (R * T / (z * F)) * 1000 * np.log(ion_concentration_out / ion_concentration_in)
    )

neuroclamp.goldman_potential

goldman_potential(T, cation_terms, anion_terms=())

Calculate the Goldman-Hodgkin-Katz (GHK) reversal potential.

Implements the GHK voltage equation for a mixture of monovalent ions:

E = (RT/F) * ln(
        (sum_i P_i^cat * C_i_out + sum_j P_j^an * C_j_in)
      / (sum_i P_i^cat * C_i_in  + sum_j P_j^an * C_j_out)
    )

where cations contribute their extracellular concentration to the numerator and intracellular to the denominator; anions are reversed.

All ion species passed must be monovalent (|z| = 1). For divalent ions such as Ca²⁺ use :func:nernst_potential directly.

Parameters:

Name Type Description Default
T float

Temperature in Kelvin.

required
cation_terms Sequence[tuple[float, float, float]]

Sequence of (P, C_out, C_in) tuples for each monovalent cation, where P is the relative permeability (dimensionless), C_out the extracellular concentration (mM), and C_in the intracellular concentration (mM).

required
anion_terms Sequence[tuple[float, float, float]]

Sequence of (P, C_out, C_in) tuples for each monovalent anion. Defaults to an empty sequence (cations only).

()

Returns:

Type Description
float

GHK reversal potential in millivolts (mV).

Raises:

Type Description
ValueError

If T is not positive, if both cation_terms and anion_terms are empty, if any permeability is negative, or if any concentration is non-positive.

Source code in neuroclamp/electrochemistry.py
 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
def goldman_potential(
    T: float,
    cation_terms: Sequence[tuple[float, float, float]],
    anion_terms: Sequence[tuple[float, float, float]] = (),
) -> float:
    """Calculate the Goldman-Hodgkin-Katz (GHK) reversal potential.

    Implements the GHK voltage equation for a mixture of monovalent ions:

        E = (RT/F) * ln(
                (sum_i P_i^cat * C_i_out + sum_j P_j^an * C_j_in)
              / (sum_i P_i^cat * C_i_in  + sum_j P_j^an * C_j_out)
            )

    where cations contribute their extracellular concentration to the
    numerator and intracellular to the denominator; anions are reversed.

    All ion species passed must be monovalent (|z| = 1).  For divalent ions
    such as Ca²⁺ use :func:`nernst_potential` directly.

    Args:
        T: Temperature in Kelvin.
        cation_terms: Sequence of ``(P, C_out, C_in)`` tuples for each
            monovalent cation, where *P* is the relative permeability
            (dimensionless), *C_out* the extracellular concentration (mM),
            and *C_in* the intracellular concentration (mM).
        anion_terms: Sequence of ``(P, C_out, C_in)`` tuples for each
            monovalent anion.  Defaults to an empty sequence (cations only).

    Returns:
        GHK reversal potential in millivolts (mV).

    Raises:
        ValueError: If *T* is not positive, if both *cation_terms* and
            *anion_terms* are empty, if any permeability is negative, or if
            any concentration is non-positive.
    """
    if T <= 0:
        raise ValueError("Temperature (T) must be positive (in Kelvin).")
    if not cation_terms and not anion_terms:
        raise ValueError("At least one ion term (cation or anion) must be provided.")

    all_terms = list(cation_terms) + list(anion_terms)
    for P, c_out, c_in in all_terms:
        if P < 0:
            raise ValueError(f"Permeability must be non-negative, got {P}.")
        if c_out <= 0:
            raise ValueError(
                f"Extracellular concentration must be positive, got {c_out}."
            )
        if c_in <= 0:
            raise ValueError(
                f"Intracellular concentration must be positive, got {c_in}."
            )

    # Numerator: cation C_out + anion C_in
    numerator = sum(P * c_out for P, c_out, _ in cation_terms) + sum(
        P * c_in for P, _, c_in in anion_terms
    )
    # Denominator: cation C_in + anion C_out
    denominator = sum(P * c_in for P, _, c_in in cation_terms) + sum(
        P * c_out for P, c_out, _ in anion_terms
    )

    if numerator <= 0 or denominator <= 0:
        raise ValueError(
            "GHK numerator and denominator must both be positive. "
            "Check that at least one permeability is non-zero."
        )

    return (R * T / F) * 1000 * np.log(numerator / denominator)

neuroclamp.find_zero_current_voltage

find_zero_current_voltage(neuron, v_min=-100.0, v_max=-20.0, tol=1e-06, ca_i=None)

Find the membrane voltage where total ionic current is zero.

Uses Brent's method to locate the voltage at which the sum of all ionic currents (with gating variables held at their steady-state values) is zero. This is the true zero-current resting potential — the voltage the neuron will settle to when no external current is injected.

Calcium dynamics are accounted for by using ca_i as the intracellular Ca²⁺ concentration when evaluating calcium-dependent gating variables. When ca_i is None (the default) the neuron's declared ca_rest is used, consistent with how :func:~neuroclamp.simulate_current_clamp historically initialized the state. Pass an explicit value (e.g. from :func:find_coupled_equilibrium) when you need to evaluate the zero-current voltage at a specific Ca²⁺ concentration.

Parameters:

Name Type Description Default
neuron 'Neuron'

The conductance-based neuron model.

required
v_min float

Lower bound of the voltage search range in mV. Must bracket the root together with v_max.

-100.0
v_max float

Upper bound of the voltage search range in mV.

-20.0
tol float

Convergence tolerance in mV.

1e-06
ca_i float | None

Intracellular Ca²⁺ concentration in mM to use when evaluating calcium-dependent gating variables. None defaults to neuron.calcium_dynamics.ca_rest (or 0.0 if no calcium dynamics are configured).

None

Returns:

Type Description
float

Voltage in mV at which total ionic current is zero.

Raises:

Type Description
ValueError

If v_min and v_max do not bracket a sign change in the ionic-current function, or if v_min >= v_max.

Source code in neuroclamp/equilibrium.py
 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
def find_zero_current_voltage(
    neuron: "Neuron",
    v_min: float = -100.0,
    v_max: float = -20.0,
    tol: float = 1e-6,
    ca_i: float | None = None,
) -> float:
    """Find the membrane voltage where total ionic current is zero.

    Uses Brent's method to locate the voltage at which the sum of all ionic
    currents (with gating variables held at their steady-state values) is
    zero.  This is the true zero-current resting potential — the voltage
    the neuron will settle to when no external current is injected.

    Calcium dynamics are accounted for by using *ca_i* as the intracellular
    Ca²⁺ concentration when evaluating calcium-dependent gating variables.
    When *ca_i* is ``None`` (the default) the neuron's declared ``ca_rest``
    is used, consistent with how
    :func:`~neuroclamp.simulate_current_clamp` historically initialized the
    state.  Pass an explicit value (e.g. from
    :func:`find_coupled_equilibrium`) when you need to evaluate the
    zero-current voltage at a specific Ca²⁺ concentration.

    Args:
        neuron: The conductance-based neuron model.
        v_min: Lower bound of the voltage search range in mV.  Must bracket
            the root together with *v_max*.
        v_max: Upper bound of the voltage search range in mV.
        tol: Convergence tolerance in mV.
        ca_i: Intracellular Ca²⁺ concentration in mM to use when evaluating
            calcium-dependent gating variables.  ``None`` defaults to
            ``neuron.calcium_dynamics.ca_rest`` (or 0.0 if no calcium
            dynamics are configured).

    Returns:
        Voltage in mV at which total ionic current is zero.

    Raises:
        ValueError: If *v_min* and *v_max* do not bracket a sign change in
            the ionic-current function, or if *v_min* >= *v_max*.
    """
    if v_min >= v_max:
        raise ValueError(f"v_min ({v_min}) must be less than v_max ({v_max}).")

    _ca_i: float = (
        ca_i
        if ca_i is not None
        else (
            neuron.calcium_dynamics.ca_rest
            if neuron.calcium_dynamics is not None
            else 0.0
        )
    )

    f_min = _total_ionic_current(neuron, v_min, _ca_i)
    f_max = _total_ionic_current(neuron, v_max, _ca_i)

    if f_min * f_max > 0:
        raise ValueError(
            f"v_min={v_min} mV (I={f_min:.4f}) and v_max={v_max} mV "
            f"(I={f_max:.4f}) do not bracket a root.  Adjust the search "
            "range or verify that the neuron has a stable resting point."
        )

    return brentq(
        lambda V: _total_ionic_current(neuron, V, _ca_i),
        v_min,
        v_max,
        xtol=tol,
    )

neuroclamp.find_coupled_equilibrium

find_coupled_equilibrium(neuron, v_min=-100.0, v_max=-20.0, tol=1e-06, max_iter=50)

Find the coupled (V_ss, ca_i_ss) equilibrium for a neuron.

For neurons without calcium dynamics, equivalent to :func:find_zero_current_voltage with ca_i = 0 — returns (V_ss, 0.0).

For neurons with calcium dynamics, uses fixed-point iteration to simultaneously satisfy:

  • Voltage equilibrium: total ionic current is zero at V_ss (with gating variables at their steady-state values for that voltage and Ca²⁺ concentration).
  • Calcium equilibrium: the calcium ODE is at rest — ca_i_ss = ca_rest − α_ca · I_Ca(V_ss, ca_i_ss) · τ_ca.

Because the Ca²⁺ reversal potential depends on ca_i (dynamic E_Ca), the two equilibrium conditions are coupled: the resting ca_i shifts E_Ca, which shifts the zero-current voltage, which changes the Ca²⁺ window current, which shifts ca_i again. Iteration typically converges in fewer than ten steps for physiological parameters.

The returned (V_ss, ca_i_ss) pair is the correct starting point for :func:~neuroclamp.simulate_current_clamp so that the simulation does not drift when no external current is applied.

Parameters:

Name Type Description Default
neuron 'Neuron'

The conductance-based neuron model.

required
v_min float

Lower bound for the voltage root search in mV.

-100.0
v_max float

Upper bound for the voltage root search in mV.

-20.0
tol float

Convergence tolerance: iteration stops when both |V_new − V_old| < tol and |ca_i_new − ca_i_old| < 1e-10.

1e-06
max_iter int

Maximum number of fixed-point iterations before giving up. If reached without satisfying tol, a :class:RuntimeWarning is emitted and the last iterate is returned — calibrating preset constants against a non-converged value will produce silent drift, so callers should treat the warning as a failure.

50

Returns:

Type Description
float

(V_ss, ca_i_ss) — equilibrium membrane voltage in mV and

float

equilibrium intracellular Ca²⁺ concentration in mM.

Raises:

Type Description
ValueError

Propagated from :func:find_zero_current_voltage if the search range does not bracket a root.

Warns:

Type Description
RuntimeWarning

If max_iter iterations elapse without convergence.

Source code in neuroclamp/equilibrium.py
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
def find_coupled_equilibrium(
    neuron: "Neuron",
    v_min: float = -100.0,
    v_max: float = -20.0,
    tol: float = 1e-6,
    max_iter: int = 50,
) -> tuple[float, float]:
    """Find the coupled (V_ss, ca_i_ss) equilibrium for a neuron.

    For neurons without calcium dynamics, equivalent to
    :func:`find_zero_current_voltage` with ``ca_i = 0`` — returns
    ``(V_ss, 0.0)``.

    For neurons *with* calcium dynamics, uses fixed-point iteration to
    simultaneously satisfy:

    * **Voltage equilibrium**: total ionic current is zero at *V_ss* (with
      gating variables at their steady-state values for that voltage and
      Ca²⁺ concentration).
    * **Calcium equilibrium**: the calcium ODE is at rest —
      ``ca_i_ss = ca_rest − α_ca · I_Ca(V_ss, ca_i_ss) · τ_ca``.

    Because the Ca²⁺ reversal potential depends on ``ca_i`` (dynamic E_Ca),
    the two equilibrium conditions are coupled: the resting ``ca_i`` shifts
    E_Ca, which shifts the zero-current voltage, which changes the Ca²⁺
    window current, which shifts ``ca_i`` again.  Iteration typically
    converges in fewer than ten steps for physiological parameters.

    The returned ``(V_ss, ca_i_ss)`` pair is the correct starting point for
    :func:`~neuroclamp.simulate_current_clamp` so that the simulation does
    not drift when no external current is applied.

    Args:
        neuron: The conductance-based neuron model.
        v_min: Lower bound for the voltage root search in mV.
        v_max: Upper bound for the voltage root search in mV.
        tol: Convergence tolerance: iteration stops when both
            ``|V_new − V_old| < tol`` and ``|ca_i_new − ca_i_old| < 1e-10``.
        max_iter: Maximum number of fixed-point iterations before giving up.
            If reached without satisfying *tol*, a :class:`RuntimeWarning` is
            emitted and the last iterate is returned — calibrating preset
            constants against a non-converged value will produce silent drift,
            so callers should treat the warning as a failure.

    Returns:
        ``(V_ss, ca_i_ss)`` — equilibrium membrane voltage in mV and
        equilibrium intracellular Ca²⁺ concentration in mM.

    Raises:
        ValueError: Propagated from :func:`find_zero_current_voltage` if the
            search range does not bracket a root.

    Warns:
        RuntimeWarning: If *max_iter* iterations elapse without convergence.
    """
    if neuron.calcium_dynamics is None:
        return find_zero_current_voltage(neuron, v_min, v_max, tol), 0.0

    cd = neuron.calcium_dynamics
    ca_i: float = cd.ca_rest
    V_ss: float = find_zero_current_voltage(neuron, v_min, v_max, tol, ca_i=ca_i)
    dV: float = float("inf")
    dca: float = float("inf")

    for _ in range(max_iter):
        gating_state: dict[str, float] = {}
        for gv in neuron.all_gating_variables:
            a = gv.alpha(V_ss, ca_i)
            b = gv.beta(V_ss, ca_i)
            gating_state[gv.name] = a / (a + b)

        i_ca: float = sum(
            ch.compute_current(V_ss, gating_state, neuron, ca_i=ca_i)
            for ch in neuron.channels
            if ch.carries_calcium
        )
        ca_i_new = max(cd.ca_rest - cd.alpha_ca * i_ca * cd.tau_ca, _CA_NERNST_FLOOR)
        V_ss_new = find_zero_current_voltage(neuron, v_min, v_max, tol, ca_i=ca_i_new)

        dV = abs(V_ss_new - V_ss)
        dca = abs(ca_i_new - ca_i)
        if dV < tol and dca < 1e-10:
            return V_ss_new, ca_i_new

        V_ss, ca_i = V_ss_new, ca_i_new

    warnings.warn(
        f"find_coupled_equilibrium did not converge after {max_iter} iterations "
        f"(last step: ΔV={dV:.2e} mV, Δca_i={dca:.2e} mM); returning the last "
        "iterate.  Increase max_iter or investigate whether the neuron has a "
        "stable resting point.",
        RuntimeWarning,
        stacklevel=2,
    )
    return V_ss, ca_i