Skip to content

Analysis

Post-hoc metric extraction from a SimulationResult. The members below are documented from the neuroclamp.analysis subpackage.

neuroclamp.analysis

Analysis subpackage for neuroclamp.

Provides tools for extracting quantitative metrics from simulation results.

Modules:

Name Description
ap_metrics

Action potential detection and metric extraction.

burst_metrics

Burst detection and burst-metric extraction.

calcium_transients

Calcium transient detection and decay-τ fitting.

derivatives

General-purpose derivative utilities (e.g. dV/dt).

fi_curve

F-I curve construction from current clamp multi-sweep results.

hyperpolarization

Sag and rebound analysis from hyperpolarization sweeps.

impedance

Impedance-profile analysis from a chirp current-clamp run.

inactivation

Steady-state inactivation (h∞) curve from a two-pulse VC run.

iv_curve

I-V curve construction from voltage clamp multi-sweep results.

membrane_test

Dedicated membrane test for passive property characterisation.

passive_properties

Passive membrane property extraction (R_in, τₘ, Cₘ).

sfa

Spike-frequency adaptation curves and adaptation index.

tau_v

Activation/inactivation time-constant fits from voltage-clamp sweeps.

APAnalysisResult dataclass

Complete action potential analysis of a voltage trace.

Attributes:

Name Type Description
spike_count int

Number of detected spikes.

spikes list[SpikeMetrics]

Per-spike metrics for each detected spike.

isis list[float]

Inter-spike intervals in ms (length = spike_count - 1).

mean_threshold_voltage float | None

Mean threshold voltage across all spikes (mV), or None when no spikes were detected.

mean_peak_voltage float | None

Mean peak voltage across all spikes (mV), or None when no spikes were detected.

mean_rise_time float | None

Mean rise time across all spikes (ms), or None when no spikes were detected.

mean_half_width float | None

Mean half-width across all spikes (ms), or None when no spikes were detected.

mean_ahp_depth float | None

Mean AHP depth across spikes that have a measurable trough (mV), or None when no such spikes exist.

mean_isi float | None

Mean inter-spike interval (ms), or None when fewer than two spikes were detected.

firing_rate float | None

Mean firing rate in Hz (1000 / mean_isi), or None when fewer than two spikes were detected.

Source code in neuroclamp/analysis/ap_metrics.py
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
@dataclasses.dataclass
class APAnalysisResult:
    """Complete action potential analysis of a voltage trace.

    Attributes:
        spike_count: Number of detected spikes.
        spikes: Per-spike metrics for each detected spike.
        isis: Inter-spike intervals in ms (length = spike_count - 1).
        mean_threshold_voltage: Mean threshold voltage across all spikes (mV),
            or ``None`` when no spikes were detected.
        mean_peak_voltage: Mean peak voltage across all spikes (mV), or
            ``None`` when no spikes were detected.
        mean_rise_time: Mean rise time across all spikes (ms), or ``None``
            when no spikes were detected.
        mean_half_width: Mean half-width across all spikes (ms), or ``None``
            when no spikes were detected.
        mean_ahp_depth: Mean AHP depth across spikes that have a measurable
            trough (mV), or ``None`` when no such spikes exist.
        mean_isi: Mean inter-spike interval (ms), or ``None`` when fewer
            than two spikes were detected.
        firing_rate: Mean firing rate in Hz (``1000 / mean_isi``), or
            ``None`` when fewer than two spikes were detected.
    """

    spike_count: int
    spikes: list[SpikeMetrics]
    isis: list[float]
    mean_threshold_voltage: float | None
    mean_peak_voltage: float | None
    mean_rise_time: float | None
    mean_half_width: float | None
    mean_ahp_depth: float | None
    mean_isi: float | None
    firing_rate: float | None

SpikeMetrics dataclass

Metrics for a single detected action potential.

Attributes:

Name Type Description
index int

Zero-based spike number within the trace.

threshold_voltage float

Membrane voltage at spike onset (mV), defined as the point where dV/dt first exceeds the detection threshold.

threshold_time float

Time of threshold crossing (ms).

peak_voltage float

Maximum membrane voltage during the spike (mV).

peak_time float

Time of peak voltage (ms).

rise_time float

Duration from threshold crossing to peak (ms).

half_width float

Spike duration measured at the half-amplitude level between threshold voltage and peak voltage (ms).

ahp_depth float | None

Minimum membrane voltage after the spike trough (mV). None when no trough region is available (e.g. last spike with no subsequent data).

Source code in neuroclamp/analysis/ap_metrics.py
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
@dataclasses.dataclass
class SpikeMetrics:
    """Metrics for a single detected action potential.

    Attributes:
        index: Zero-based spike number within the trace.
        threshold_voltage: Membrane voltage at spike onset (mV), defined as
            the point where dV/dt first exceeds the detection threshold.
        threshold_time: Time of threshold crossing (ms).
        peak_voltage: Maximum membrane voltage during the spike (mV).
        peak_time: Time of peak voltage (ms).
        rise_time: Duration from threshold crossing to peak (ms).
        half_width: Spike duration measured at the half-amplitude level
            between threshold voltage and peak voltage (ms).
        ahp_depth: Minimum membrane voltage after the spike trough (mV).
            ``None`` when no trough region is available (e.g. last spike
            with no subsequent data).
    """

    index: int
    threshold_voltage: float
    threshold_time: float
    peak_voltage: float
    peak_time: float
    rise_time: float
    half_width: float
    ahp_depth: float | None

BurstAnalysisResult dataclass

Complete burst analysis of a spike train.

Attributes:

Name Type Description
burst_count int

Number of detected bursts.

bursts list[BurstMetrics]

Per-burst metrics.

unburst_spike_count int

Number of spikes that were not assigned to any burst because they were isolated by long inter-spike intervals.

mean_spikes_per_burst float | None

Mean spike_count across detected bursts, or None when no bursts were detected.

mean_intra_burst_frequency float | None

Mean intra_burst_frequency across multi-spike bursts, or None when no multi-spike burst exists.

mean_inter_burst_interval float | None

Mean gap between the end of one burst and the start of the next (ms), or None when fewer than two bursts were detected.

duty_cycle float | None

Fraction of the recording window spent inside a burst (sum(burst.duration) / total_duration). None when no bursts were detected.

isi_threshold_ms float

The inter-spike interval threshold (ms) used to separate intra-burst ISIs from inter-burst gaps. Always set, even when no bursts were detected, so downstream consumers can display the threshold that was applied.

threshold_method str

How :attr:isi_threshold_ms was determined. One of "auto-histogram", "default-fixed", or "user". "default-fixed" carries the tight-cluster intra-burst cap (12 ms): the grouper finds bursts whenever a contiguous run of ISIs falls inside that cap. Clusters with more than :data:_TIGHT_CLUSTER_MAX_ISIS + 1 spikes are subject to the terminating-cluster carve-out (see :func:analyze_bursts) — retained as bursts only when they match the LTS rebound phenotype, otherwise folded into the unburst count to preserve tonic-train protection (issue #290).

Source code in neuroclamp/analysis/burst_metrics.py
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
@dataclasses.dataclass
class BurstAnalysisResult:
    """Complete burst analysis of a spike train.

    Attributes:
        burst_count: Number of detected bursts.
        bursts: Per-burst metrics.
        unburst_spike_count: Number of spikes that were not assigned to any
            burst because they were isolated by long inter-spike intervals.
        mean_spikes_per_burst: Mean ``spike_count`` across detected bursts,
            or ``None`` when no bursts were detected.
        mean_intra_burst_frequency: Mean ``intra_burst_frequency`` across
            multi-spike bursts, or ``None`` when no multi-spike burst exists.
        mean_inter_burst_interval: Mean gap between the end of one burst and
            the start of the next (ms), or ``None`` when fewer than two
            bursts were detected.
        duty_cycle: Fraction of the recording window spent inside a burst
            (``sum(burst.duration) / total_duration``).  ``None`` when no
            bursts were detected.
        isi_threshold_ms: The inter-spike interval threshold (ms) used to
            separate intra-burst ISIs from inter-burst gaps.  Always set,
            even when no bursts were detected, so downstream consumers can
            display the threshold that was applied.
        threshold_method: How :attr:`isi_threshold_ms` was determined.  One
            of ``"auto-histogram"``, ``"default-fixed"``, or ``"user"``.
            ``"default-fixed"`` carries the tight-cluster intra-burst cap
            (12 ms): the grouper finds bursts whenever a contiguous run of
            ISIs falls inside that cap.  Clusters with more than
            :data:`_TIGHT_CLUSTER_MAX_ISIS` + 1 spikes are subject to the
            terminating-cluster carve-out (see :func:`analyze_bursts`) —
            retained as bursts only when they match the LTS rebound
            phenotype, otherwise folded into the unburst count to preserve
            tonic-train protection (issue #290).
    """

    burst_count: int
    bursts: list[BurstMetrics]
    unburst_spike_count: int
    mean_spikes_per_burst: float | None
    mean_intra_burst_frequency: float | None
    mean_inter_burst_interval: float | None
    duty_cycle: float | None
    isi_threshold_ms: float
    threshold_method: str

BurstMetrics dataclass

Metrics for a single detected burst.

Attributes:

Name Type Description
index int

Zero-based burst number within the trace.

start_time float

Peak time of the first spike in the burst (ms).

end_time float

Peak time of the last spike in the burst (ms).

duration float

end_time - start_time (ms); 0 for single-spike bursts.

spike_count int

Number of spikes contained in the burst.

intra_burst_frequency float | None

Mean firing rate within the burst (Hz), computed as (spike_count - 1) * 1000 / duration. None for single-spike bursts (which have zero duration).

mean_intra_burst_isi float | None

Mean of the inter-spike intervals inside the burst (ms). None for single-spike bursts.

Source code in neuroclamp/analysis/burst_metrics.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@dataclasses.dataclass
class BurstMetrics:
    """Metrics for a single detected burst.

    Attributes:
        index: Zero-based burst number within the trace.
        start_time: Peak time of the first spike in the burst (ms).
        end_time: Peak time of the last spike in the burst (ms).
        duration: ``end_time - start_time`` (ms); 0 for single-spike bursts.
        spike_count: Number of spikes contained in the burst.
        intra_burst_frequency: Mean firing rate within the burst (Hz),
            computed as ``(spike_count - 1) * 1000 / duration``.  ``None``
            for single-spike bursts (which have zero duration).
        mean_intra_burst_isi: Mean of the inter-spike intervals inside the
            burst (ms).  ``None`` for single-spike bursts.
    """

    index: int
    start_time: float
    end_time: float
    duration: float
    spike_count: int
    intra_burst_frequency: float | None
    mean_intra_burst_isi: float | None

CalciumTransient dataclass

Metrics for a single detected calcium transient.

Attributes:

Name Type Description
index int

Zero-based transient number within the trace.

onset_time float

Time at which the rise from baseline begins (ms).

peak_time float

Time of peak [Ca²⁺]ᵢ (ms).

peak_concentration float

Peak [Ca²⁺]ᵢ (µM).

baseline_concentration float

Per-transient baseline [Ca²⁺]ᵢ (µM), measured in a small window before onset_time.

amplitude float

peak_concentration - baseline_concentration (µM).

time_to_peak float

Duration from onset to peak (ms).

decay_tau float | None

Decay time constant from the exponential fit (ms), or None when both the fit and the 1/e-fallback estimate fail.

decay_fit_converged bool

True when :func:scipy.optimize.curve_fit converged; False when a fallback estimate (or None) was used.

Source code in neuroclamp/analysis/calcium_transients.py
 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
@dataclasses.dataclass
class CalciumTransient:
    """Metrics for a single detected calcium transient.

    Attributes:
        index: Zero-based transient number within the trace.
        onset_time: Time at which the rise from baseline begins (ms).
        peak_time: Time of peak [Ca²⁺]ᵢ (ms).
        peak_concentration: Peak [Ca²⁺]ᵢ (µM).
        baseline_concentration: Per-transient baseline [Ca²⁺]ᵢ (µM), measured
            in a small window before ``onset_time``.
        amplitude: ``peak_concentration - baseline_concentration`` (µM).
        time_to_peak: Duration from onset to peak (ms).
        decay_tau: Decay time constant from the exponential fit (ms), or
            ``None`` when both the fit and the 1/e-fallback estimate fail.
        decay_fit_converged: ``True`` when :func:`scipy.optimize.curve_fit`
            converged; ``False`` when a fallback estimate (or ``None``) was
            used.
    """

    index: int
    onset_time: float
    peak_time: float
    peak_concentration: float
    baseline_concentration: float
    amplitude: float
    time_to_peak: float
    decay_tau: float | None
    decay_fit_converged: bool

CalciumTransientAnalysisResult dataclass

Complete calcium-transient analysis of a [Ca²⁺]ᵢ trace.

Attributes:

Name Type Description
transient_count int

Number of detected transients.

transients list[CalciumTransient]

Per-transient metrics.

baseline_concentration float | None

Global pre-stimulus mean [Ca²⁺]ᵢ (µM), or None when the trace is empty.

mean_peak_concentration float | None

Mean peak [Ca²⁺]ᵢ across detected transients (µM), or None when no transients were detected.

mean_time_to_peak float | None

Mean time-to-peak across detected transients (ms), or None when no transients were detected.

mean_decay_tau float | None

Mean decay τ across transients with a usable τ (ms), or None when no transient yielded a usable τ.

mean_amplitude float | None

Mean peak - baseline across transients (µM), or None when no transients were detected.

Source code in neuroclamp/analysis/calcium_transients.py
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
@dataclasses.dataclass
class CalciumTransientAnalysisResult:
    """Complete calcium-transient analysis of a [Ca²⁺]ᵢ trace.

    Attributes:
        transient_count: Number of detected transients.
        transients: Per-transient metrics.
        baseline_concentration: Global pre-stimulus mean [Ca²⁺]ᵢ (µM), or
            ``None`` when the trace is empty.
        mean_peak_concentration: Mean peak [Ca²⁺]ᵢ across detected transients
            (µM), or ``None`` when no transients were detected.
        mean_time_to_peak: Mean time-to-peak across detected transients (ms),
            or ``None`` when no transients were detected.
        mean_decay_tau: Mean decay τ across transients with a usable τ (ms),
            or ``None`` when no transient yielded a usable τ.
        mean_amplitude: Mean ``peak - baseline`` across transients (µM), or
            ``None`` when no transients were detected.
    """

    transient_count: int
    transients: list[CalciumTransient]
    baseline_concentration: float | None
    mean_peak_concentration: float | None
    mean_time_to_peak: float | None
    mean_decay_tau: float | None
    mean_amplitude: float | None

FIAnalysisResult dataclass

Complete F-I analysis from a multi-sweep current clamp simulation.

Points are stored in ascending order of current step. The convenience properties current_steps, mean_firing_rates, initial_firing_rates, and steady_state_firing_rates extract the corresponding field from each point on demand.

Attributes:

Name Type Description
points list[FIPoint]

Per-step measurements, one entry per current step, sorted by ascending current amplitude.

Source code in neuroclamp/analysis/fi_curve.py
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
@dataclasses.dataclass
class FIAnalysisResult:
    """Complete F-I analysis from a multi-sweep current clamp simulation.

    Points are stored in ascending order of current step.  The convenience
    properties ``current_steps``, ``mean_firing_rates``,
    ``initial_firing_rates``, and ``steady_state_firing_rates`` extract the
    corresponding field from each point on demand.

    Attributes:
        points: Per-step measurements, one entry per current step, sorted by
            ascending current amplitude.
    """

    points: list[FIPoint]

    @property
    def current_steps(self) -> list[float]:
        """Injected current amplitudes in µA/cm², sorted ascending."""
        return [p.current_step for p in self.points]

    @property
    def mean_firing_rates(self) -> list[float | None]:
        """Mean firing rate at each step (Hz), or ``None`` for silent steps."""
        return [p.mean_firing_rate for p in self.points]

    @property
    def initial_firing_rates(self) -> list[float | None]:
        """Initial firing rate at each step (Hz), or ``None`` for silent steps."""
        return [p.initial_firing_rate for p in self.points]

    @property
    def steady_state_firing_rates(self) -> list[float | None]:
        """Steady-state firing rate at each step (Hz), or ``None`` for silent steps."""
        return [p.steady_state_firing_rate for p in self.points]

current_steps property

current_steps

Injected current amplitudes in µA/cm², sorted ascending.

mean_firing_rates property

mean_firing_rates

Mean firing rate at each step (Hz), or None for silent steps.

initial_firing_rates property

initial_firing_rates

Initial firing rate at each step (Hz), or None for silent steps.

steady_state_firing_rates property

steady_state_firing_rates

Steady-state firing rate at each step (Hz), or None for silent steps.

FIPoint dataclass

Firing rate measurements for a single current step in an F-I protocol.

Attributes:

Name Type Description
current_step float

Injected current amplitude during the step (µA/cm²).

spike_count int

Number of spikes detected within the stimulus window.

mean_firing_rate float | None

Mean firing rate in Hz (1000 / mean_ISI), or None when fewer than two spikes were detected.

initial_firing_rate float | None

Initial firing rate in Hz (1000 / first_ISI), or None when fewer than two spikes were detected.

steady_state_firing_rate float | None

Steady-state firing rate in Hz (1000 / last_ISI), or None when fewer than two spikes were detected.

Source code in neuroclamp/analysis/fi_curve.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclasses.dataclass
class FIPoint:
    """Firing rate measurements for a single current step in an F-I protocol.

    Attributes:
        current_step: Injected current amplitude during the step (µA/cm²).
        spike_count: Number of spikes detected within the stimulus window.
        mean_firing_rate: Mean firing rate in Hz (``1000 / mean_ISI``), or
            ``None`` when fewer than two spikes were detected.
        initial_firing_rate: Initial firing rate in Hz (``1000 / first_ISI``),
            or ``None`` when fewer than two spikes were detected.
        steady_state_firing_rate: Steady-state firing rate in Hz
            (``1000 / last_ISI``), or ``None`` when fewer than two spikes
            were detected.
    """

    current_step: float
    spike_count: int
    mean_firing_rate: float | None
    initial_firing_rate: float | None
    steady_state_firing_rate: float | None

BoltzmannFit dataclass

Fitted parameters for a two-parameter Boltzmann sigmoid.

The fit uses the function 1 / (1 + exp(-(V - v_half) / k)).

Attributes:

Name Type Description
v_half float

Half-activation voltage (mV).

k float

Slope factor (mV). Larger values mean shallower activation.

converged bool

True when scipy.optimize.curve_fit succeeded.

Source code in neuroclamp/analysis/gv_curve.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@dataclasses.dataclass
class BoltzmannFit:
    """Fitted parameters for a two-parameter Boltzmann sigmoid.

    The fit uses the function ``1 / (1 + exp(-(V - v_half) / k))``.

    Attributes:
        v_half: Half-activation voltage (mV).
        k: Slope factor (mV). Larger values mean shallower activation.
        converged: ``True`` when ``scipy.optimize.curve_fit`` succeeded.
    """

    v_half: float
    k: float
    converged: bool

GVAnalysisResult dataclass

Complete g-V analysis from a multi-sweep voltage clamp simulation.

Points are sorted in ascending order of voltage step. The convenience properties voltage_steps, conductances, and g_normalized_values extract the corresponding field from each point on demand.

Attributes:

Name Type Description
points list[GVPoint]

Per-step conductance records, sorted by ascending voltage.

boltzmann BoltzmannFit

Fitted Boltzmann parameters (may have converged=False).

reversal_potential float

Reversal potential used for conductance computation (mV).

Source code in neuroclamp/analysis/gv_curve.py
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
@dataclasses.dataclass
class GVAnalysisResult:
    """Complete g-V analysis from a multi-sweep voltage clamp simulation.

    Points are sorted in ascending order of voltage step.  The convenience
    properties ``voltage_steps``, ``conductances``, and ``g_normalized_values``
    extract the corresponding field from each point on demand.

    Attributes:
        points: Per-step conductance records, sorted by ascending voltage.
        boltzmann: Fitted Boltzmann parameters (may have ``converged=False``).
        reversal_potential: Reversal potential used for conductance computation
            (mV).
    """

    points: list[GVPoint]
    boltzmann: BoltzmannFit
    reversal_potential: float

    @property
    def voltage_steps(self) -> list[float]:
        """Command voltages in mV, sorted ascending."""
        return [p.voltage_step for p in self.points]

    @property
    def conductances(self) -> list[float]:
        """Chord conductances in mS/cm² at each voltage step."""
        return [p.conductance for p in self.points]

    @property
    def g_normalized_values(self) -> list[float]:
        """G/G_max values (dimensionless, 0–1) at each voltage step."""
        return [p.g_normalized for p in self.points]

voltage_steps property

voltage_steps

Command voltages in mV, sorted ascending.

conductances property

conductances

Chord conductances in mS/cm² at each voltage step.

g_normalized_values property

g_normalized_values

G/G_max values (dimensionless, 0–1) at each voltage step.

GVPoint dataclass

Conductance measurement for a single voltage step in a g-V protocol.

Attributes:

Name Type Description
voltage_step float

Command voltage applied during the step (mV).

conductance float

Chord conductance at this step (mS/cm²).

g_normalized float

Conductance normalized to G/G_max (dimensionless, 0–1).

Source code in neuroclamp/analysis/gv_curve.py
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclasses.dataclass
class GVPoint:
    """Conductance measurement for a single voltage step in a g-V protocol.

    Attributes:
        voltage_step: Command voltage applied during the step (mV).
        conductance: Chord conductance at this step (mS/cm²).
        g_normalized: Conductance normalized to G/G_max (dimensionless, 0–1).
    """

    voltage_step: float
    conductance: float
    g_normalized: float

HyperpolarizationAnalysisResult dataclass

Complete hyperpolarization analysis from a multi-sweep simulation.

Points are stored in ascending order of current step (most negative first). Convenience properties extract each field across all points.

Attributes:

Name Type Description
points list[SagPoint]

Per-step measurements, one entry per sweep, sorted by ascending (most negative) current amplitude.

Source code in neuroclamp/analysis/hyperpolarization.py
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
@dataclasses.dataclass
class HyperpolarizationAnalysisResult:
    """Complete hyperpolarization analysis from a multi-sweep simulation.

    Points are stored in ascending order of current step (most negative first).
    Convenience properties extract each field across all points.

    Attributes:
        points: Per-step measurements, one entry per sweep, sorted by
            ascending (most negative) current amplitude.
    """

    points: list[SagPoint]

    @property
    def current_steps(self) -> list[float]:
        """Injected current amplitudes (µA/cm²), most negative first."""
        return [p.current_step for p in self.points]

    @property
    def sag_amplitudes(self) -> list[float]:
        """Sag amplitude (mV) at each step, sorted with most negative step first."""
        return [p.sag_amplitude for p in self.points]

    @property
    def rebound_spike_counts(self) -> list[int]:
        """Rebound spike count at each step, sorted with most negative step first."""
        return [p.rebound_spike_count for p in self.points]

current_steps property

current_steps

Injected current amplitudes (µA/cm²), most negative first.

sag_amplitudes property

sag_amplitudes

Sag amplitude (mV) at each step, sorted with most negative step first.

rebound_spike_counts property

rebound_spike_counts

Rebound spike count at each step, sorted with most negative step first.

SagPoint dataclass

Sag and rebound measurements for a single hyperpolarizing current step.

Attributes:

Name Type Description
current_step float

Injected current amplitude during the step (µA/cm², negative).

peak_voltage float

Most negative membrane voltage reached during the step (mV).

steady_state_voltage float

Mean membrane voltage over the last 50 ms of the step (mV).

sag_amplitude float

Depolarizing drift during the step in mV (steady_state_voltage − peak_voltage; ≥ 0 when sag is present).

rebound_spike_count int

Number of action potentials detected in the rebound_window_ms immediately following step offset. This is mechanism-agnostic: spikes from ICaT de-inactivation, Ih overshoot, or HH anode-break excitation are all counted.

Source code in neuroclamp/analysis/hyperpolarization.py
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
@dataclasses.dataclass
class SagPoint:
    """Sag and rebound measurements for a single hyperpolarizing current step.

    Attributes:
        current_step: Injected current amplitude during the step (µA/cm²,
            negative).
        peak_voltage: Most negative membrane voltage reached during the step
            (mV).
        steady_state_voltage: Mean membrane voltage over the last 50 ms of the
            step (mV).
        sag_amplitude: Depolarizing drift during the step in mV
            (``steady_state_voltage − peak_voltage``; ≥ 0 when sag is
            present).
        rebound_spike_count: Number of action potentials detected in the
            ``rebound_window_ms`` immediately following step offset.  This is
            mechanism-agnostic: spikes from ICaT de-inactivation, Ih overshoot,
            or HH anode-break excitation are all counted.
    """

    current_step: float
    peak_voltage: float
    steady_state_voltage: float
    sag_amplitude: float
    rebound_spike_count: int

ImpedanceProfile dataclass

Membrane impedance profile from a chirp current-clamp run.

The per-area spectra (magnitude) and the band-maximum impedance (max_impedance) are always populated. When area_cm2 is supplied to :func:analyze_impedance, the absolute counterparts (magnitude_mohm, max_impedance_mohm, peak_impedance_mohm) are filled in too — analogous to the per-area / absolute split in :class:~neuroclamp.analysis.passive_properties.PassiveProperties.

resonance_frequency, peak_impedance and quality_factor are all None together unless |Z(f)| has a genuine resonance — an interior peak that both rises meaningfully above the low-frequency reference and has a half-power (−3 dB) width that can be bracketed inside the analysis band and is at least one FFT bin wide. A passive low-pass cell, or one whose mild interior bump has no bracketable bandwidth, reports None for all three; its max_impedance (the band-edge value, ≈ the input impedance) is still available.

Attributes:

Name Type Description
frequencies list[float]

Analysis-band frequency axis in Hz, ascending.

magnitude list[float]

|Z(f)| in kΩ·cm² (|V̂ / Î| where V̂ is in mV and Î is in µA/cm²), aligned to frequencies.

phase list[float]

∠Z(f) in degrees, aligned to frequencies; positive values mean the voltage leads the current.

max_impedance float

The maximum of |Z(f)| over the analysis band in kΩ·cm². For a cell with a genuine resonance this equals peak_impedance; for a passive low-pass cell it is the lowest-frequency (≈ DC) value, i.e. roughly the input impedance. Always populated.

resonance_frequency float | None

Frequency of the |Z| resonance peak in Hz, or None when there is no genuine resonance (the maximum lies at a band edge, does not clear the prominence margin, or has no bracketable −3 dB width).

peak_impedance float | None

|Z| at resonance_frequency in kΩ·cm², or None when there is no genuine resonance. When non-None it is identical to max_impedance (the resonance peak is the band maximum).

quality_factor float | None

Dimensionless Q = f_R / FWHM where FWHM is the full width of the |Z| peak at the half-power (−3 dB) level, or None when there is no genuine resonance.

magnitude_mohm list[float] | None

|Z(f)| converted to absolute MΩ when area_cm2 is supplied; None otherwise.

max_impedance_mohm float | None

max_impedance in MΩ when area_cm2 is supplied; None otherwise.

peak_impedance_mohm float | None

Absolute peak impedance in MΩ when area_cm2 is supplied and a genuine resonance exists; None otherwise.

area_cm2 float | None

Membrane surface area in cm² used for the absolute conversion. None when only per-area values were requested.

f_start float

Lower edge of the requested analysis band in Hz.

f_end float

Upper edge of the requested analysis band in Hz.

analyzed_window_ms float | None

None when the full chirp window was analyzed. Otherwise the duration in ms of the spike-free sub-window that was analyzed instead (the chirp contained spikes; impedance was recovered from the longest contiguous spike-free segment, which covers only a sub-band of [f_start, f_end] — see frequencies[0] / frequencies[-1] for the actually-covered band).

Source code in neuroclamp/analysis/impedance.py
 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
@dataclasses.dataclass
class ImpedanceProfile:
    """Membrane impedance profile from a chirp current-clamp run.

    The per-area spectra (``magnitude``) and the band-maximum impedance
    (``max_impedance``) are always populated.  When ``area_cm2`` is supplied to
    :func:`analyze_impedance`, the absolute counterparts (``magnitude_mohm``,
    ``max_impedance_mohm``, ``peak_impedance_mohm``) are filled in too —
    analogous to the per-area / absolute split in
    :class:`~neuroclamp.analysis.passive_properties.PassiveProperties`.

    ``resonance_frequency``, ``peak_impedance`` and ``quality_factor`` are all
    ``None`` together unless ``|Z(f)|`` has a genuine resonance — an interior
    peak that both rises meaningfully above the low-frequency reference *and*
    has a half-power (−3 dB) width that can be bracketed inside the analysis
    band and is at least one FFT bin wide.  A passive low-pass cell, or one
    whose mild interior bump has no bracketable bandwidth, reports ``None`` for
    all three; its ``max_impedance`` (the band-edge value, ≈ the input
    impedance) is still available.

    Attributes:
        frequencies: Analysis-band frequency axis in Hz, ascending.
        magnitude: ``|Z(f)|`` in kΩ·cm² (``|V̂ / Î|`` where V̂ is in mV and
            Î is in µA/cm²), aligned to ``frequencies``.
        phase: ``∠Z(f)`` in degrees, aligned to ``frequencies``; positive
            values mean the voltage leads the current.
        max_impedance: The maximum of ``|Z(f)|`` over the analysis band in
            kΩ·cm².  For a cell with a genuine resonance this equals
            ``peak_impedance``; for a passive low-pass cell it is the
            lowest-frequency (≈ DC) value, i.e. roughly the input impedance.
            Always populated.
        resonance_frequency: Frequency of the ``|Z|`` resonance peak in Hz, or
            ``None`` when there is no genuine resonance (the maximum lies at a
            band edge, does not clear the prominence margin, or has no
            bracketable −3 dB width).
        peak_impedance: ``|Z|`` at ``resonance_frequency`` in kΩ·cm², or
            ``None`` when there is no genuine resonance.  When non-``None`` it
            is identical to ``max_impedance`` (the resonance peak *is* the
            band maximum).
        quality_factor: Dimensionless ``Q = f_R / FWHM`` where FWHM is the
            full width of the ``|Z|`` peak at the half-power (−3 dB) level, or
            ``None`` when there is no genuine resonance.
        magnitude_mohm: ``|Z(f)|`` converted to absolute MΩ when ``area_cm2``
            is supplied; ``None`` otherwise.
        max_impedance_mohm: ``max_impedance`` in MΩ when ``area_cm2`` is
            supplied; ``None`` otherwise.
        peak_impedance_mohm: Absolute peak impedance in MΩ when ``area_cm2`` is
            supplied and a genuine resonance exists; ``None`` otherwise.
        area_cm2: Membrane surface area in cm² used for the absolute
            conversion.  ``None`` when only per-area values were requested.
        f_start: Lower edge of the requested analysis band in Hz.
        f_end: Upper edge of the requested analysis band in Hz.
        analyzed_window_ms: ``None`` when the full chirp window was analyzed.
            Otherwise the duration in ms of the spike-free sub-window that was
            analyzed instead (the chirp contained spikes; impedance was
            recovered from the longest contiguous spike-free segment, which
            covers only a sub-band of ``[f_start, f_end]`` — see
            ``frequencies[0]`` / ``frequencies[-1]`` for the actually-covered
            band).
    """

    frequencies: list[float]
    magnitude: list[float]
    phase: list[float]
    max_impedance: float
    resonance_frequency: float | None
    peak_impedance: float | None
    quality_factor: float | None
    magnitude_mohm: list[float] | None = None
    max_impedance_mohm: float | None = None
    peak_impedance_mohm: float | None = None
    area_cm2: float | None = None
    f_start: float = 0.0
    f_end: float = 0.0
    analyzed_window_ms: float | None = None

InactivationAnalysisResult dataclass

Complete steady-state inactivation analysis from a two-pulse simulation.

Points are sorted in ascending order of prepulse voltage. The convenience properties prepulse_voltages, peak_inward_currents, and h_normalized_values extract the corresponding field from each point on demand.

The fitted Boltzmann parameterizes a decreasing sigmoid h∞(V) = 1 / (1 + exp((V - v_half) / k)) with k > 0 — equivalently boltzmann(V, v_half, -k) using the shared :func:~neuroclamp.analysis.gv_curve.boltzmann function (which is the increasing activation form). Callers reconstructing the fit curve must therefore negate k.

Attributes:

Name Type Description
points list[InactivationPoint]

Per-prepulse availability records, sorted by ascending prepulse voltage.

boltzmann BoltzmannFit

Fitted Boltzmann parameters (may have converged=False). v_half is the half-inactivation voltage (mV) and k the slope factor (mV, positive); the curve they describe is decreasing.

Source code in neuroclamp/analysis/inactivation.py
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
@dataclasses.dataclass
class InactivationAnalysisResult:
    """Complete steady-state inactivation analysis from a two-pulse simulation.

    Points are sorted in ascending order of prepulse voltage.  The convenience
    properties ``prepulse_voltages``, ``peak_inward_currents``, and
    ``h_normalized_values`` extract the corresponding field from each point on
    demand.

    The fitted Boltzmann parameterizes a *decreasing* sigmoid
    ``h∞(V) = 1 / (1 + exp((V - v_half) / k))`` with ``k > 0`` — equivalently
    ``boltzmann(V, v_half, -k)`` using the shared
    :func:`~neuroclamp.analysis.gv_curve.boltzmann` function (which is the
    *increasing* activation form).  Callers reconstructing the fit curve must
    therefore negate ``k``.

    Attributes:
        points: Per-prepulse availability records, sorted by ascending prepulse
            voltage.
        boltzmann: Fitted Boltzmann parameters (may have ``converged=False``).
            ``v_half`` is the half-inactivation voltage (mV) and ``k`` the
            slope factor (mV, positive); the curve they describe is decreasing.
    """

    points: list[InactivationPoint]
    boltzmann: BoltzmannFit

    @property
    def prepulse_voltages(self) -> list[float]:
        """Conditioning prepulse voltages in mV, sorted ascending."""
        return [p.prepulse_voltage for p in self.points]

    @property
    def peak_inward_currents(self) -> list[float]:
        """Test-pulse peak inward currents in µA/cm² at each prepulse."""
        return [p.peak_inward_current for p in self.points]

    @property
    def h_normalized_values(self) -> list[float]:
        """h∞ availability values (dimensionless, 0–1) at each prepulse."""
        return [p.h_normalized for p in self.points]

prepulse_voltages property

prepulse_voltages

Conditioning prepulse voltages in mV, sorted ascending.

peak_inward_currents property

peak_inward_currents

Test-pulse peak inward currents in µA/cm² at each prepulse.

h_normalized_values property

h_normalized_values

h∞ availability values (dimensionless, 0–1) at each prepulse.

InactivationPoint dataclass

Availability measurement for a single conditioning prepulse voltage.

Attributes:

Name Type Description
prepulse_voltage float

Conditioning prepulse voltage held before the fixed test pulse (mV).

peak_inward_current float

Most negative (inward) current measured during the test pulse for this prepulse (µA/cm²).

h_normalized float

Availability normalized to h∞ = I_peak / I_peak_max, where I_peak_max is the most negative peak across all prepulses (dimensionless, clamped to 0–1).

Source code in neuroclamp/analysis/inactivation.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@dataclasses.dataclass
class InactivationPoint:
    """Availability measurement for a single conditioning prepulse voltage.

    Attributes:
        prepulse_voltage: Conditioning prepulse voltage held before the fixed
            test pulse (mV).
        peak_inward_current: Most negative (inward) current measured during the
            test pulse for this prepulse (µA/cm²).
        h_normalized: Availability normalized to h∞ = I_peak / I_peak_max, where
            I_peak_max is the most negative peak across all prepulses
            (dimensionless, clamped to 0–1).
    """

    prepulse_voltage: float
    peak_inward_current: float
    h_normalized: float

IVAnalysisResult dataclass

Complete I-V analysis from a multi-sweep voltage clamp simulation.

Points are stored in ascending order of voltage step. The convenience properties voltage_steps, peak_inward_currents, peak_outward_currents, and steady_state_currents extract the corresponding field from each point on demand.

Attributes:

Name Type Description
points list[IVPoint]

Per-step measurements, one entry per voltage step, sorted by ascending voltage.

Source code in neuroclamp/analysis/iv_curve.py
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
@dataclasses.dataclass
class IVAnalysisResult:
    """Complete I-V analysis from a multi-sweep voltage clamp simulation.

    Points are stored in ascending order of voltage step.  The convenience
    properties ``voltage_steps``, ``peak_inward_currents``,
    ``peak_outward_currents``, and ``steady_state_currents`` extract the
    corresponding field from each point on demand.

    Attributes:
        points: Per-step measurements, one entry per voltage step, sorted by
            ascending voltage.
    """

    points: list[IVPoint]

    @property
    def voltage_steps(self) -> list[float]:
        """Command voltages in mV, sorted ascending."""
        return [p.voltage_step for p in self.points]

    @property
    def peak_inward_currents(self) -> list[float]:
        """Most negative current at each step (µA/cm²)."""
        return [p.peak_inward_current for p in self.points]

    @property
    def peak_outward_currents(self) -> list[float]:
        """Most positive current at each step (µA/cm²)."""
        return [p.peak_outward_current for p in self.points]

    @property
    def steady_state_currents(self) -> list[float]:
        """Steady-state current at each step (µA/cm²)."""
        return [p.steady_state_current for p in self.points]

voltage_steps property

voltage_steps

Command voltages in mV, sorted ascending.

peak_inward_currents property

peak_inward_currents

Most negative current at each step (µA/cm²).

peak_outward_currents property

peak_outward_currents

Most positive current at each step (µA/cm²).

steady_state_currents property

steady_state_currents

Steady-state current at each step (µA/cm²).

IVPoint dataclass

Current measurements for a single voltage step in an I-V protocol.

Attributes:

Name Type Description
voltage_step float

Command voltage applied during the step (mV).

peak_inward_current float

Most negative (inward) current during the step (µA/cm²).

peak_outward_current float

Most positive (outward) current during the step (µA/cm²).

steady_state_current float

Mean current over the last 10% of the stimulus window (µA/cm²).

Source code in neuroclamp/analysis/iv_curve.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclasses.dataclass
class IVPoint:
    """Current measurements for a single voltage step in an I-V protocol.

    Attributes:
        voltage_step: Command voltage applied during the step (mV).
        peak_inward_current: Most negative (inward) current during the step
            (µA/cm²).
        peak_outward_current: Most positive (outward) current during the step
            (µA/cm²).
        steady_state_current: Mean current over the last 10% of the stimulus
            window (µA/cm²).
    """

    voltage_step: float
    peak_inward_current: float
    peak_outward_current: float
    steady_state_current: float

PassiveProperties dataclass

Passive membrane properties extracted from a subthreshold current clamp step.

The per-area density values (input_resistance, membrane_capacitance) are always populated. When area_cm2 is supplied to :func:analyze_passive_properties, the absolute counterparts (input_resistance_mohm, membrane_capacitance_pf) are filled in too. time_constant is the same numeric value in both modes — τₘ = R · C is invariant to the per-area / absolute conversion.

Attributes:

Name Type Description
input_resistance float

Input resistance in kΩ·cm² (R_in = ΔV / ΔI where ΔV is in mV and ΔI is in µA/cm²).

time_constant float

Membrane time constant in ms from exponential fit. Numerically identical regardless of whether area is supplied.

membrane_capacitance float | None

Derived C_m = τ_m / R_in in µF/cm², or None when R_in is zero.

fit_converged bool

True when the exponential fit converged successfully; False when a fallback 63.2%-crossing estimate was used instead.

input_resistance_mohm float | None

Absolute input resistance in MΩ when area_cm2 is supplied; None otherwise.

membrane_capacitance_pf float | None

Absolute membrane capacitance in pF when area_cm2 is supplied and the per-area capacitance is finite; None otherwise.

area_cm2 float | None

Membrane surface area in cm² used to compute the absolute values. None when only density values were requested.

Source code in neuroclamp/analysis/passive_properties.py
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
@dataclasses.dataclass
class PassiveProperties:
    """Passive membrane properties extracted from a subthreshold current clamp step.

    The per-area density values (``input_resistance``, ``membrane_capacitance``)
    are always populated.  When ``area_cm2`` is supplied to
    :func:`analyze_passive_properties`, the absolute counterparts
    (``input_resistance_mohm``, ``membrane_capacitance_pf``) are filled in too.
    ``time_constant`` is the same numeric value in both modes — τₘ = R · C is
    invariant to the per-area / absolute conversion.

    Attributes:
        input_resistance: Input resistance in kΩ·cm² (R_in = ΔV / ΔI where
            ΔV is in mV and ΔI is in µA/cm²).
        time_constant: Membrane time constant in ms from exponential fit.
            Numerically identical regardless of whether area is supplied.
        membrane_capacitance: Derived C_m = τ_m / R_in in µF/cm², or ``None``
            when R_in is zero.
        fit_converged: ``True`` when the exponential fit converged successfully;
            ``False`` when a fallback 63.2%-crossing estimate was used instead.
        input_resistance_mohm: Absolute input resistance in MΩ when
            ``area_cm2`` is supplied; ``None`` otherwise.
        membrane_capacitance_pf: Absolute membrane capacitance in pF when
            ``area_cm2`` is supplied and the per-area capacitance is finite;
            ``None`` otherwise.
        area_cm2: Membrane surface area in cm² used to compute the absolute
            values.  ``None`` when only density values were requested.
    """

    input_resistance: float
    time_constant: float
    membrane_capacitance: float | None
    fit_converged: bool
    input_resistance_mohm: float | None = None
    membrane_capacitance_pf: float | None = None
    area_cm2: float | None = None

SFAAnalysisResult dataclass

Spike-frequency adaptation analysis, possibly across multiple sweeps.

Attributes:

Name Type Description
curves list[SFACurve]

One :class:SFACurve per sweep that contained at least two spikes (one ISI). Sweeps with fewer spikes are excluded.

Source code in neuroclamp/analysis/sfa.py
40
41
42
43
44
45
46
47
48
49
@dataclasses.dataclass
class SFAAnalysisResult:
    """Spike-frequency adaptation analysis, possibly across multiple sweeps.

    Attributes:
        curves: One :class:`SFACurve` per sweep that contained at least two
            spikes (one ISI).  Sweeps with fewer spikes are excluded.
    """

    curves: list[SFACurve]

SFACurve dataclass

Instantaneous-frequency curve for a single current clamp sweep.

Attributes:

Name Type Description
spike_indices list[int]

Zero-based index for each ISI pair (0, 1, 2, …). Length equals len(instantaneous_frequencies).

instantaneous_frequencies list[float]

Instantaneous firing frequency in Hz (1000 / ISI_ms) for each consecutive spike pair.

adaptation_index float

(f_first - f_last) / f_first, dimensionless. Positive when firing slows (adaptation), negative when firing accelerates, and zero for uniform spike trains.

label str

Optional display label for multi-sweep overlay (e.g. "10.0 µA/cm²"). Empty string for single-sweep use.

Source code in neuroclamp/analysis/sfa.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@dataclasses.dataclass
class SFACurve:
    """Instantaneous-frequency curve for a single current clamp sweep.

    Attributes:
        spike_indices: Zero-based index for each ISI pair (0, 1, 2, …).
            Length equals ``len(instantaneous_frequencies)``.
        instantaneous_frequencies: Instantaneous firing frequency in Hz
            (``1000 / ISI_ms``) for each consecutive spike pair.
        adaptation_index: ``(f_first - f_last) / f_first``, dimensionless.
            Positive when firing slows (adaptation), negative when firing
            accelerates, and zero for uniform spike trains.
        label: Optional display label for multi-sweep overlay (e.g.
            ``"10.0 µA/cm²"``).  Empty string for single-sweep use.
    """

    spike_indices: list[int]
    instantaneous_frequencies: list[float]
    adaptation_index: float
    label: str

DoubleExponentialFit dataclass

Fitted parameters for the two-exponential decay model.

The model is A_fast * exp(-t/τ_fast) + A_slow * exp(-t/τ_slow) + C, with the convention τ_fast <= τ_slow enforced by :func:compute_tau_v_point after fitting.

Attributes:

Name Type Description
amplitude_fast float

Fast component pre-exponential.

tau_fast_ms float

Faster of the two time constants (ms).

amplitude_slow float

Slow component pre-exponential.

tau_slow_ms float

Slower of the two time constants (ms).

offset float

Baseline / asymptote C (µA/cm²).

converged bool

True when scipy.optimize.curve_fit succeeded.

rss float

Residual sum of squares of the fit.

Source code in neuroclamp/analysis/tau_v.py
 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
@dataclasses.dataclass
class DoubleExponentialFit:
    """Fitted parameters for the two-exponential decay model.

    The model is ``A_fast * exp(-t/τ_fast) + A_slow * exp(-t/τ_slow) + C``,
    with the convention ``τ_fast <= τ_slow`` enforced by
    :func:`compute_tau_v_point` after fitting.

    Attributes:
        amplitude_fast: Fast component pre-exponential.
        tau_fast_ms: Faster of the two time constants (ms).
        amplitude_slow: Slow component pre-exponential.
        tau_slow_ms: Slower of the two time constants (ms).
        offset: Baseline / asymptote ``C`` (µA/cm²).
        converged: ``True`` when ``scipy.optimize.curve_fit`` succeeded.
        rss: Residual sum of squares of the fit.
    """

    amplitude_fast: float
    tau_fast_ms: float
    amplitude_slow: float
    tau_slow_ms: float
    offset: float
    converged: bool
    rss: float

ExponentialFit dataclass

Fitted parameters for a single exponential model.

Attributes:

Name Type Description
amplitude float

Pre-exponential coefficient A. Sign convention follows the chosen model (positive for single_exp_rise, signed for single_exp_decay).

tau_ms float

Time constant τ in ms.

offset float

Baseline / asymptote C (µA/cm²).

converged bool

True when scipy.optimize.curve_fit succeeded.

rss float

Residual sum of squares of the fit; used to compare against the double-exponential fit. inf when the fit failed.

Source code in neuroclamp/analysis/tau_v.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@dataclasses.dataclass
class ExponentialFit:
    """Fitted parameters for a single exponential model.

    Attributes:
        amplitude: Pre-exponential coefficient ``A``.  Sign convention follows
            the chosen model (positive for ``single_exp_rise``, signed for
            ``single_exp_decay``).
        tau_ms: Time constant τ in ms.
        offset: Baseline / asymptote ``C`` (µA/cm²).
        converged: ``True`` when ``scipy.optimize.curve_fit`` succeeded.
        rss: Residual sum of squares of the fit; used to compare against
            the double-exponential fit.  ``inf`` when the fit failed.
    """

    amplitude: float
    tau_ms: float
    offset: float
    converged: bool
    rss: float

TauVAnalysisResult dataclass

Aggregate τ-V analysis from a multi-sweep voltage clamp simulation.

Points are sorted in ascending order of voltage step.

Attributes:

Name Type Description
points list[TauVPoint]

Per-step time constants, sorted by ascending voltage.

Source code in neuroclamp/analysis/tau_v.py
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
@dataclasses.dataclass
class TauVAnalysisResult:
    """Aggregate τ-V analysis from a multi-sweep voltage clamp simulation.

    Points are sorted in ascending order of voltage step.

    Attributes:
        points: Per-step time constants, sorted by ascending voltage.
    """

    points: list[TauVPoint]

    @property
    def voltage_steps(self) -> list[float]:
        """Command voltages in mV, sorted ascending."""
        return [p.voltage_step for p in self.points]

    @property
    def tau_activation_values(self) -> list[float | None]:
        """Activation τ (ms) at each voltage step (``None`` for skipped/failed fits)."""
        return [p.tau_activation_ms for p in self.points]

    @property
    def tau_inactivation_values(self) -> list[float | None]:
        """Inactivation τ (ms) at each voltage step (``None`` for skipped/failed fits).

        When a double-exponential fit was accepted at a step, this is the
        fast component; the slow component is in
        :attr:`tau_inactivation_slow_values`.
        """
        return [p.tau_inactivation_ms for p in self.points]

    @property
    def tau_inactivation_slow_values(self) -> list[float | None]:
        """Slow inactivation τ (ms) at each step where a double-exp fit was accepted."""
        return [p.tau_inactivation_slow_ms for p in self.points]

voltage_steps property

voltage_steps

Command voltages in mV, sorted ascending.

tau_activation_values property

tau_activation_values

Activation τ (ms) at each voltage step (None for skipped/failed fits).

tau_inactivation_values property

tau_inactivation_values

Inactivation τ (ms) at each voltage step (None for skipped/failed fits).

When a double-exponential fit was accepted at a step, this is the fast component; the slow component is in :attr:tau_inactivation_slow_values.

tau_inactivation_slow_values property

tau_inactivation_slow_values

Slow inactivation τ (ms) at each step where a double-exp fit was accepted.

TauVPoint dataclass

Time-constant measurements for a single voltage step.

All τ fields are None when the corresponding fit was skipped (window too short, no inactivation phase observed, etc.) or did not converge. The *_converged flags distinguish between "skipped" (τ is None and converged is False) and "fit succeeded" (τ is a float and converged is True).

Attributes:

Name Type Description
voltage_step float

Command voltage applied during the step (mV).

tau_activation_ms float | None

Time constant of the rising phase (ms), or None when no fit was produced.

tau_inactivation_ms float | None

Fast time constant of the decaying phase (ms), or None. When inactivation_is_double is True, this is the fast component of the double-exponential fit.

tau_inactivation_slow_ms float | None

Slow time constant of the decaying phase (ms). Populated only when inactivation_is_double is True.

activation_converged bool

True when the activation fit succeeded.

inactivation_converged bool

True when the inactivation fit succeeded.

inactivation_is_double bool

True when the double-exponential fit was preferred over the single-exponential fit.

Source code in neuroclamp/analysis/tau_v.py
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
@dataclasses.dataclass
class TauVPoint:
    """Time-constant measurements for a single voltage step.

    All τ fields are ``None`` when the corresponding fit was skipped (window
    too short, no inactivation phase observed, etc.) or did not converge.
    The ``*_converged`` flags distinguish between "skipped" (τ is ``None``
    and converged is ``False``) and "fit succeeded" (τ is a float and
    converged is ``True``).

    Attributes:
        voltage_step: Command voltage applied during the step (mV).
        tau_activation_ms: Time constant of the rising phase (ms), or
            ``None`` when no fit was produced.
        tau_inactivation_ms: Fast time constant of the decaying phase
            (ms), or ``None``.  When ``inactivation_is_double`` is ``True``,
            this is the fast component of the double-exponential fit.
        tau_inactivation_slow_ms: Slow time constant of the decaying phase
            (ms).  Populated only when ``inactivation_is_double`` is ``True``.
        activation_converged: ``True`` when the activation fit succeeded.
        inactivation_converged: ``True`` when the inactivation fit succeeded.
        inactivation_is_double: ``True`` when the double-exponential fit
            was preferred over the single-exponential fit.
    """

    voltage_step: float
    tau_activation_ms: float | None
    tau_inactivation_ms: float | None
    tau_inactivation_slow_ms: float | None
    activation_converged: bool
    inactivation_converged: bool
    inactivation_is_double: bool

analyze_aps

analyze_aps(time, voltage, dvdt_threshold=20.0, min_spike_height=-20.0)

Extract action potential metrics from a voltage trace.

Spikes are detected by finding upward crossings of dvdt_threshold in the dV/dt signal. For each candidate crossing the subsequent voltage peak is located. Candidates are rejected when the peak is below min_spike_height or when they fall within a refractory window after the previous accepted spike.

Parameters:

Name Type Description Default
time ndarray

Time array in ms, shape (N,).

required
voltage ndarray

Membrane voltage in mV, shape (N,), same length as time.

required
dvdt_threshold float

dV/dt value (mV/ms) used to identify spike onset. The default of 20 mV/ms is standard for HH-type models.

20.0
min_spike_height float

Minimum peak voltage (mV) for a candidate event to be classified as a spike. Subthreshold oscillations typically peak well below 0 mV.

-20.0

Returns:

Name Type Description
An APAnalysisResult

class:APAnalysisResult containing per-spike metrics and

APAnalysisResult

aggregate summary statistics.

Source code in neuroclamp/analysis/ap_metrics.py
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def analyze_aps(
    time: np.ndarray,
    voltage: np.ndarray,
    dvdt_threshold: float = 20.0,
    min_spike_height: float = -20.0,
) -> APAnalysisResult:
    """Extract action potential metrics from a voltage trace.

    Spikes are detected by finding upward crossings of ``dvdt_threshold`` in
    the dV/dt signal.  For each candidate crossing the subsequent voltage peak
    is located.  Candidates are rejected when the peak is below
    ``min_spike_height`` or when they fall within a refractory window after
    the previous accepted spike.

    Args:
        time: Time array in ms, shape ``(N,)``.
        voltage: Membrane voltage in mV, shape ``(N,)``, same length as
            ``time``.
        dvdt_threshold: dV/dt value (mV/ms) used to identify spike onset.
            The default of 20 mV/ms is standard for HH-type models.
        min_spike_height: Minimum peak voltage (mV) for a candidate event to
            be classified as a spike.  Subthreshold oscillations typically
            peak well below 0 mV.

    Returns:
        An :class:`APAnalysisResult` containing per-spike metrics and
        aggregate summary statistics.
    """
    time = np.asarray(time, dtype=float)
    voltage = np.asarray(voltage, dtype=float)

    n = len(time)
    if n < 2:
        return _empty_result()

    dt_arr = np.diff(time)
    dvdt = np.diff(voltage) / dt_arr  # length n-1

    # --- Step 1: upward threshold crossings in dV/dt ---
    above = dvdt >= dvdt_threshold
    # crossing at index i means dvdt[i] is the first sample >= threshold
    crossing_mask = np.zeros(len(dvdt), dtype=bool)
    crossing_mask[1:] = above[1:] & ~above[:-1]
    crossing_mask[0] = above[0]
    crossing_indices = np.where(crossing_mask)[0]

    spikes: list[SpikeMetrics] = []
    last_peak_idx = -_REFRACTORY_SAMPLES - 1

    for c_idx in crossing_indices.tolist():
        # Enforce refractory period
        if c_idx - last_peak_idx < _REFRACTORY_SAMPLES:
            continue

        # --- Step 2: find peak after crossing ---
        # Scan forward until dV/dt drops below zero (voltage starts falling)
        search_start = c_idx + 1
        drop_indices = np.where(dvdt[search_start:] < 0)[0]
        if len(drop_indices) == 0:
            # Voltage never falls — peak is the last sample
            peak_idx = n - 1
        else:
            peak_idx = search_start + drop_indices[0]
            # The actual peak is the maximum in [c_idx, peak_idx]
            peak_idx = int(np.argmax(voltage[c_idx : peak_idx + 1])) + c_idx

        # Reject subthreshold events
        if voltage[peak_idx] < min_spike_height:
            continue

        # --- Step 3: per-spike metrics ---
        thresh_v = float(voltage[c_idx])
        thresh_t = float(time[c_idx])
        peak_v = float(voltage[peak_idx])
        peak_t = float(time[peak_idx])
        rise_time = peak_t - thresh_t

        # Half-width: duration at half-amplitude level
        half_level = (thresh_v + peak_v) / 2.0
        rise_cross_t = _interpolate_crossing(
            time, voltage, half_level, c_idx, peak_idx + 1, rising=True
        )
        # Search for falling crossing after the peak
        fall_end = n
        fall_cross_t = _interpolate_crossing(
            time, voltage, half_level, peak_idx, fall_end, rising=False
        )
        half_width = fall_cross_t - rise_cross_t
        if half_width < 0:
            raise ValueError(
                f"Spike {len(spikes)}: computed half_width={half_width:.4f} ms is "
                "negative (rise_cross_t={rise_cross_t:.4f}, "
                f"fall_cross_t={fall_cross_t:.4f}).  This indicates a bug in the "
                "crossing-detection logic."
            )

        spikes.append(
            SpikeMetrics(
                index=len(spikes),
                threshold_voltage=thresh_v,
                threshold_time=thresh_t,
                peak_voltage=peak_v,
                peak_time=peak_t,
                rise_time=rise_time,
                half_width=half_width,
                ahp_depth=None,  # filled in below once all peaks are known
            )
        )
        last_peak_idx = peak_idx

    if not spikes:
        return _empty_result()

    # --- Step 4: AHP depth ---
    # Collect peak indices again from the SpikeMetrics for the AHP window.
    peak_times = [s.peak_time for s in spikes]
    thresh_times = [s.threshold_time for s in spikes]

    for i, spike in enumerate(spikes):
        p_t = peak_times[i]
        # AHP window: from peak to the next threshold crossing (or end of trace)
        ahp_end_t = thresh_times[i + 1] if i + 1 < len(spikes) else float(time[-1])
        p_idx = int(np.searchsorted(time, p_t))
        ahp_end_idx = int(np.searchsorted(time, ahp_end_t))
        if ahp_end_idx > p_idx:
            spikes[i] = dataclasses.replace(
                spike, ahp_depth=float(np.min(voltage[p_idx : ahp_end_idx + 1]))
            )

    # --- Step 5: ISIs ---
    isis = [peak_times[i + 1] - peak_times[i] for i in range(len(peak_times) - 1)]

    # --- Step 6: summary statistics ---
    mean_thresh = float(np.mean([s.threshold_voltage for s in spikes]))
    mean_peak = float(np.mean([s.peak_voltage for s in spikes]))
    mean_rise = float(np.mean([s.rise_time for s in spikes]))
    mean_hw = float(np.mean([s.half_width for s in spikes]))

    ahp_values = [s.ahp_depth for s in spikes if s.ahp_depth is not None]
    mean_ahp: float | None = float(np.mean(ahp_values)) if ahp_values else None

    mean_isi: float | None = float(np.mean(isis)) if isis else None
    firing_rate: float | None = (1000.0 / mean_isi) if mean_isi is not None else None

    return APAnalysisResult(
        spike_count=len(spikes),
        spikes=spikes,
        isis=isis,
        mean_threshold_voltage=mean_thresh,
        mean_peak_voltage=mean_peak,
        mean_rise_time=mean_rise,
        mean_half_width=mean_hw,
        mean_ahp_depth=mean_ahp,
        mean_isi=mean_isi,
        firing_rate=firing_rate,
    )

analyze_aps_from_result

analyze_aps_from_result(result, dvdt_threshold=20.0, min_spike_height=-20.0)

Extract AP metrics from a :class:~neuroclamp.SimulationResult.

Convenience wrapper around :func:analyze_aps that pulls the "time" and "voltage" fields from the structured array.

Parameters:

Name Type Description Default
result SimulationResult

A structured NumPy array returned by :func:~neuroclamp.simulate_current_clamp or the voltage-clamp equivalents. Must contain "time" and "voltage" fields.

required
dvdt_threshold float

dV/dt threshold for spike onset detection (mV/ms).

20.0
min_spike_height float

Minimum peak voltage for a valid spike (mV).

-20.0

Returns:

Name Type Description
An APAnalysisResult

class:APAnalysisResult.

Source code in neuroclamp/analysis/ap_metrics.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def analyze_aps_from_result(
    result: SimulationResult,
    dvdt_threshold: float = 20.0,
    min_spike_height: float = -20.0,
) -> APAnalysisResult:
    """Extract AP metrics from a :class:`~neuroclamp.SimulationResult`.

    Convenience wrapper around :func:`analyze_aps` that pulls the ``"time"``
    and ``"voltage"`` fields from the structured array.

    Args:
        result: A structured NumPy array returned by
            :func:`~neuroclamp.simulate_current_clamp` or the voltage-clamp
            equivalents.  Must contain ``"time"`` and ``"voltage"`` fields.
        dvdt_threshold: dV/dt threshold for spike onset detection (mV/ms).
        min_spike_height: Minimum peak voltage for a valid spike (mV).

    Returns:
        An :class:`APAnalysisResult`.
    """
    return analyze_aps(
        result["time"],
        result["voltage"],
        dvdt_threshold=dvdt_threshold,
        min_spike_height=min_spike_height,
    )

analyze_bursts

analyze_bursts(ap_result, *, total_duration_ms, isi_threshold_ms=None, min_spikes_per_burst=_DEFAULT_MIN_SPIKES_PER_BURST, _trace_end_time_ms=None)

Group detected spikes into bursts and compute burst metrics.

Parameters:

Name Type Description Default
ap_result APAnalysisResult

AP analysis from :func:~neuroclamp.analysis.analyze_aps. Provides the spike list and ISIs that drive grouping.

required
total_duration_ms float

Length of the recording window (ms). Used as the denominator of :attr:BurstAnalysisResult.duty_cycle. Typically time[-1] - time[0].

required
isi_threshold_ms float | None

Optional user-supplied threshold (ms). When None, the function attempts a histogram-based auto-detect. If auto-detect cannot find a bimodal split it returns method "default-fixed" with threshold :data:_TIGHT_CLUSTER_MAX_ISI_MS (12 ms): contiguous runs of ISIs at or below this group into bursts, longer ISIs end them. In the default-fixed path a size cap of :data:_TIGHT_CLUSTER_MAX_ISIS + 1 spikes per burst applies, so sustained high-frequency tonic firing is not fabricated into one giant burst (issue #290). Oversized clusters that match the LTS rebound phenotype — fast mean ISI (≤ 6 ms) and pronounced post-burst quiescence — are retained via :func:_is_terminating_lts_cluster, allowing the ~16-spike TRN rebound (Huguenard & Prince 1992) to be reported correctly while the tonic-train protection for Purkinje and HH presets is preserved. Caller-supplied ("user") and histogram-derived ("auto-histogram") thresholds bypass the cap entirely.

None
min_spikes_per_burst int

Minimum spike count for a group to count as a burst. Defaults to 2; isolated spikes are tracked via :attr:BurstAnalysisResult.unburst_spike_count.

_DEFAULT_MIN_SPIKES_PER_BURST
_trace_end_time_ms float | None

Last time point of the recording (ms), used as the quiescent-window reference for the LTS termination check when an oversized cluster ends at the last spike. When None, defaults to the last spike's peak time, which is the safe choice for callers that do not know the recording window.

None

Returns:

Name Type Description
A BurstAnalysisResult

class:BurstAnalysisResult with per-burst and aggregate metrics.

Source code in neuroclamp/analysis/burst_metrics.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
def analyze_bursts(
    ap_result: APAnalysisResult,
    *,
    total_duration_ms: float,
    isi_threshold_ms: float | None = None,
    min_spikes_per_burst: int = _DEFAULT_MIN_SPIKES_PER_BURST,
    _trace_end_time_ms: float | None = None,
) -> BurstAnalysisResult:
    """Group detected spikes into bursts and compute burst metrics.

    Args:
        ap_result: AP analysis from :func:`~neuroclamp.analysis.analyze_aps`.
            Provides the spike list and ISIs that drive grouping.
        total_duration_ms: Length of the recording window (ms).  Used as the
            denominator of :attr:`BurstAnalysisResult.duty_cycle`.  Typically
            ``time[-1] - time[0]``.
        isi_threshold_ms: Optional user-supplied threshold (ms).  When
            ``None``, the function attempts a histogram-based auto-detect.
            If auto-detect cannot find a bimodal split it returns method
            ``"default-fixed"`` with threshold
            :data:`_TIGHT_CLUSTER_MAX_ISI_MS` (12 ms): contiguous runs of
            ISIs at or below this group into bursts, longer ISIs end them.
            In the default-fixed path a size cap of
            :data:`_TIGHT_CLUSTER_MAX_ISIS` + 1 spikes per burst applies,
            so sustained high-frequency tonic firing is not fabricated into
            one giant burst (issue #290).  Oversized clusters that match the
            LTS rebound phenotype — fast mean ISI (≤ 6 ms) and pronounced
            post-burst quiescence — are retained via
            :func:`_is_terminating_lts_cluster`, allowing the ~16-spike TRN
            rebound (Huguenard & Prince 1992) to be reported correctly while
            the tonic-train protection for Purkinje and HH presets is
            preserved.  Caller-supplied (``"user"``) and histogram-derived
            (``"auto-histogram"``) thresholds bypass the cap entirely.
        min_spikes_per_burst: Minimum spike count for a group to count as a
            burst.  Defaults to 2; isolated spikes are tracked via
            :attr:`BurstAnalysisResult.unburst_spike_count`.
        _trace_end_time_ms: Last time point of the recording (ms), used as
            the quiescent-window reference for the LTS termination check
            when an oversized cluster ends at the last spike.  When
            ``None``, defaults to the last spike's peak time, which is the
            safe choice for callers that do not know the recording window.

    Returns:
        A :class:`BurstAnalysisResult` with per-burst and aggregate metrics.
    """
    if isi_threshold_ms is not None:
        threshold = float(isi_threshold_ms)
        method = "user"
    else:
        threshold, method = _estimate_isi_threshold(list(ap_result.isis))

    if ap_result.spike_count == 0:
        return _empty_result(threshold, method)

    # 1-spike traces fall through to the grouper so they are correctly
    # routed to ``unburst_spike_count`` under the default
    # ``min_spikes_per_burst=2`` (or to a single 1-spike burst when the
    # caller has lowered the minimum).
    peak_times = [s.peak_time for s in ap_result.spikes]
    trace_end = (
        float(_trace_end_time_ms)
        if _trace_end_time_ms is not None
        else float(peak_times[-1])
    )
    bursts, trailing_gaps, unburst = _group_spikes_into_bursts(
        peak_times,
        list(ap_result.isis),
        threshold,
        min_spikes_per_burst,
    )

    # In the default-fixed path, apply a size cap so sustained
    # high-frequency tonic firing (issue #290) is not fabricated into one
    # giant burst.  Real LTS-style bursts top out at 7–8 spikes (TC LTS
    # 3–7; STN rebound 3–8).  Oversized clusters that match the LTS rebound
    # phenotype (fast mean ISI and pronounced post-burst quiescence, as
    # identified by :func:`_is_terminating_lts_cluster`) are retained so
    # the ~16-spike TRN rebound is reported correctly.  Caller-supplied
    # (``"user"``) and histogram-derived (``"auto-histogram"``) thresholds
    # bypass the cap entirely.
    if method == "default-fixed" and isi_threshold_ms is None and bursts:
        survivors: list[BurstMetrics] = []
        for burst, gap in zip(bursts, trailing_gaps):
            if burst.spike_count <= _TIGHT_CLUSTER_MAX_ISIS + 1:
                survivors.append(burst)
            elif _is_terminating_lts_cluster(burst, gap, trace_end):
                survivors.append(burst)
            else:
                unburst += burst.spike_count
        bursts = [
            BurstMetrics(
                index=i,
                start_time=b.start_time,
                end_time=b.end_time,
                duration=b.duration,
                spike_count=b.spike_count,
                intra_burst_frequency=b.intra_burst_frequency,
                mean_intra_burst_isi=b.mean_intra_burst_isi,
            )
            for i, b in enumerate(survivors)
        ]

    if not bursts:
        return BurstAnalysisResult(
            burst_count=0,
            bursts=[],
            unburst_spike_count=unburst,
            mean_spikes_per_burst=None,
            mean_intra_burst_frequency=None,
            mean_inter_burst_interval=None,
            duty_cycle=None,
            isi_threshold_ms=threshold,
            threshold_method=method,
        )

    spike_counts = [b.spike_count for b in bursts]
    mean_spikes = float(np.mean(spike_counts))

    freq_values = [
        b.intra_burst_frequency for b in bursts if b.intra_burst_frequency is not None
    ]
    mean_freq: float | None = float(np.mean(freq_values)) if freq_values else None

    if len(bursts) >= 2:
        ibis = [
            bursts[k + 1].start_time - bursts[k].end_time
            for k in range(len(bursts) - 1)
        ]
        mean_ibi: float | None = float(np.mean(ibis))
    else:
        mean_ibi = None

    if total_duration_ms > 0:
        duty_cycle: float | None = float(
            sum(b.duration for b in bursts) / total_duration_ms
        )
    else:
        duty_cycle = None

    return BurstAnalysisResult(
        burst_count=len(bursts),
        bursts=bursts,
        unburst_spike_count=unburst,
        mean_spikes_per_burst=mean_spikes,
        mean_intra_burst_frequency=mean_freq,
        mean_inter_burst_interval=mean_ibi,
        duty_cycle=duty_cycle,
        isi_threshold_ms=threshold,
        threshold_method=method,
    )

analyze_bursts_from_result

analyze_bursts_from_result(result, *, isi_threshold_ms=None, min_spikes_per_burst=_DEFAULT_MIN_SPIKES_PER_BURST, dvdt_threshold=20.0, min_spike_height=-20.0)

Extract burst metrics from a :class:SimulationResult.

Convenience wrapper that runs :func:analyze_aps_from_result to obtain the spike list and then forwards to :func:analyze_bursts. Callers that have already run :func:~neuroclamp.analyze_aps (or :func:~neuroclamp.analyze_aps_from_result) on the same trace should prefer :func:analyze_bursts directly to avoid re-detecting spikes.

Parameters:

Name Type Description Default
result SimulationResult

A structured NumPy array returned by :func:~neuroclamp.simulate_current_clamp or its voltage-clamp equivalents. Must contain "time" and "voltage" fields.

required
isi_threshold_ms float | None

Optional user-supplied threshold (ms).

None
min_spikes_per_burst int

Minimum spike count for a burst.

_DEFAULT_MIN_SPIKES_PER_BURST
dvdt_threshold float

dV/dt threshold passed to spike detection (mV/ms).

20.0
min_spike_height float

Minimum peak voltage for spike detection (mV).

-20.0

Returns:

Name Type Description
A BurstAnalysisResult

class:BurstAnalysisResult.

Source code in neuroclamp/analysis/burst_metrics.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
def analyze_bursts_from_result(
    result: SimulationResult,
    *,
    isi_threshold_ms: float | None = None,
    min_spikes_per_burst: int = _DEFAULT_MIN_SPIKES_PER_BURST,
    dvdt_threshold: float = 20.0,
    min_spike_height: float = -20.0,
) -> BurstAnalysisResult:
    """Extract burst metrics from a :class:`SimulationResult`.

    Convenience wrapper that runs :func:`analyze_aps_from_result` to obtain
    the spike list and then forwards to :func:`analyze_bursts`.  Callers
    that have already run :func:`~neuroclamp.analyze_aps` (or
    :func:`~neuroclamp.analyze_aps_from_result`) on the same trace should
    prefer :func:`analyze_bursts` directly to avoid re-detecting spikes.

    Args:
        result: A structured NumPy array returned by
            :func:`~neuroclamp.simulate_current_clamp` or its voltage-clamp
            equivalents.  Must contain ``"time"`` and ``"voltage"`` fields.
        isi_threshold_ms: Optional user-supplied threshold (ms).
        min_spikes_per_burst: Minimum spike count for a burst.
        dvdt_threshold: dV/dt threshold passed to spike detection (mV/ms).
        min_spike_height: Minimum peak voltage for spike detection (mV).

    Returns:
        A :class:`BurstAnalysisResult`.
    """
    ap_result = analyze_aps_from_result(
        result,
        dvdt_threshold=dvdt_threshold,
        min_spike_height=min_spike_height,
    )
    time = result["time"]
    total_duration_ms = float(time[-1] - time[0]) if len(time) > 1 else 0.0
    return analyze_bursts(
        ap_result,
        total_duration_ms=total_duration_ms,
        isi_threshold_ms=isi_threshold_ms,
        min_spikes_per_burst=min_spikes_per_burst,
        _trace_end_time_ms=float(time[-1]),
    )

analyze_calcium_transients

analyze_calcium_transients(time, ca_i, *, prominence_uM=_DEFAULT_PROMINENCE_UM, min_separation_ms=_DEFAULT_MIN_SEPARATION_MS, max_decay_window_ms=_MAX_DECAY_WINDOW_MS)

Detect calcium transients and extract peak, time-to-peak, and decay τ.

Transients are detected with :func:scipy.signal.find_peaks using a prominence criterion expressed in µM; this is robust to slow baseline drift and does not require an absolute height threshold. For each detected peak the function locates the rise onset, computes a per-transient baseline from a short pre-onset window, and fits a single-exponential decay to the falling phase using :func:scipy.optimize.curve_fit.

Parameters:

Name Type Description Default
time ndarray

Time array in ms, shape (N,).

required
ca_i ndarray

Intracellular [Ca²⁺] in mM, shape (N,), same length as time. Output values are reported in µM.

required
prominence_uM float

Minimum peak prominence in µM. Defaults to 0.05 µM (50 nM), which sits well above typical resting fluctuations and below typical AP-evoked transient amplitudes.

_DEFAULT_PROMINENCE_UM
min_separation_ms float

Minimum spacing between detected peaks in ms.

_DEFAULT_MIN_SEPARATION_MS
max_decay_window_ms float

Cap on the decay-fit window in ms.

_MAX_DECAY_WINDOW_MS

Returns:

Name Type Description
A CalciumTransientAnalysisResult

class:CalciumTransientAnalysisResult with per-transient and

CalciumTransientAnalysisResult

aggregate metrics in µM and ms.

Source code in neuroclamp/analysis/calcium_transients.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def analyze_calcium_transients(
    time: np.ndarray,
    ca_i: np.ndarray,
    *,
    prominence_uM: float = _DEFAULT_PROMINENCE_UM,
    min_separation_ms: float = _DEFAULT_MIN_SEPARATION_MS,
    max_decay_window_ms: float = _MAX_DECAY_WINDOW_MS,
) -> CalciumTransientAnalysisResult:
    """Detect calcium transients and extract peak, time-to-peak, and decay τ.

    Transients are detected with :func:`scipy.signal.find_peaks` using a
    prominence criterion expressed in µM; this is robust to slow baseline
    drift and does not require an absolute height threshold.  For each
    detected peak the function locates the rise onset, computes a
    per-transient baseline from a short pre-onset window, and fits a
    single-exponential decay to the falling phase using
    :func:`scipy.optimize.curve_fit`.

    Args:
        time: Time array in ms, shape ``(N,)``.
        ca_i: Intracellular [Ca²⁺] in **mM**, shape ``(N,)``, same length as
            ``time``.  Output values are reported in µM.
        prominence_uM: Minimum peak prominence in µM.  Defaults to 0.05 µM
            (50 nM), which sits well above typical resting fluctuations and
            below typical AP-evoked transient amplitudes.
        min_separation_ms: Minimum spacing between detected peaks in ms.
        max_decay_window_ms: Cap on the decay-fit window in ms.

    Returns:
        A :class:`CalciumTransientAnalysisResult` with per-transient and
        aggregate metrics in µM and ms.
    """
    time = np.asarray(time, dtype=float)
    ca_i = np.asarray(ca_i, dtype=float)
    n = len(time)

    if n < 2:
        return _empty_result()

    ca_uM = ca_i * _MM_TO_UM

    dt_arr = np.diff(time)
    dt_ms = float(np.median(dt_arr)) if len(dt_arr) > 0 else 0.0
    if dt_ms <= 0.0:
        return _empty_result()

    # --- Global baseline (pre-stimulus mean of the first _GLOBAL_BASELINE_FRACTION) ---
    baseline_samples = max(1, int(_GLOBAL_BASELINE_FRACTION * n))
    global_baseline_uM = float(np.mean(ca_uM[:baseline_samples]))

    # --- Detect peaks ---
    distance = max(1, int(round(min_separation_ms / dt_ms)))
    peak_indices, properties = find_peaks(
        ca_uM, prominence=prominence_uM, distance=distance
    )

    if len(peak_indices) == 0:
        return _empty_result(baseline_concentration=global_baseline_uM)

    # `left_bases` from find_peaks is the lowest point to the left of each
    # peak that bounds the prominence — i.e. the inter-transient trough.
    # We use it as an anchor for both onset detection and per-transient
    # baseline estimation; both are kept independent of `prev_peak_idx`
    # so closely-spaced transients are still characterised correctly.
    left_bases = np.asarray(properties["left_bases"], dtype=int)

    baseline_window_samples = max(1, int(round(_BASELINE_WINDOW_MS / dt_ms)))
    max_decay_samples = max(_MIN_DECAY_SAMPLES, int(round(max_decay_window_ms / dt_ms)))

    transients: list[CalciumTransient] = []

    for i, peak_idx in enumerate(peak_indices):
        peak_idx_int = int(peak_idx)
        peak_uM = float(ca_uM[peak_idx_int])
        left_base = int(left_bases[i])

        # --- Per-transient baseline: short window ending at left_base
        #     (the inter-transient trough), so the rising phase never
        #     contaminates the baseline estimate. ---
        baseline_start = max(0, left_base - baseline_window_samples + 1)
        baseline_end = left_base + 1  # exclusive
        if baseline_end <= baseline_start:
            baseline_uM = float(ca_uM[left_base])
        else:
            baseline_uM = float(np.mean(ca_uM[baseline_start:baseline_end]))

        # --- Onset (walk back from peak to first sample below threshold) ---
        onset_idx = _find_onset(ca_uM, peak_idx_int, baseline_uM, left_base)

        # --- Decay fit window: peak → next onset / end / cap ---
        if i + 1 < len(peak_indices):
            decay_end_idx = int(peak_indices[i + 1])
        else:
            decay_end_idx = n
        decay_end_idx = min(decay_end_idx, peak_idx_int + max_decay_samples)
        decay_end_idx = min(decay_end_idx, n)

        decay_slice = slice(peak_idx_int, decay_end_idx)
        t_decay = time[decay_slice] - time[peak_idx_int]
        ca_decay_uM = ca_uM[decay_slice]

        decay_tau, fit_converged = _fit_decay(
            t_decay, ca_decay_uM, peak_uM, baseline_uM
        )

        peak_time = float(time[peak_idx_int])
        onset_time = float(time[onset_idx])

        transients.append(
            CalciumTransient(
                index=len(transients),
                onset_time=onset_time,
                peak_time=peak_time,
                peak_concentration=peak_uM,
                baseline_concentration=baseline_uM,
                amplitude=peak_uM - baseline_uM,
                time_to_peak=peak_time - onset_time,
                decay_tau=decay_tau,
                decay_fit_converged=fit_converged,
            )
        )

    mean_peak = float(np.mean([t.peak_concentration for t in transients]))
    mean_ttp = float(np.mean([t.time_to_peak for t in transients]))
    mean_amp = float(np.mean([t.amplitude for t in transients]))

    tau_values = [t.decay_tau for t in transients if t.decay_tau is not None]
    mean_tau: float | None = float(np.mean(tau_values)) if tau_values else None

    return CalciumTransientAnalysisResult(
        transient_count=len(transients),
        transients=transients,
        baseline_concentration=global_baseline_uM,
        mean_peak_concentration=mean_peak,
        mean_time_to_peak=mean_ttp,
        mean_decay_tau=mean_tau,
        mean_amplitude=mean_amp,
    )

analyze_calcium_transients_from_result

analyze_calcium_transients_from_result(result, *, prominence_uM=_DEFAULT_PROMINENCE_UM, min_separation_ms=_DEFAULT_MIN_SEPARATION_MS, max_decay_window_ms=_MAX_DECAY_WINDOW_MS)

Extract calcium transient metrics from a :class:SimulationResult.

Convenience wrapper around :func:analyze_calcium_transients that pulls the "time" and "ca_i" fields from the structured array. Returns None when ca_i is absent (i.e. calcium dynamics were not active during the simulation).

Parameters:

Name Type Description Default
result SimulationResult

A structured NumPy array returned by :func:~neuroclamp.simulate_current_clamp or its voltage-clamp equivalents.

required
prominence_uM float

Minimum peak prominence in µM.

_DEFAULT_PROMINENCE_UM
min_separation_ms float

Minimum spacing between detected peaks in ms.

_DEFAULT_MIN_SEPARATION_MS
max_decay_window_ms float

Cap on the decay-fit window in ms.

_MAX_DECAY_WINDOW_MS

Returns:

Name Type Description
A CalciumTransientAnalysisResult | None

class:CalciumTransientAnalysisResult when ca_i is present,

CalciumTransientAnalysisResult | None

otherwise None.

Source code in neuroclamp/analysis/calcium_transients.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def analyze_calcium_transients_from_result(
    result: SimulationResult,
    *,
    prominence_uM: float = _DEFAULT_PROMINENCE_UM,
    min_separation_ms: float = _DEFAULT_MIN_SEPARATION_MS,
    max_decay_window_ms: float = _MAX_DECAY_WINDOW_MS,
) -> CalciumTransientAnalysisResult | None:
    """Extract calcium transient metrics from a :class:`SimulationResult`.

    Convenience wrapper around :func:`analyze_calcium_transients` that pulls
    the ``"time"`` and ``"ca_i"`` fields from the structured array.  Returns
    ``None`` when ``ca_i`` is absent (i.e. calcium dynamics were not active
    during the simulation).

    Args:
        result: A structured NumPy array returned by
            :func:`~neuroclamp.simulate_current_clamp` or its voltage-clamp
            equivalents.
        prominence_uM: Minimum peak prominence in µM.
        min_separation_ms: Minimum spacing between detected peaks in ms.
        max_decay_window_ms: Cap on the decay-fit window in ms.

    Returns:
        A :class:`CalciumTransientAnalysisResult` when ``ca_i`` is present,
        otherwise ``None``.
    """
    field_names = result.dtype.names
    if field_names is None or "ca_i" not in field_names:
        return None

    return analyze_calcium_transients(
        result["time"],
        result["ca_i"],
        prominence_uM=prominence_uM,
        min_separation_ms=min_separation_ms,
        max_decay_window_ms=max_decay_window_ms,
    )

compute_dvdt

compute_dvdt(time, voltage)

Compute dV/dt from time and voltage arrays.

Uses np.gradient (central differences) so the output length matches the input length, avoiding the off-by-one issue of np.diff.

Parameters:

Name Type Description Default
time ArrayLike

Time array in ms (length N).

required
voltage ArrayLike

Membrane voltage array in mV (length N).

required

Raises:

Type Description
ValueError

If time and voltage have different lengths.

Returns:

Type Description
ndarray

dvdt array in mV/ms with the same length as voltage.

ndarray

If len(time) < 2, an empty array is returned.

Source code in neuroclamp/analysis/derivatives.py
 7
 8
 9
10
11
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
def compute_dvdt(
    time: npt.ArrayLike,
    voltage: npt.ArrayLike,
) -> np.ndarray:
    """Compute dV/dt from time and voltage arrays.

    Uses ``np.gradient`` (central differences) so the output length matches
    the input length, avoiding the off-by-one issue of ``np.diff``.

    Args:
        time: Time array in ms (length N).
        voltage: Membrane voltage array in mV (length N).

    Raises:
        ValueError: If ``time`` and ``voltage`` have different lengths.

    Returns:
        ``dvdt`` array in mV/ms with the same length as ``voltage``.
        If ``len(time) < 2``, an empty array is returned.
    """
    time = np.asarray(time, dtype=float)
    voltage = np.asarray(voltage, dtype=float)
    if len(time) != len(voltage):
        raise ValueError(
            f"time and voltage must have the same length; "
            f"got {len(time)} and {len(voltage)}"
        )
    if len(time) < 2:
        return np.empty(0)
    return np.gradient(voltage, time)

analyze_fi

analyze_fi(time, voltages, current_steps, stim_start_ms, stim_end_ms)

Compute F-I curve from a multi-sweep current clamp simulation.

Calls :func:compute_fi_point for each sweep and assembles the results, sorted in ascending order of current step.

Parameters:

Name Type Description Default
time ndarray

Shared time axis in ms (same for all sweeps).

required
voltages list[ndarray]

List of membrane voltage arrays (mV), one per sweep.

required
current_steps list[float]

Injected current amplitude (µA/cm²) for each sweep, parallel to voltages.

required
stim_start_ms float

Start of the stimulus window in ms.

required
stim_end_ms float

End of the stimulus window in ms.

required

Returns:

Name Type Description
An FIAnalysisResult

class:FIAnalysisResult with per-step measurements sorted by

FIAnalysisResult

current amplitude.

Source code in neuroclamp/analysis/fi_curve.py
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
def analyze_fi(
    time: np.ndarray,
    voltages: list[np.ndarray],
    current_steps: list[float],
    stim_start_ms: float,
    stim_end_ms: float,
) -> FIAnalysisResult:
    """Compute F-I curve from a multi-sweep current clamp simulation.

    Calls :func:`compute_fi_point` for each sweep and assembles the results,
    sorted in ascending order of current step.

    Args:
        time: Shared time axis in ms (same for all sweeps).
        voltages: List of membrane voltage arrays (mV), one per sweep.
        current_steps: Injected current amplitude (µA/cm²) for each sweep,
            parallel to ``voltages``.
        stim_start_ms: Start of the stimulus window in ms.
        stim_end_ms: End of the stimulus window in ms.

    Returns:
        An :class:`FIAnalysisResult` with per-step measurements sorted by
        current amplitude.
    """
    points = [
        compute_fi_point(time, voltage, i_step, stim_start_ms, stim_end_ms)
        for voltage, i_step in zip(voltages, current_steps)
    ]
    points.sort(key=lambda p: p.current_step)
    return FIAnalysisResult(points=points)

compute_fi_point

compute_fi_point(time, voltage, current_step, stim_start_ms, stim_end_ms)

Compute F-I metrics for a single current step sweep.

Detects spikes using :func:~neuroclamp.analysis.ap_metrics.analyze_aps and delegates to :func:_fi_point_from_ap_result for the rate computation.

Parameters:

Name Type Description Default
time ndarray

Time axis array in ms.

required
voltage ndarray

Membrane voltage array in mV, same length as time.

required
current_step float

Injected current amplitude during the step (µA/cm²).

required
stim_start_ms float

Start of the stimulus window in ms.

required
stim_end_ms float

End of the stimulus window in ms.

required

Returns:

Name Type Description
An FIPoint

class:FIPoint with spike count and firing rate measurements for

FIPoint

this current step.

Source code in neuroclamp/analysis/fi_curve.py
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
def compute_fi_point(
    time: np.ndarray,
    voltage: np.ndarray,
    current_step: float,
    stim_start_ms: float,
    stim_end_ms: float,
) -> FIPoint:
    """Compute F-I metrics for a single current step sweep.

    Detects spikes using :func:`~neuroclamp.analysis.ap_metrics.analyze_aps`
    and delegates to :func:`_fi_point_from_ap_result` for the rate computation.

    Args:
        time: Time axis array in ms.
        voltage: Membrane voltage array in mV, same length as ``time``.
        current_step: Injected current amplitude during the step (µA/cm²).
        stim_start_ms: Start of the stimulus window in ms.
        stim_end_ms: End of the stimulus window in ms.

    Returns:
        An :class:`FIPoint` with spike count and firing rate measurements for
        this current step.
    """
    return _fi_point_from_ap_result(
        analyze_aps(time, voltage), current_step, stim_start_ms, stim_end_ms
    )

estimate_rheobase

estimate_rheobase(fi_result)

Estimate the rheobase from F-I analysis results.

The rheobase is the minimum injected current that elicits at least one action potential. It is identified as the lowest current step with a non-zero spike count. A single spike qualifies as suprathreshold even though it produces no ISI-derived firing rate.

Parameters:

Name Type Description Default
fi_result FIAnalysisResult

F-I analysis result. Points may be in any order.

required

Returns:

Type Description
float | None

The rheobase current in µA/cm² (the current_step of the first

float | None

class:FIPoint with spike_count >= 1), or None when no

float | None

sweep produced a spike.

Source code in neuroclamp/analysis/fi_curve.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def estimate_rheobase(fi_result: FIAnalysisResult) -> float | None:
    """Estimate the rheobase from F-I analysis results.

    The rheobase is the minimum injected current that elicits at least one
    action potential.  It is identified as the lowest current step with a
    non-zero spike count.  A single spike qualifies as suprathreshold even
    though it produces no ISI-derived firing rate.

    Args:
        fi_result: F-I analysis result.  Points may be in any order.

    Returns:
        The rheobase current in µA/cm² (the ``current_step`` of the first
        :class:`FIPoint` with ``spike_count >= 1``), or ``None`` when no
        sweep produced a spike.
    """
    spiking = [p.current_step for p in fi_result.points if p.spike_count >= 1]
    return min(spiking) if spiking else None

boltzmann

boltzmann(V, v_half, k)

Evaluate the two-parameter Boltzmann sigmoid.

Computes the standard voltage-dependent activation function::

f(V) = 1 / (1 + exp(-(V - v_half) / k))

Accepts either a scalar float or a NumPy array for V, which allows the function to be used directly with scipy.optimize.curve_fit.

Parameters:

Name Type Description Default
V float | ndarray

Membrane voltage in mV. May be a scalar or a 1-D NumPy array.

required
v_half float

Half-activation voltage (mV).

required
k float

Slope factor (mV).

required

Returns:

Type Description
float | ndarray

Sigmoid value in [0, 1]. Returns a NumPy array when V is an array,

float | ndarray

or a float when V is a scalar.

Source code in neuroclamp/analysis/gv_curve.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def boltzmann(
    V: float | np.ndarray,
    v_half: float,
    k: float,
) -> float | np.ndarray:
    """Evaluate the two-parameter Boltzmann sigmoid.

    Computes the standard voltage-dependent activation function::

        f(V) = 1 / (1 + exp(-(V - v_half) / k))

    Accepts either a scalar float or a NumPy array for *V*, which allows the
    function to be used directly with ``scipy.optimize.curve_fit``.

    Args:
        V: Membrane voltage in mV.  May be a scalar or a 1-D NumPy array.
        v_half: Half-activation voltage (mV).
        k: Slope factor (mV).

    Returns:
        Sigmoid value in [0, 1].  Returns a NumPy array when *V* is an array,
        or a float when *V* is a scalar.
    """
    return 1.0 / (1.0 + np.exp(-(V - v_half) / k))

compute_gv

compute_gv(iv_result, reversal_potential, driving_force_threshold=5.0)

Compute normalized conductance vs. voltage from I-V analysis results.

For each voltage step the chord conductance is::

g(V) = I_peak_inward / (V - E_rev)

where E_rev is the supplied reversal potential. Points where the absolute driving force |V - E_rev| is below driving_force_threshold are excluded to avoid division-by-near-zero artefacts. Points that produce non-positive conductances (physically implausible for the inward activation curve) are also excluded.

The retained conductances are normalized to G/G_max, then a Boltzmann sigmoid is fitted via scipy.optimize.curve_fit. If the fit does not converge, :attr:BoltzmannFit.converged is False and the parameter values are 0.0 and 1.0 respectively.

Parameters:

Name Type Description Default
iv_result IVAnalysisResult

Pre-computed I-V analysis result containing per-step peak inward currents.

required
reversal_potential float

Reversal potential used to compute driving force (mV). Typically the Nernst potential for the dominant inward current carrier (e.g. E_Na).

required
driving_force_threshold float

Minimum absolute driving force (mV) required for a point to be included. Defaults to 5.0.

5.0

Returns:

Name Type Description
A GVAnalysisResult

class:GVAnalysisResult with sorted per-step conductance records

GVAnalysisResult

and Boltzmann fit parameters.

Source code in neuroclamp/analysis/gv_curve.py
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
217
218
219
220
221
222
def compute_gv(
    iv_result: IVAnalysisResult,
    reversal_potential: float,
    driving_force_threshold: float = 5.0,
) -> GVAnalysisResult:
    """Compute normalized conductance vs. voltage from I-V analysis results.

    For each voltage step the chord conductance is::

        g(V) = I_peak_inward / (V - E_rev)

    where ``E_rev`` is the supplied reversal potential.  Points where the
    absolute driving force ``|V - E_rev|`` is below *driving_force_threshold*
    are excluded to avoid division-by-near-zero artefacts.  Points that
    produce non-positive conductances (physically implausible for the inward
    activation curve) are also excluded.

    The retained conductances are normalized to G/G_max, then a Boltzmann
    sigmoid is fitted via ``scipy.optimize.curve_fit``.  If the fit does not
    converge, :attr:`BoltzmannFit.converged` is ``False`` and the parameter
    values are ``0.0`` and ``1.0`` respectively.

    Args:
        iv_result: Pre-computed I-V analysis result containing per-step peak
            inward currents.
        reversal_potential: Reversal potential used to compute driving force
            (mV).  Typically the Nernst potential for the dominant inward
            current carrier (e.g. E_Na).
        driving_force_threshold: Minimum absolute driving force (mV) required
            for a point to be included.  Defaults to ``5.0``.

    Returns:
        A :class:`GVAnalysisResult` with sorted per-step conductance records
        and Boltzmann fit parameters.
    """
    # Sentinel returned on failure; parameter values are never exposed to the
    # user because all callers check BoltzmannFit.converged before using them.
    _null_fit = BoltzmannFit(v_half=0.0, k=1.0, converged=False)

    if not iv_result.points:
        return GVAnalysisResult(
            points=[], boltzmann=_null_fit, reversal_potential=reversal_potential
        )

    # --- compute chord conductances and filter ---
    valid: list[tuple[float, float]] = []  # (voltage_step, conductance)
    for pt in iv_result.points:
        df = pt.voltage_step - reversal_potential
        if abs(df) < driving_force_threshold:
            continue
        g = pt.peak_inward_current / df
        if g <= 0.0:
            continue
        valid.append((pt.voltage_step, g))

    if len(valid) < 2:
        return GVAnalysisResult(
            points=[], boltzmann=_null_fit, reversal_potential=reversal_potential
        )

    valid.sort(key=lambda x: x[0])
    voltages = [v for v, _ in valid]
    conductances = [g for _, g in valid]

    g_max = max(conductances)
    g_norm = [g / g_max for g in conductances]

    points = [
        GVPoint(voltage_step=v, conductance=g, g_normalized=gn)
        for v, g, gn in zip(voltages, conductances, g_norm)
    ]

    # --- fit Boltzmann ---
    v_arr = np.array(voltages, dtype=float)
    gn_arr = np.array(g_norm, dtype=float)

    fit = _null_fit
    try:
        popt, _ = curve_fit(
            boltzmann,
            v_arr,
            gn_arr,
            p0=[_VHALF_GUESS, _K_GUESS],
            bounds=(
                [_VHALF_BOUNDS[0], _K_BOUNDS[0]],
                [_VHALF_BOUNDS[1], _K_BOUNDS[1]],
            ),
            maxfev=2000,
        )
        fit = BoltzmannFit(v_half=float(popt[0]), k=float(popt[1]), converged=True)
    except (RuntimeError, ValueError) as exc:
        logger.debug("Boltzmann fit did not converge: %s", exc)

    return GVAnalysisResult(
        points=points,
        boltzmann=fit,
        reversal_potential=reversal_potential,
    )

analyze_hyperpolarization

analyze_hyperpolarization(time, voltages, current_steps, stim_start_ms, stim_end_ms, rebound_window_ms=50.0)

Compute sag and rebound metrics from a multi-sweep hyperpolarization run.

Calls :func:compute_sag_point for each sweep and assembles the results, sorted in ascending order of current step (most negative first). Rebound spike counts are mechanism-agnostic; see the module docstring for the mechanisms that contribute in different neuron models.

Parameters:

Name Type Description Default
time ndarray

Shared time axis in ms (same for all sweeps).

required
voltages list[ndarray]

List of membrane voltage arrays (mV), one per sweep.

required
current_steps list[float]

Injected current amplitude (µA/cm²) for each sweep, parallel to voltages.

required
stim_start_ms float

Start of the current step in ms.

required
stim_end_ms float

End of the current step in ms.

required
rebound_window_ms float

Duration of the post-step window in which rebound spikes are counted (ms).

50.0

Returns:

Name Type Description
A HyperpolarizationAnalysisResult

class:HyperpolarizationAnalysisResult with per-step measurements

HyperpolarizationAnalysisResult

sorted by current amplitude (most negative first).

Source code in neuroclamp/analysis/hyperpolarization.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def analyze_hyperpolarization(
    time: np.ndarray,
    voltages: list[np.ndarray],
    current_steps: list[float],
    stim_start_ms: float,
    stim_end_ms: float,
    rebound_window_ms: float = 50.0,
) -> HyperpolarizationAnalysisResult:
    """Compute sag and rebound metrics from a multi-sweep hyperpolarization run.

    Calls :func:`compute_sag_point` for each sweep and assembles the results,
    sorted in ascending order of current step (most negative first).  Rebound
    spike counts are mechanism-agnostic; see the module docstring for the
    mechanisms that contribute in different neuron models.

    Args:
        time: Shared time axis in ms (same for all sweeps).
        voltages: List of membrane voltage arrays (mV), one per sweep.
        current_steps: Injected current amplitude (µA/cm²) for each sweep,
            parallel to ``voltages``.
        stim_start_ms: Start of the current step in ms.
        stim_end_ms: End of the current step in ms.
        rebound_window_ms: Duration of the post-step window in which rebound
            spikes are counted (ms).

    Returns:
        A :class:`HyperpolarizationAnalysisResult` with per-step measurements
        sorted by current amplitude (most negative first).
    """
    points = [
        compute_sag_point(
            time, voltage, i_step, stim_start_ms, stim_end_ms, rebound_window_ms
        )
        for voltage, i_step in zip(voltages, current_steps)
    ]
    points.sort(key=lambda p: p.current_step)
    return HyperpolarizationAnalysisResult(points=points)

compute_sag_point

compute_sag_point(time, voltage, current_step, stim_start_ms, stim_end_ms, rebound_window_ms=50.0, steady_state_fraction=0.15)

Compute sag and rebound metrics for a single hyperpolarizing sweep.

Peak voltage is the minimum of the voltage trace during the step. Steady-state voltage is the mean over the last steady_state_fraction of the step duration. Rebound spikes are action potentials whose peak time falls within [stim_end_ms, stim_end_ms + rebound_window_ms]. The count is mechanism-agnostic: ICaT de-inactivation, Ih overshoot, and HH anode-break excitation all contribute equally.

Parameters:

Name Type Description Default
time ndarray

Time axis array in ms.

required
voltage ndarray

Membrane voltage array in mV, same length as time.

required
current_step float

Injected current amplitude during the step (µA/cm²).

required
stim_start_ms float

Start of the current step in ms.

required
stim_end_ms float

End of the current step in ms.

required
rebound_window_ms float

Duration of the post-step window in which rebound spikes are counted (ms).

50.0
steady_state_fraction float

Fraction of the step duration used to compute the steady-state voltage (trailing portion of the step).

0.15

Returns:

Name Type Description
A SagPoint

class:SagPoint with sag and rebound measurements for this sweep.

Source code in neuroclamp/analysis/hyperpolarization.py
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
def compute_sag_point(
    time: np.ndarray,
    voltage: np.ndarray,
    current_step: float,
    stim_start_ms: float,
    stim_end_ms: float,
    rebound_window_ms: float = 50.0,
    steady_state_fraction: float = 0.15,
) -> SagPoint:
    """Compute sag and rebound metrics for a single hyperpolarizing sweep.

    Peak voltage is the minimum of the voltage trace during the step.
    Steady-state voltage is the mean over the last ``steady_state_fraction`` of
    the step duration.  Rebound spikes are action potentials whose peak time
    falls within ``[stim_end_ms, stim_end_ms + rebound_window_ms]``.  The count
    is mechanism-agnostic: ICaT de-inactivation, Ih overshoot, and HH anode-break
    excitation all contribute equally.

    Args:
        time: Time axis array in ms.
        voltage: Membrane voltage array in mV, same length as ``time``.
        current_step: Injected current amplitude during the step (µA/cm²).
        stim_start_ms: Start of the current step in ms.
        stim_end_ms: End of the current step in ms.
        rebound_window_ms: Duration of the post-step window in which rebound
            spikes are counted (ms).
        steady_state_fraction: Fraction of the step duration used to compute
            the steady-state voltage (trailing portion of the step).

    Returns:
        A :class:`SagPoint` with sag and rebound measurements for this sweep.
    """
    return _sag_point_from_ap_result(
        time,
        voltage,
        analyze_aps(time, voltage),
        current_step,
        stim_start_ms,
        stim_end_ms,
        rebound_window_ms,
        steady_state_fraction,
    )

analyze_impedance

analyze_impedance(time, voltage, injected_current, stim_start_ms, stim_end_ms, f_start, f_end, area_cm2=None)

Compute the membrane impedance profile from a chirp current-clamp run.

Extracts the chirp window from the traces, removes the DC component from both signals, takes the real FFT of each (numpy.fft.rfft), forms Z(f) = V̂(f) / Î(f) over the swept band [f_start, f_end] (keeping only the longest contiguous run of FFT bins where the chirp has usable spectral power), and reports the magnitude and phase spectra, the band-maximum impedance, plus — when a genuine resonance is present — the resonance frequency and quality factor. A genuine resonance requires an interior |Z| maximum that clears the prominence margin over the low-frequency reference and has a half-power (−3 dB) width that is both bracketable inside the band and at least one FFT bin wide; resonance_frequency, peak_impedance and quality_factor are otherwise all None.

Membrane impedance is a linear, small-signal quantity, so spike transients are excluded: when the windowed response contains spikes the analysis falls back to the longest contiguous spike-free sub-window (a linear chirp's frequency is time-dependent, so the recovered profile then covers only a sub-band of [f_start, f_end] — surfaced via :attr:ImpedanceProfile.analyzed_window_ms). The analysis bails out (returns None) when no such spike-free segment is long enough — see :func:impedance_unavailable_reason for the user-facing reason.

Parameters:

Name Type Description Default
time ndarray

Time axis in ms, assumed uniformly sampled (the FFT frequency axis is derived from the mean sample interval).

required
voltage ndarray

Membrane voltage response in mV.

required
injected_current ndarray

Injected chirp current in µA/cm².

required
stim_start_ms float

Start of the chirp stimulus window in ms.

required
stim_end_ms float

End of the chirp stimulus window in ms.

required
f_start float

Starting frequency of the chirp sweep in Hz.

required
f_end float

Ending frequency of the chirp sweep in Hz.

required
area_cm2 float | None

Optional membrane surface area in cm². When supplied, the absolute MΩ counterparts (magnitude_mohm, max_impedance_mohm, peak_impedance_mohm) are populated.

None

Returns:

Name Type Description
An ImpedanceProfile | None

class:ImpedanceProfile, or None when the inputs are

ImpedanceProfile | None

inconsistent (mismatched lengths, non-finite values), the band is

ImpedanceProfile | None

invalid (f_end <= f_start or f_start < 0), the chirp window is

ImpedanceProfile | None

shorter than :data:_MIN_WINDOW_MS, the response fires throughout the

ImpedanceProfile | None

chirp (no spike-free segment of at least :data:_MIN_WINDOW_MS), the

ImpedanceProfile | None

stimulus has no spectral power in the band, or fewer than

ImpedanceProfile | None

data:_MIN_BAND_BINS FFT bins remain after band-edge trimming.

Source code in neuroclamp/analysis/impedance.py
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def analyze_impedance(
    time: np.ndarray,
    voltage: np.ndarray,
    injected_current: np.ndarray,
    stim_start_ms: float,
    stim_end_ms: float,
    f_start: float,
    f_end: float,
    area_cm2: float | None = None,
) -> ImpedanceProfile | None:
    """Compute the membrane impedance profile from a chirp current-clamp run.

    Extracts the chirp window from the traces, removes the DC component from
    both signals, takes the real FFT of each (``numpy.fft.rfft``), forms
    ``Z(f) = V̂(f) / Î(f)`` over the swept band ``[f_start, f_end]`` (keeping
    only the longest contiguous run of FFT bins where the chirp has usable
    spectral power), and reports the magnitude and phase spectra, the
    band-maximum impedance, plus — when a genuine resonance is present — the
    resonance frequency and quality factor.  A genuine resonance requires an
    interior ``|Z|`` maximum that clears the prominence margin over the
    low-frequency reference and has a half-power (−3 dB) width that is both
    bracketable inside the band and at least one FFT bin wide;
    ``resonance_frequency``, ``peak_impedance`` and ``quality_factor`` are
    otherwise all ``None``.

    Membrane impedance is a linear, small-signal quantity, so spike transients
    are excluded: when the windowed response contains spikes the analysis falls
    back to the longest contiguous spike-free sub-window (a linear chirp's
    frequency is time-dependent, so the recovered profile then covers only a
    sub-band of ``[f_start, f_end]`` — surfaced via
    :attr:`ImpedanceProfile.analyzed_window_ms`).  The analysis bails out
    (returns ``None``) when no such spike-free segment is long enough — see
    :func:`impedance_unavailable_reason` for the user-facing reason.

    Args:
        time: Time axis in ms, assumed uniformly sampled (the FFT frequency
            axis is derived from the mean sample interval).
        voltage: Membrane voltage response in mV.
        injected_current: Injected chirp current in µA/cm².
        stim_start_ms: Start of the chirp stimulus window in ms.
        stim_end_ms: End of the chirp stimulus window in ms.
        f_start: Starting frequency of the chirp sweep in Hz.
        f_end: Ending frequency of the chirp sweep in Hz.
        area_cm2: Optional membrane surface area in cm².  When supplied, the
            absolute MΩ counterparts (``magnitude_mohm``, ``max_impedance_mohm``,
            ``peak_impedance_mohm``) are populated.

    Returns:
        An :class:`ImpedanceProfile`, or ``None`` when the inputs are
        inconsistent (mismatched lengths, non-finite values), the band is
        invalid (``f_end <= f_start`` or ``f_start < 0``), the chirp window is
        shorter than :data:`_MIN_WINDOW_MS`, the response fires throughout the
        chirp (no spike-free segment of at least :data:`_MIN_WINDOW_MS`), the
        stimulus has no spectral power in the band, or fewer than
        :data:`_MIN_BAND_BINS` FFT bins remain after band-edge trimming.
    """
    # _prepare_impedance_window returns exactly one of (reason, None) /
    # (None, prepared), so a None `prepared` always carries a non-empty reason.
    reason, prepared = _prepare_impedance_window(
        time, voltage, injected_current, stim_start_ms, stim_end_ms, f_start, f_end
    )
    if prepared is None:
        logger.warning("analyze_impedance: %s", reason)
        return None
    t_win, v_win, i_win, analyzed_window_ms = prepared

    dt_ms = float(np.mean(np.diff(t_win)))
    if dt_ms <= 0.0:
        logger.warning("analyze_impedance: non-positive sampling interval; skipping.")
        return None
    fs_hz = 1000.0 / dt_ms

    # Remove the DC component from both signals before transforming.  No
    # additional taper is applied: a linear chirp already starts at zero
    # phase, and its magnitude spectrum is approximately flat across the swept
    # band, so a Hann (or similar) window is counter-productive here — it
    # heavily attenuates the chirp's low- and high-frequency content (which
    # lives in its first and last cycles) and inflates the band-edge impedance
    # estimate where the windowed stimulus energy collapses toward zero.
    v_d = v_win - v_win.mean()
    i_d = i_win - i_win.mean()
    n = v_d.size

    v_fft = np.fft.rfft(v_d)
    i_fft = np.fft.rfft(i_d)
    freqs = np.fft.rfftfreq(n, d=1.0 / fs_hz)

    band = (freqs >= f_start) & (freqs <= f_end)
    if int(band.sum()) < _MIN_BAND_BINS:
        logger.warning(
            "analyze_impedance: only %d FFT bins in band; need %d; skipping.",
            int(band.sum()),
            _MIN_BAND_BINS,
        )
        return None
    fb = freqs[band]
    v_band = v_fft[band]
    i_band = i_fft[band]

    i_mag = np.abs(i_band)
    i_max = float(np.max(i_mag))
    if i_max <= 0.0:
        logger.warning("analyze_impedance: stimulus has no power in band; skipping.")
        return None
    # Keep only the longest contiguous run of bins with usable stimulus power so
    # that dividing by a near-zero stimulus cannot inflate the band-edge
    # estimate or spike it at an interior dropout.
    lo, hi = _longest_usable_run(i_mag, _MIN_STIM_FRAC * i_max)
    if hi - lo < _MIN_BAND_BINS:
        logger.warning(
            "analyze_impedance: only %d FFT bins with usable stimulus power; "
            "need %d; skipping.",
            hi - lo,
            _MIN_BAND_BINS,
        )
        return None
    fb = fb[lo:hi]
    v_band = v_band[lo:hi]
    i_band = i_band[lo:hi]

    z = v_band / i_band
    mag = np.abs(z)
    phase_deg = np.degrees(np.angle(z))

    max_impedance = float(np.max(mag))
    peak_idx = int(np.argmax(mag))
    # Reference the low-frequency end with a small average to be robust to
    # spectral leakage in the first bin.
    low_ref = float(np.mean(mag[: min(3, mag.size)]))
    # A resonance is reported only when the interior |Z| peak both clears the
    # prominence margin and has a measurable -3 dB width, so that f_R, the peak
    # impedance, and Q always populate (or blank) together — a "resonance" with
    # no bracketable half-power bandwidth is just measurement ripple on an
    # otherwise monotone passive response.
    peak_prominent = 0 < peak_idx < mag.size - 1 and float(mag[peak_idx]) > low_ref * (
        1.0 + _RESONANCE_REL_MARGIN
    )
    q = _quality_factor(fb, mag, peak_idx) if peak_prominent else None
    if q is not None:
        # The resonance peak is the band maximum (peak_idx == argmax(mag)), so
        # peak_impedance == max_impedance here; keep both for callers that want
        # the resonance-specific value to be None when there is no resonance.
        resonance_frequency: float | None = float(fb[peak_idx])
        peak_impedance: float | None = max_impedance
        quality_factor: float | None = q
    else:
        resonance_frequency = None
        peak_impedance = None
        quality_factor = None

    if area_cm2 is not None and area_cm2 > 0.0:
        # Per the density_to_absolute_r_in derivation: kΩ·cm² / area / 1000 = MΩ.
        magnitude_mohm: list[float] | None = [float(m) / area_cm2 / 1000.0 for m in mag]
    else:
        magnitude_mohm = None
    max_impedance_mohm = density_to_absolute_r_in(max_impedance, area_cm2)
    peak_impedance_mohm = (
        density_to_absolute_r_in(peak_impedance, area_cm2)
        if peak_impedance is not None
        else None
    )

    return ImpedanceProfile(
        frequencies=fb.tolist(),
        magnitude=mag.tolist(),
        phase=phase_deg.tolist(),
        max_impedance=max_impedance,
        resonance_frequency=resonance_frequency,
        peak_impedance=peak_impedance,
        quality_factor=quality_factor,
        magnitude_mohm=magnitude_mohm,
        max_impedance_mohm=max_impedance_mohm,
        peak_impedance_mohm=peak_impedance_mohm,
        area_cm2=area_cm2,
        f_start=float(f_start),
        f_end=float(f_end),
        analyzed_window_ms=analyzed_window_ms,
    )

impedance_unavailable_reason

impedance_unavailable_reason(time, voltage, injected_current, stim_start_ms, stim_end_ms, f_start, f_end)

Return a human-readable reason impedance analysis can't proceed, or "".

Returns the empty string when the cheap pre-FFT checks pass (so the analysis would proceed past the windowing / suprathreshold guards), letting callers use the result directly as UI copy. Only those pre-FFT failure modes are reported — when this returns "" and :func:analyze_impedance still returns None, the caller should fall back to a generic "too little usable signal in the band" message.

Parameters:

Name Type Description Default
time ndarray

Time axis in ms.

required
voltage ndarray

Membrane voltage response in mV.

required
injected_current ndarray

Injected chirp current in µA/cm².

required
stim_start_ms float

Start of the chirp stimulus window in ms.

required
stim_end_ms float

End of the chirp stimulus window in ms.

required
f_start float

Starting frequency of the chirp sweep in Hz.

required
f_end float

Ending frequency of the chirp sweep in Hz.

required

Returns:

Type Description
str

A single-sentence reason string, or "" when the preamble checks

str

pass.

Source code in neuroclamp/analysis/impedance.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def impedance_unavailable_reason(
    time: np.ndarray,
    voltage: np.ndarray,
    injected_current: np.ndarray,
    stim_start_ms: float,
    stim_end_ms: float,
    f_start: float,
    f_end: float,
) -> str:
    """Return a human-readable reason impedance analysis can't proceed, or ``""``.

    Returns the empty string when the cheap pre-FFT checks pass (so the
    analysis would proceed past the windowing / suprathreshold guards), letting
    callers use the result directly as UI copy.  Only those pre-FFT failure
    modes are reported — when this returns ``""`` and :func:`analyze_impedance`
    still returns ``None``, the caller should fall back to a generic "too little
    usable signal in the band" message.

    Args:
        time: Time axis in ms.
        voltage: Membrane voltage response in mV.
        injected_current: Injected chirp current in µA/cm².
        stim_start_ms: Start of the chirp stimulus window in ms.
        stim_end_ms: End of the chirp stimulus window in ms.
        f_start: Starting frequency of the chirp sweep in Hz.
        f_end: Ending frequency of the chirp sweep in Hz.

    Returns:
        A single-sentence reason string, or ``""`` when the preamble checks
        pass.
    """
    reason, _ = _prepare_impedance_window(
        time, voltage, injected_current, stim_start_ms, stim_end_ms, f_start, f_end
    )
    return reason or ""

compute_inactivation

compute_inactivation(iv_result)

Compute normalized availability vs. prepulse voltage from I-V results.

Each :class:~neuroclamp.analysis.iv_curve.IVPoint in iv_result is assumed to come from one sweep of a two-pulse inactivation protocol: its voltage_step is the conditioning prepulse voltage and its peak_inward_current is the most negative current measured during the fixed test pulse. Availability is::

h∞(V) = I_peak(V) / I_peak_max

where I_peak_max is the most negative peak across all prepulses; the ratio is clamped to [0, 1] (a non-negative test-pulse peak — full inactivation, possibly net outward — maps to 0.0).

A decreasing Boltzmann sigmoid h∞(V) = 1 / (1 + exp((V - v_half) / k)) is then fitted via scipy.optimize.curve_fit. When the fit does not converge, :attr:BoltzmannFit.converged is False and the parameter values are 0.0 and 1.0 respectively. The returned k is positive and the fit curve is reconstructed as boltzmann(V, v_half, -k).

Parameters:

Name Type Description Default
iv_result IVAnalysisResult

Pre-computed I-V analysis result whose stimulus window is the two-pulse protocol's fixed test pulse, with one point per conditioning prepulse voltage.

required

Returns:

Name Type Description
An InactivationAnalysisResult

class:InactivationAnalysisResult with sorted per-prepulse

InactivationAnalysisResult

availability records and Boltzmann fit parameters. points is empty

InactivationAnalysisResult

only when iv_result itself is empty.

Source code in neuroclamp/analysis/inactivation.py
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
def compute_inactivation(iv_result: IVAnalysisResult) -> InactivationAnalysisResult:
    """Compute normalized availability vs. prepulse voltage from I-V results.

    Each :class:`~neuroclamp.analysis.iv_curve.IVPoint` in *iv_result* is assumed
    to come from one sweep of a two-pulse inactivation protocol: its
    ``voltage_step`` is the conditioning prepulse voltage and its
    ``peak_inward_current`` is the most negative current measured during the
    fixed test pulse.  Availability is::

        h∞(V) = I_peak(V) / I_peak_max

    where ``I_peak_max`` is the most negative peak across all prepulses; the
    ratio is clamped to [0, 1] (a non-negative test-pulse peak — full
    inactivation, possibly net outward — maps to 0.0).

    A decreasing Boltzmann sigmoid ``h∞(V) = 1 / (1 + exp((V - v_half) / k))``
    is then fitted via ``scipy.optimize.curve_fit``.  When the fit does not
    converge, :attr:`BoltzmannFit.converged` is ``False`` and the parameter
    values are ``0.0`` and ``1.0`` respectively.  The returned ``k`` is positive
    and the fit curve is reconstructed as ``boltzmann(V, v_half, -k)``.

    Args:
        iv_result: Pre-computed I-V analysis result whose stimulus window is the
            two-pulse protocol's fixed test pulse, with one point per
            conditioning prepulse voltage.

    Returns:
        An :class:`InactivationAnalysisResult` with sorted per-prepulse
        availability records and Boltzmann fit parameters.  ``points`` is empty
        only when *iv_result* itself is empty.
    """
    # Sentinel returned on failure; parameter values are never exposed to the
    # user because all callers check BoltzmannFit.converged before using them.
    _null_fit = BoltzmannFit(v_half=0.0, k=1.0, converged=False)

    if not iv_result.points:
        return InactivationAnalysisResult(points=[], boltzmann=_null_fit)

    # iv_result.points is already sorted by voltage_step (analyze_iv sorts), but
    # sort defensively so the output ordering does not depend on the caller.
    ordered = sorted(iv_result.points, key=lambda p: p.voltage_step)
    voltages = [p.voltage_step for p in ordered]
    peaks = [p.peak_inward_current for p in ordered]

    i_max = min(peaks)  # most negative ⇒ largest available inward current
    if i_max >= 0.0:
        # No inward current at any prepulse — pathological (e.g. no Na+ channel
        # or test pulse below activation threshold).  Report zero availability.
        points = [
            InactivationPoint(
                prepulse_voltage=v, peak_inward_current=p, h_normalized=0.0
            )
            for v, p in zip(voltages, peaks)
        ]
        return InactivationAnalysisResult(points=points, boltzmann=_null_fit)

    h_norm = [min(1.0, max(0.0, p / i_max)) for p in peaks]
    points = [
        InactivationPoint(prepulse_voltage=v, peak_inward_current=p, h_normalized=hn)
        for v, p, hn in zip(voltages, peaks, h_norm)
    ]

    if len(points) < 2:
        return InactivationAnalysisResult(points=points, boltzmann=_null_fit)

    v_arr = np.array(voltages, dtype=float)
    h_arr = np.array(h_norm, dtype=float)

    fit = _null_fit
    try:
        popt, _ = curve_fit(
            _decreasing_boltzmann,
            v_arr,
            h_arr,
            p0=[_VHALF_GUESS, _K_GUESS],
            bounds=(
                [_VHALF_BOUNDS[0], _K_BOUNDS[0]],
                [_VHALF_BOUNDS[1], _K_BOUNDS[1]],
            ),
            maxfev=2000,
        )
        fit = BoltzmannFit(v_half=float(popt[0]), k=float(popt[1]), converged=True)
    except (RuntimeError, ValueError) as exc:
        logger.debug("Inactivation Boltzmann fit did not converge: %s", exc)

    return InactivationAnalysisResult(points=points, boltzmann=fit)

analyze_iv

analyze_iv(time, currents, voltage_steps, stim_start_ms, stim_end_ms)

Compute I-V curve from a multi-sweep voltage clamp simulation.

Calls :func:compute_iv_point for each sweep and assembles the results, sorted in ascending order of voltage step.

Parameters:

Name Type Description Default
time ndarray

Shared time axis in ms (same for all sweeps).

required
currents list[ndarray]

List of total ionic current arrays (µA/cm²), one per sweep.

required
voltage_steps list[float]

Command voltage (mV) for each sweep, parallel to currents.

required
stim_start_ms float

Start of the stimulus window in ms.

required
stim_end_ms float

End of the stimulus window in ms.

required

Returns:

Name Type Description
An IVAnalysisResult

class:IVAnalysisResult with per-step measurements sorted by

IVAnalysisResult

voltage.

Source code in neuroclamp/analysis/iv_curve.py
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
def analyze_iv(
    time: np.ndarray,
    currents: list[np.ndarray],
    voltage_steps: list[float],
    stim_start_ms: float,
    stim_end_ms: float,
) -> IVAnalysisResult:
    """Compute I-V curve from a multi-sweep voltage clamp simulation.

    Calls :func:`compute_iv_point` for each sweep and assembles the results,
    sorted in ascending order of voltage step.

    Args:
        time: Shared time axis in ms (same for all sweeps).
        currents: List of total ionic current arrays (µA/cm²), one per sweep.
        voltage_steps: Command voltage (mV) for each sweep, parallel to
            ``currents``.
        stim_start_ms: Start of the stimulus window in ms.
        stim_end_ms: End of the stimulus window in ms.

    Returns:
        An :class:`IVAnalysisResult` with per-step measurements sorted by
        voltage.
    """
    points = [
        compute_iv_point(time, current, v, stim_start_ms, stim_end_ms)
        for current, v in zip(currents, voltage_steps)
    ]
    points.sort(key=lambda p: p.voltage_step)
    return IVAnalysisResult(points=points)

compute_iv_point

compute_iv_point(time, current, voltage_step, stim_start_ms, stim_end_ms)

Compute I-V metrics for a single voltage step sweep.

The stimulus window is identified using the provided timing boundaries. Peak inward current is the minimum (most negative) value in the window; peak outward current is the maximum (most positive) value. Steady-state current is the mean of the last 10% of the stimulus window.

Parameters:

Name Type Description Default
time ndarray

Time axis array in ms.

required
current ndarray

Total ionic current array in µA/cm², same length as time.

required
voltage_step float

Command voltage applied during the step (mV).

required
stim_start_ms float

Start of the stimulus window in ms.

required
stim_end_ms float

End of the stimulus window in ms.

required

Returns:

Name Type Description
An IVPoint

class:IVPoint with peak inward, peak outward, and steady-state

IVPoint

current measurements for this voltage step.

Source code in neuroclamp/analysis/iv_curve.py
 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
def compute_iv_point(
    time: np.ndarray,
    current: np.ndarray,
    voltage_step: float,
    stim_start_ms: float,
    stim_end_ms: float,
) -> IVPoint:
    """Compute I-V metrics for a single voltage step sweep.

    The stimulus window is identified using the provided timing boundaries.
    Peak inward current is the minimum (most negative) value in the window;
    peak outward current is the maximum (most positive) value.  Steady-state
    current is the mean of the last 10% of the stimulus window.

    Args:
        time: Time axis array in ms.
        current: Total ionic current array in µA/cm², same length as ``time``.
        voltage_step: Command voltage applied during the step (mV).
        stim_start_ms: Start of the stimulus window in ms.
        stim_end_ms: End of the stimulus window in ms.

    Returns:
        An :class:`IVPoint` with peak inward, peak outward, and steady-state
        current measurements for this voltage step.
    """
    i_start = int(np.searchsorted(time, stim_start_ms))
    i_end = int(np.searchsorted(time, stim_end_ms))
    window = current[i_start:i_end]

    if len(window) == 0:
        return IVPoint(
            voltage_step=voltage_step,
            peak_inward_current=0.0,
            peak_outward_current=0.0,
            steady_state_current=0.0,
        )

    peak_inward = float(np.min(window))
    peak_outward = float(np.max(window))

    n_ss = max(1, len(window) // 10)
    steady_state = float(np.mean(window[-n_ss:]))

    return IVPoint(
        voltage_step=voltage_step,
        peak_inward_current=peak_inward,
        peak_outward_current=peak_outward,
        steady_state_current=steady_state,
    )

run_membrane_test

run_membrane_test(neuron)

Run a dedicated membrane test on the given neuron and extract passive properties.

Constructs a passive-only copy of the neuron — only ungated channels are retained, and v_rest is set to the leak equilibrium (E_L) — to simulate the equivalent of pharmacological channel block (TTX + TEA). This ensures the step response is a clean single exponential driven by the passive RC circuit, giving an accurate R_in, τ_m, and C_m rather than values contaminated by K⁺ channel deactivation sag.

Passive channels are identified by ch.gating_variables == (); their g_max (along with the neuron's C_m, ion concentrations, and temperature) is preserved so R_in = 1 / Σ g_max and C_m match the configured membrane parameters.

When neuron.area_cm2 is set, the returned :class:PassiveProperties carries absolute MΩ / pF counterparts alongside the per-area density values. When it is None, only density values are populated.

Parameters:

Name Type Description Default
neuron Neuron

A fully configured :class:~neuroclamp.neuron.Neuron instance. Only its ungated channels survive the passive copy; gated channels (Na, K, auxiliary) are blocked. neuron.area_cm2, if set, is forwarded to :func:analyze_passive_properties to populate absolute units.

required

Returns:

Name Type Description
A PassiveProperties | None

class:~neuroclamp.analysis.passive_properties.PassiveProperties

PassiveProperties | None

instance when extraction succeeds, or None when the analysis cannot

PassiveProperties | None

converge (should not occur for a pure RC circuit).

Source code in neuroclamp/analysis/membrane_test.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
def run_membrane_test(neuron: Neuron) -> PassiveProperties | None:
    """Run a dedicated membrane test on the given neuron and extract passive properties.

    Constructs a passive-only copy of the neuron — only ungated channels are
    retained, and ``v_rest`` is set to the leak equilibrium (E_L) — to simulate
    the equivalent of pharmacological channel block (TTX + TEA).  This ensures
    the step response is a clean single exponential driven by the passive RC
    circuit, giving an accurate R_in, τ_m, and C_m rather than values
    contaminated by K⁺ channel deactivation sag.

    Passive channels are identified by ``ch.gating_variables == ()``; their
    ``g_max`` (along with the neuron's ``C_m``, ion concentrations, and
    temperature) is preserved so R_in = 1 / Σ g_max and C_m match the
    configured membrane parameters.

    When ``neuron.area_cm2`` is set, the returned :class:`PassiveProperties`
    carries absolute MΩ / pF counterparts alongside the per-area density
    values.  When it is ``None``, only density values are populated.

    Args:
        neuron: A fully configured :class:`~neuroclamp.neuron.Neuron` instance.
            Only its ungated channels survive the passive copy; gated channels
            (Na, K, auxiliary) are blocked.  ``neuron.area_cm2``, if set, is
            forwarded to :func:`analyze_passive_properties` to populate
            absolute units.

    Returns:
        A :class:`~neuroclamp.analysis.passive_properties.PassiveProperties`
        instance when extraction succeeds, or ``None`` when the analysis cannot
        converge (should not occur for a pure RC circuit).
    """
    # Effective leak equilibrium: weighted average of each passive channel's
    # reversal potential.  This is the zero-current voltage of the passive
    # circuit: Σ g_max_i * (V - E_i) = 0  →  V = Σ g_max_i * E_i / Σ g_max_i.
    passive_channels = tuple(ch for ch in neuron.channels if not ch.gating_variables)
    g_total = sum(ch.g_max for ch in passive_channels)
    if g_total > 0:
        e_l = (
            sum(ch.g_max * ch.reversal_potential(neuron) for ch in passive_channels)
            / g_total
        )
    else:
        e_l = neuron.v_rest

    # Passive-only neuron: only ungated channels survive.  Equivalent to
    # pharmacological channel block in a real experiment — guarantees a pure RC
    # circuit regardless of which gated channels the original neuron carried.
    passive_neuron = dataclasses.replace(neuron, channels=passive_channels, v_rest=e_l)

    total_ms = MEMBRANE_TEST_PRE_MS + MEMBRANE_TEST_STEP_MS + MEMBRANE_TEST_POST_MS
    stimulus = step_current(
        duration=total_ms,
        current_amplitude=MEMBRANE_TEST_CURRENT,
        step_start=MEMBRANE_TEST_PRE_MS,
        step_duration=MEMBRANE_TEST_STEP_MS,
        sampling_frequency=SIM_SAMPLING_FREQ,
    )
    result = simulate_current_clamp(passive_neuron, stimulus)
    # Use an extended fit window (150 ms) because the passive-only simulation
    # has no gating-variable relaxations to distort the fit, and Purkinje
    # cells have τ_m ≈ 50 ms requiring ≥3×τ_m in the fit window.
    return analyze_passive_properties(
        result["time"],
        result["voltage"],
        current_amplitude=MEMBRANE_TEST_CURRENT,
        stim_start_ms=MEMBRANE_TEST_PRE_MS,
        stim_end_ms=MEMBRANE_TEST_PRE_MS + MEMBRANE_TEST_STEP_MS,
        max_fit_window_ms=150.0,
        area_cm2=neuron.area_cm2,
    )

analyze_passive_properties

analyze_passive_properties(time, voltage, current_amplitude, stim_start_ms, stim_end_ms, max_fit_window_ms=_MAX_FIT_WINDOW_MS, area_cm2=None)

Extract input resistance and membrane time constant from a CC step response.

Returns None when the sweep is suprathreshold (contains spikes) or when current_amplitude is zero (R_in cannot be computed). Also returns None when the stimulus duration is shorter than :data:_MIN_STIM_DURATION_MS.

R_in is computed as ΔV / ΔI where ΔV is the steady-state voltage deflection from baseline and ΔI is current_amplitude. The result is in kΩ·cm² (mV / µA·cm⁻²).

τₘ is obtained by fitting V(t) = V_ss + A·exp(-t/τ) to the rising (or falling) phase of the response using :func:scipy.optimize.curve_fit. If the fit fails, a fallback estimate based on the 63.2%-deflection crossing time is used and fit_converged is set to False.

Cₘ is derived as τₘ / R_in. When R_in is zero, membrane_capacitance is None.

Parameters:

Name Type Description Default
time ndarray

Time array in ms, shape (N,).

required
voltage ndarray

Membrane voltage in mV, shape (N,), same length as time.

required
current_amplitude float

Injected current step amplitude in µA/cm². Must be non-zero for a meaningful R_in estimate.

required
stim_start_ms float

Time at which the current step begins (ms).

required
stim_end_ms float

Time at which the current step ends (ms).

required
max_fit_window_ms float

Maximum duration of the exponential fit window in ms. Defaults to :data:_MAX_FIT_WINDOW_MS (25 ms). Pass a larger value (e.g. 150 ms) when the trace comes from a passive-only simulation where slow gating-variable relaxations are absent.

_MAX_FIT_WINDOW_MS
area_cm2 float | None

Optional membrane surface area in cm². When supplied, the returned :class:PassiveProperties carries absolute MΩ / pF counterparts in addition to the density values. When None (default), only density values are populated.

None

Returns:

Name Type Description
A PassiveProperties | None

class:PassiveProperties instance, or None when analysis is

PassiveProperties | None

not applicable.

Source code in neuroclamp/analysis/passive_properties.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def analyze_passive_properties(
    time: np.ndarray,
    voltage: np.ndarray,
    current_amplitude: float,
    stim_start_ms: float,
    stim_end_ms: float,
    max_fit_window_ms: float = _MAX_FIT_WINDOW_MS,
    area_cm2: float | None = None,
) -> PassiveProperties | None:
    """Extract input resistance and membrane time constant from a CC step response.

    Returns ``None`` when the sweep is suprathreshold (contains spikes) or when
    ``current_amplitude`` is zero (R_in cannot be computed).  Also returns
    ``None`` when the stimulus duration is shorter than
    :data:`_MIN_STIM_DURATION_MS`.

    R_in is computed as ΔV / ΔI where ΔV is the steady-state voltage
    deflection from baseline and ΔI is ``current_amplitude``.  The result is
    in kΩ·cm² (mV / µA·cm⁻²).

    τₘ is obtained by fitting ``V(t) = V_ss + A·exp(-t/τ)`` to the rising
    (or falling) phase of the response using
    :func:`scipy.optimize.curve_fit`.  If the fit fails, a fallback estimate
    based on the 63.2%-deflection crossing time is used and
    ``fit_converged`` is set to ``False``.

    Cₘ is derived as τₘ / R_in.  When R_in is zero, ``membrane_capacitance``
    is ``None``.

    Args:
        time: Time array in ms, shape ``(N,)``.
        voltage: Membrane voltage in mV, shape ``(N,)``, same length as
            ``time``.
        current_amplitude: Injected current step amplitude in µA/cm².  Must be
            non-zero for a meaningful R_in estimate.
        stim_start_ms: Time at which the current step begins (ms).
        stim_end_ms: Time at which the current step ends (ms).
        max_fit_window_ms: Maximum duration of the exponential fit window in ms.
            Defaults to :data:`_MAX_FIT_WINDOW_MS` (25 ms).  Pass a larger
            value (e.g. 150 ms) when the trace comes from a passive-only
            simulation where slow gating-variable relaxations are absent.
        area_cm2: Optional membrane surface area in cm².  When supplied, the
            returned :class:`PassiveProperties` carries absolute MΩ / pF
            counterparts in addition to the density values.  When ``None``
            (default), only density values are populated.

    Returns:
        A :class:`PassiveProperties` instance, or ``None`` when analysis is
        not applicable.
    """
    time = np.asarray(time, dtype=float)
    voltage = np.asarray(voltage, dtype=float)

    stim_duration = stim_end_ms - stim_start_ms
    if current_amplitude == 0.0 or stim_duration < _MIN_STIM_DURATION_MS:
        return None

    if not is_subthreshold(time, voltage):
        return None

    # --- Baseline voltage: mean of samples before the step ---
    pre_mask = time < stim_start_ms
    if not np.any(pre_mask):
        return None
    v_baseline = float(np.mean(voltage[pre_mask]))

    # --- Steady-state voltage: mean of last _SS_FRACTION of the step ---
    ss_start_ms = stim_end_ms - _SS_FRACTION * stim_duration
    ss_mask = (time >= ss_start_ms) & (time < stim_end_ms)
    if not np.any(ss_mask):
        return None
    v_ss = float(np.mean(voltage[ss_mask]))

    # --- Input resistance ---
    delta_v = v_ss - v_baseline  # mV
    r_in = delta_v / current_amplitude  # kΩ·cm²

    # --- Exponential fit for τₘ ---
    # Fit window: from stim_start to stim_start + _FIT_FRACTION * stim_duration,
    # capped at max_fit_window_ms so that slow gating-variable relaxations do
    # not distort the single-exponential fit of the fast capacitative transient.
    fit_end_ms = stim_start_ms + min(_FIT_FRACTION * stim_duration, max_fit_window_ms)
    fit_mask = (time >= stim_start_ms) & (time < fit_end_ms)
    if not np.any(fit_mask):
        return None

    t_fit = time[fit_mask] - stim_start_ms  # relative to step onset
    v_fit = voltage[fit_mask]

    a0 = v_baseline - v_ss  # initial amplitude estimate
    p0 = [v_ss, a0, _TAU_INITIAL_GUESS_MS]

    fit_converged = True
    try:
        popt, _ = curve_fit(
            _exponential_model,
            t_fit,
            v_fit,
            p0=p0,
            bounds=(
                [-np.inf, -np.inf, 1e-3],  # tau must be positive
                [np.inf, np.inf, np.inf],
            ),
            maxfev=5000,
        )
        tau_m = float(popt[2])
        if tau_m <= 0:
            raise RuntimeError("Non-positive tau from curve_fit")
    except (RuntimeError, ValueError) as exc:
        logger.debug("Passive property exponential fit failed: %s", exc)
        fit_converged = False
        tau_m = _fallback_tau(t_fit, v_fit, v_baseline, v_ss)

    # --- Membrane capacitance ---
    c_m: float | None = tau_m / r_in if r_in != 0.0 else None

    r_in_mohm = density_to_absolute_r_in(r_in, area_cm2)
    c_m_pf = density_to_absolute_c_m(c_m, area_cm2)

    return PassiveProperties(
        input_resistance=r_in,
        time_constant=tau_m,
        membrane_capacitance=c_m,
        fit_converged=fit_converged,
        input_resistance_mohm=r_in_mohm,
        membrane_capacitance_pf=c_m_pf,
        area_cm2=area_cm2,
    )

density_to_absolute_c_m

density_to_absolute_c_m(c_m_uf_cm2, area_cm2)

Convert per-area membrane capacitance (µF/cm²) to absolute pF.

Derivation: C [pF] = C_m [µF/cm²] × area [cm²] × 1e6.

Parameters:

Name Type Description Default
c_m_uf_cm2 float | None

Per-area membrane capacitance in µF/cm². None returns None.

required
area_cm2 float | None

Total membrane surface area in cm². None or non-positive returns None.

required

Returns:

Type Description
float | None

Absolute capacitance in pF, or None when either input is None

float | None

or area_cm2 is not strictly positive.

Source code in neuroclamp/analysis/passive_properties.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def density_to_absolute_c_m(
    c_m_uf_cm2: float | None,
    area_cm2: float | None,
) -> float | None:
    """Convert per-area membrane capacitance (µF/cm²) to absolute pF.

    Derivation: ``C [pF] = C_m [µF/cm²] × area [cm²] × 1e6``.

    Args:
        c_m_uf_cm2: Per-area membrane capacitance in µF/cm².  ``None`` returns
            ``None``.
        area_cm2: Total membrane surface area in cm².  ``None`` or
            non-positive returns ``None``.

    Returns:
        Absolute capacitance in pF, or ``None`` when either input is ``None``
        or ``area_cm2`` is not strictly positive.
    """
    if c_m_uf_cm2 is None or area_cm2 is None or area_cm2 <= 0:
        return None
    return c_m_uf_cm2 * area_cm2 * 1e6

density_to_absolute_r_in

density_to_absolute_r_in(input_resistance_kohm_cm2, area_cm2)

Convert per-area input resistance (kΩ·cm²) to absolute MΩ.

Derivation: R_in [kΩ·cm²] / area [cm²] = R_n [kΩ] = R_n [MΩ] × 1000, so R_n [MΩ] = R_in / area / 1000.

Parameters:

Name Type Description Default
input_resistance_kohm_cm2 float

Per-area input resistance in kΩ·cm².

required
area_cm2 float | None

Total membrane surface area in cm². None or non-positive returns None.

required

Returns:

Type Description
float | None

Absolute input resistance in MΩ, or None when area_cm2 is

float | None

None or not strictly positive.

Source code in neuroclamp/analysis/passive_properties.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def density_to_absolute_r_in(
    input_resistance_kohm_cm2: float,
    area_cm2: float | None,
) -> float | None:
    """Convert per-area input resistance (kΩ·cm²) to absolute MΩ.

    Derivation: ``R_in [kΩ·cm²] / area [cm²] = R_n [kΩ] = R_n [MΩ] × 1000``,
    so ``R_n [MΩ] = R_in / area / 1000``.

    Args:
        input_resistance_kohm_cm2: Per-area input resistance in kΩ·cm².
        area_cm2: Total membrane surface area in cm².  ``None`` or
            non-positive returns ``None``.

    Returns:
        Absolute input resistance in MΩ, or ``None`` when ``area_cm2`` is
        ``None`` or not strictly positive.
    """
    if area_cm2 is None or area_cm2 <= 0:
        return None
    return input_resistance_kohm_cm2 / area_cm2 / 1000.0

is_subthreshold

is_subthreshold(time, voltage, dvdt_threshold=20.0, min_spike_height=-20.0)

Return True when a voltage trace contains no detected action potentials.

Parameters:

Name Type Description Default
time ndarray

Time array in ms, shape (N,).

required
voltage ndarray

Membrane voltage in mV, shape (N,), same length as time.

required
dvdt_threshold float

dV/dt value (mV/ms) used to identify spike onset.

20.0
min_spike_height float

Minimum peak voltage (mV) for a candidate event to be classified as a spike.

-20.0

Returns:

Type Description
bool

True if no spikes are detected, False otherwise.

Source code in neuroclamp/analysis/passive_properties.py
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
def is_subthreshold(
    time: np.ndarray,
    voltage: np.ndarray,
    dvdt_threshold: float = 20.0,
    min_spike_height: float = -20.0,
) -> bool:
    """Return ``True`` when a voltage trace contains no detected action potentials.

    Args:
        time: Time array in ms, shape ``(N,)``.
        voltage: Membrane voltage in mV, shape ``(N,)``, same length as
            ``time``.
        dvdt_threshold: dV/dt value (mV/ms) used to identify spike onset.
        min_spike_height: Minimum peak voltage (mV) for a candidate event to
            be classified as a spike.

    Returns:
        ``True`` if no spikes are detected, ``False`` otherwise.
    """
    result = analyze_aps(
        time,
        voltage,
        dvdt_threshold=dvdt_threshold,
        min_spike_height=min_spike_height,
    )
    return result.spike_count == 0

longest_subthreshold_run

longest_subthreshold_run(time, voltage, *, dvdt_threshold=20.0, min_spike_height=-20.0)

Find the longest contiguous spike-free span of a voltage trace.

Runs :func:analyze_aps to locate spikes, excises a guard-padded window around each one — from :data:_SPIKE_GUARD_PRE_MS before its threshold crossing to :data:_SPIKE_GUARD_POST_MS after its peak, so the after-hyperpolarization transient is removed too — and returns the widest remaining gap. When the trace contains no spikes the whole trace is returned.

Parameters:

Name Type Description Default
time ndarray

Time array in ms, shape (N,), ascending.

required
voltage ndarray

Membrane voltage in mV, shape (N,), same length as time.

required
dvdt_threshold float

dV/dt value (mV/ms) used to identify spike onset.

20.0
min_spike_height float

Minimum peak voltage (mV) for a candidate event to be classified as a spike.

-20.0

Returns:

Type Description
tuple[int, int] | None

Half-open index bounds (start_idx, stop_idx) into time /

tuple[int, int] | None

voltage of the longest spike-free span ((0, N) when there are no

tuple[int, int] | None

spikes), or None when no spike-free span exists — every sample falls

tuple[int, int] | None

inside a guard window.

Source code in neuroclamp/analysis/passive_properties.py
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def longest_subthreshold_run(
    time: np.ndarray,
    voltage: np.ndarray,
    *,
    dvdt_threshold: float = 20.0,
    min_spike_height: float = -20.0,
) -> tuple[int, int] | None:
    """Find the longest contiguous spike-free span of a voltage trace.

    Runs :func:`analyze_aps` to locate spikes, excises a guard-padded window
    around each one — from :data:`_SPIKE_GUARD_PRE_MS` before its threshold
    crossing to :data:`_SPIKE_GUARD_POST_MS` after its peak, so the
    after-hyperpolarization transient is removed too — and returns the widest
    remaining gap.  When the trace contains no spikes the whole trace is
    returned.

    Args:
        time: Time array in ms, shape ``(N,)``, ascending.
        voltage: Membrane voltage in mV, shape ``(N,)``, same length as
            ``time``.
        dvdt_threshold: dV/dt value (mV/ms) used to identify spike onset.
        min_spike_height: Minimum peak voltage (mV) for a candidate event to be
            classified as a spike.

    Returns:
        Half-open index bounds ``(start_idx, stop_idx)`` into ``time`` /
        ``voltage`` of the longest spike-free span (``(0, N)`` when there are no
        spikes), or ``None`` when no spike-free span exists — every sample falls
        inside a guard window.
    """
    time = np.asarray(time, dtype=float)
    voltage = np.asarray(voltage, dtype=float)
    n = time.size
    if n == 0:
        return None

    result = analyze_aps(
        time,
        voltage,
        dvdt_threshold=dvdt_threshold,
        min_spike_height=min_spike_height,
    )
    if result.spike_count == 0:
        return (0, n)

    # Merge the guard-padded "bad" time intervals around each spike.
    intervals = sorted(
        (s.threshold_time - _SPIKE_GUARD_PRE_MS, s.peak_time + _SPIKE_GUARD_POST_MS)
        for s in result.spikes
    )
    merged: list[list[float]] = [list(intervals[0])]
    for lo, hi in intervals[1:]:
        if lo <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], hi)
        else:
            merged.append([lo, hi])

    # Spike-free time gaps: before the first interval, between consecutive
    # intervals, and after the last interval.
    gaps: list[tuple[float, float]] = [(float(time[0]), merged[0][0])]
    for idx in range(len(merged) - 1):
        gaps.append((merged[idx][1], merged[idx + 1][0]))
    gaps.append((merged[-1][1], float(time[-1])))

    best: tuple[int, int] | None = None
    best_span = 0.0
    for gap_start, gap_end in gaps:
        if gap_end <= gap_start:
            continue
        start_idx = int(np.searchsorted(time, gap_start, side="left"))
        stop_idx = int(np.searchsorted(time, gap_end, side="right"))
        if stop_idx - start_idx < 2:
            continue
        span = float(time[stop_idx - 1] - time[start_idx])
        if span > best_span:
            best_span = span
            best = (start_idx, stop_idx)
    return best

analyze_sfa

analyze_sfa(ap_results, labels=None)

Compute spike-frequency adaptation curves for multiple sweeps.

Calls :func:compute_sfa for each sweep and collects the non-None results. Sweeps with fewer than two spikes are silently excluded.

Parameters:

Name Type Description Default
ap_results list[APAnalysisResult]

List of AP analysis results, one per sweep.

required
labels list[str] | None

Optional parallel list of display labels, aligned with ap_results. Defaults to empty strings for all sweeps.

None

Returns:

Name Type Description
An SFAAnalysisResult

class:SFAAnalysisResult whose curves list contains one

SFAAnalysisResult

entry per sweep that had at least two spikes.

Source code in neuroclamp/analysis/sfa.py
 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
def analyze_sfa(
    ap_results: list[APAnalysisResult],
    labels: list[str] | None = None,
) -> SFAAnalysisResult:
    """Compute spike-frequency adaptation curves for multiple sweeps.

    Calls :func:`compute_sfa` for each sweep and collects the non-``None``
    results.  Sweeps with fewer than two spikes are silently excluded.

    Args:
        ap_results: List of AP analysis results, one per sweep.
        labels: Optional parallel list of display labels, aligned with
            ``ap_results``.  Defaults to empty strings for all sweeps.

    Returns:
        An :class:`SFAAnalysisResult` whose ``curves`` list contains one
        entry per sweep that had at least two spikes.
    """
    if labels is None:
        labels = [""] * len(ap_results)

    curves: list[SFACurve] = []
    for ap_result, label in zip(ap_results, labels):
        curve = compute_sfa(ap_result, label=label)
        if curve is not None:
            curves.append(curve)

    return SFAAnalysisResult(curves=curves)

compute_sfa

compute_sfa(ap_result, label='')

Compute an instantaneous-frequency curve from a pre-computed AP analysis.

Reuses ap_result.isis directly; no additional spike detection is run. Returns None when fewer than two spikes were detected (zero ISIs).

Parameters:

Name Type Description Default
ap_result APAnalysisResult

AP analysis result whose isis field is populated.

required
label str

Display label for multi-sweep overlay (e.g. current step). Defaults to an empty string.

''

Returns:

Name Type Description
An SFACurve | None

class:SFACurve, or None when ap_result.isis is empty.

Source code in neuroclamp/analysis/sfa.py
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
def compute_sfa(ap_result: APAnalysisResult, label: str = "") -> SFACurve | None:
    """Compute an instantaneous-frequency curve from a pre-computed AP analysis.

    Reuses ``ap_result.isis`` directly; no additional spike detection is run.
    Returns ``None`` when fewer than two spikes were detected (zero ISIs).

    Args:
        ap_result: AP analysis result whose ``isis`` field is populated.
        label: Display label for multi-sweep overlay (e.g. current step).
            Defaults to an empty string.

    Returns:
        An :class:`SFACurve`, or ``None`` when ``ap_result.isis`` is empty.
    """
    if not ap_result.isis:
        return None

    inst_freqs = [1000.0 / isi for isi in ap_result.isis]
    spike_indices = list(range(len(inst_freqs)))
    f_first = inst_freqs[0]
    f_last = inst_freqs[-1]
    adaptation_index = (f_first - f_last) / f_first if f_first != 0.0 else 0.0

    return SFACurve(
        spike_indices=spike_indices,
        instantaneous_frequencies=inst_freqs,
        adaptation_index=adaptation_index,
        label=label,
    )

analyze_tau_v

analyze_tau_v(time, currents, voltage_steps, stim_start_ms, stim_end_ms, *, fit_inactivation=True)

Compute τ-V from a multi-sweep voltage clamp simulation.

Calls :func:compute_tau_v_point for each sweep and assembles the points sorted in ascending order of voltage step. Failed individual fits do not raise; they surface as None τ values on their respective :class:TauVPoint.

Caveat — total-current vs. isolated-channel kinetics: When currents is the total membrane current (rather than an isolated channel current obtained via, e.g. TTX subtraction), the recovered τ values reflect the dominant channel at each voltage. At strong depolarizations of an HH-style neuron the total current is dominated by the much larger sustained K⁺ outward current, which masks the brief inward Na⁺ inactivation; the τ_inactivation values at those voltages should not be interpreted as the isolated Na⁺ inactivation time constant. For unambiguous channel-specific kinetics, run this analysis on a pharmacologically isolated current.

Parameters:

Name Type Description Default
time ndarray

Shared time axis in ms (same for all sweeps).

required
currents list[ndarray]

List of total ionic current arrays (µA/cm²), one per sweep.

required
voltage_steps list[float]

Command voltage (mV) for each sweep, parallel to currents.

required
stim_start_ms float

Start of the stimulus window in ms.

required
stim_end_ms float

End of the stimulus window in ms.

required
fit_inactivation bool

When False, skip every inactivation fit.

True

Returns:

Name Type Description
A TauVAnalysisResult

class:TauVAnalysisResult with per-step τ values sorted by

TauVAnalysisResult

voltage.

Source code in neuroclamp/analysis/tau_v.py
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
def analyze_tau_v(
    time: np.ndarray,
    currents: list[np.ndarray],
    voltage_steps: list[float],
    stim_start_ms: float,
    stim_end_ms: float,
    *,
    fit_inactivation: bool = True,
) -> TauVAnalysisResult:
    """Compute τ-V from a multi-sweep voltage clamp simulation.

    Calls :func:`compute_tau_v_point` for each sweep and assembles the points
    sorted in ascending order of voltage step.  Failed individual fits do
    not raise; they surface as ``None`` τ values on their respective
    :class:`TauVPoint`.

    Caveat — total-current vs. isolated-channel kinetics:
        When ``currents`` is the total membrane current (rather than an
        isolated channel current obtained via, e.g. TTX subtraction), the
        recovered τ values reflect the dominant channel at each voltage.
        At strong depolarizations of an HH-style neuron the total current is
        dominated by the much larger sustained K⁺ outward current, which
        masks the brief inward Na⁺ inactivation; the τ_inactivation values
        at those voltages should not be interpreted as the isolated Na⁺
        inactivation time constant.  For unambiguous channel-specific
        kinetics, run this analysis on a pharmacologically isolated current.

    Args:
        time: Shared time axis in ms (same for all sweeps).
        currents: List of total ionic current arrays (µA/cm²), one per sweep.
        voltage_steps: Command voltage (mV) for each sweep, parallel to
            ``currents``.
        stim_start_ms: Start of the stimulus window in ms.
        stim_end_ms: End of the stimulus window in ms.
        fit_inactivation: When ``False``, skip every inactivation fit.

    Returns:
        A :class:`TauVAnalysisResult` with per-step τ values sorted by
        voltage.
    """
    points = [
        compute_tau_v_point(
            time,
            current,
            v,
            stim_start_ms,
            stim_end_ms,
            fit_inactivation=fit_inactivation,
        )
        for current, v in zip(currents, voltage_steps)
    ]
    points.sort(key=lambda p: p.voltage_step)
    return TauVAnalysisResult(points=points)

compute_tau_v_point

compute_tau_v_point(time, current, voltage_step, stim_start_ms, stim_end_ms, *, fit_inactivation=True)

Fit activation and inactivation exponentials for one voltage-clamp sweep.

The stimulus window is split at the absolute-value peak of the current. The rising segment (start → peak) is fit with :func:single_exp_rise to extract τ_activation; the decaying segment (peak → end) is fit with :func:single_exp_decay and, when fit_inactivation is True, also with :func:double_exp_decay. The double-exponential fit is preferred only when

  1. its residual sum of squares improves on the single-exponential fit by at least :data:_DOUBLE_FIT_IMPROVEMENT (10%), and
  2. its two τ values differ by at least :data:_DOUBLE_TAU_RATIO (a factor of 3),

so that a marginal second component does not displace the simpler model.

Failed or skipped fits surface as None τ values; this function never raises on bad data.

Parameters:

Name Type Description Default
time ndarray

Shared time axis in ms (full sweep, not just the step window).

required
current ndarray

Total ionic current array in µA/cm², same length as time.

required
voltage_step float

Command voltage applied during the step (mV).

required
stim_start_ms float

Start of the stimulus window in ms.

required
stim_end_ms float

End of the stimulus window in ms.

required
fit_inactivation bool

When False, skip the inactivation fit entirely and report tau_inactivation_ms=None.

True

Returns:

Name Type Description
A TauVPoint

class:TauVPoint with the activation and (optional) inactivation

TauVPoint

time constants for this step.

Source code in neuroclamp/analysis/tau_v.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def compute_tau_v_point(
    time: np.ndarray,
    current: np.ndarray,
    voltage_step: float,
    stim_start_ms: float,
    stim_end_ms: float,
    *,
    fit_inactivation: bool = True,
) -> TauVPoint:
    """Fit activation and inactivation exponentials for one voltage-clamp sweep.

    The stimulus window is split at the absolute-value peak of the current.
    The rising segment (start → peak) is fit with :func:`single_exp_rise` to
    extract τ_activation; the decaying segment (peak → end) is fit with
    :func:`single_exp_decay` and, when ``fit_inactivation`` is ``True``, also
    with :func:`double_exp_decay`.  The double-exponential fit is preferred
    only when

    1. its residual sum of squares improves on the single-exponential fit by
       at least :data:`_DOUBLE_FIT_IMPROVEMENT` (10%), and
    2. its two τ values differ by at least :data:`_DOUBLE_TAU_RATIO`
       (a factor of 3),

    so that a marginal second component does not displace the simpler model.

    Failed or skipped fits surface as ``None`` τ values; this function never
    raises on bad data.

    Args:
        time: Shared time axis in ms (full sweep, not just the step window).
        current: Total ionic current array in µA/cm², same length as ``time``.
        voltage_step: Command voltage applied during the step (mV).
        stim_start_ms: Start of the stimulus window in ms.
        stim_end_ms: End of the stimulus window in ms.
        fit_inactivation: When ``False``, skip the inactivation fit entirely
            and report ``tau_inactivation_ms=None``.

    Returns:
        A :class:`TauVPoint` with the activation and (optional) inactivation
        time constants for this step.
    """
    t_win, i_win = _slice_step_window(time, current, stim_start_ms, stim_end_ms)
    stim_duration = stim_end_ms - stim_start_ms

    if i_win.size < _MIN_FIT_POINTS or stim_duration <= 0.0:
        return TauVPoint(
            voltage_step=voltage_step,
            tau_activation_ms=None,
            tau_inactivation_ms=None,
            tau_inactivation_slow_ms=None,
            activation_converged=False,
            inactivation_converged=False,
            inactivation_is_double=False,
        )

    peak_idx = _peak_index_in_window(i_win)
    t_act = t_win[: peak_idx + 1]
    i_act = i_win[: peak_idx + 1]
    t_inact = t_win[peak_idx:] - t_win[peak_idx]
    i_inact = i_win[peak_idx:]

    tau_max = stim_duration * _TAU_CEILING_FRACTION
    # τ values that converge near a bound are typically curve_fit hitting
    # the corner of the search space rather than locating a real time
    # constant; treat them as failed fits.
    tau_lo_reject = _TAU_FLOOR_MS * (1.0 + _TAU_BOUND_REJECT_FRACTION)
    tau_hi_reject = tau_max * (1.0 - _TAU_BOUND_REJECT_FRACTION)

    def _tau_is_bound_pinned(tau: float) -> bool:
        """Return True when ``tau`` lies near either fitting bound."""
        return tau <= tau_lo_reject or tau >= tau_hi_reject

    # ---- activation fit ------------------------------------------------ #
    tau_act: float | None = None
    activation_converged = False
    if t_act.size >= _MIN_FIT_POINTS:
        peak_value = float(i_act[-1])
        baseline = float(i_act[0])
        amp = peak_value - baseline
        # Allow either sign of amplitude; bounds are symmetric around zero
        # to handle both inward and outward currents.
        amp_abs = max(abs(amp), 1e-6)
        a_lo, a_hi = -10.0 * amp_abs, 10.0 * amp_abs
        c_lo, c_hi = baseline - 10.0 * amp_abs, baseline + 10.0 * amp_abs
        # ensure p0 is strictly inside bounds
        amp_seed = float(np.clip(amp, a_lo + 1e-9, a_hi - 1e-9))
        tau_seed = max(_TAU_FLOOR_MS * 10.0, min(stim_duration / 5.0, tau_max / 2.0))
        offset_seed = float(np.clip(baseline, c_lo + 1e-9, c_hi - 1e-9))
        p0 = [amp_seed, tau_seed, offset_seed]
        bounds = ([a_lo, _TAU_FLOOR_MS, c_lo], [a_hi, tau_max, c_hi])
        fit = _fit_single_exp(single_exp_rise, t_act, i_act, p0, bounds)
        if fit.converged and not _tau_is_bound_pinned(fit.tau_ms):
            tau_act = fit.tau_ms
            activation_converged = True

    # ---- inactivation fit ---------------------------------------------- #
    tau_inact: float | None = None
    tau_inact_slow: float | None = None
    inactivation_converged = False
    is_double = False

    if fit_inactivation and t_inact.size >= _MIN_FIT_POINTS:
        peak_value = float(i_inact[0])
        end_value = float(i_inact[-1])
        peak_abs = abs(peak_value)
        end_abs = abs(end_value)
        if peak_abs > 0.0 and end_abs <= _INACTIVATION_PEAK_FRACTION * peak_abs:
            amp = peak_value - end_value
            amp_abs = max(abs(amp), 1e-6)
            a_lo, a_hi = -10.0 * amp_abs, 10.0 * amp_abs
            c_lo, c_hi = end_value - 10.0 * amp_abs, end_value + 10.0 * amp_abs
            amp_seed = float(np.clip(amp, a_lo + 1e-9, a_hi - 1e-9))
            tau_seed = max(
                _TAU_FLOOR_MS * 10.0, min(stim_duration / 5.0, tau_max / 2.0)
            )
            offset_seed = float(np.clip(end_value, c_lo + 1e-9, c_hi - 1e-9))
            p0 = [amp_seed, tau_seed, offset_seed]
            bounds = ([a_lo, _TAU_FLOOR_MS, c_lo], [a_hi, tau_max, c_hi])
            single_fit = _fit_single_exp(single_exp_decay, t_inact, i_inact, p0, bounds)

            if single_fit.converged and not _tau_is_bound_pinned(single_fit.tau_ms):
                tau_inact = single_fit.tau_ms
                inactivation_converged = True

                # Try double-exp; accept only if it clearly improves the fit
                # and the two τ values are distinct.
                tau_fast_seed = max(_TAU_FLOOR_MS * 10.0, single_fit.tau_ms / 3.0)
                tau_slow_seed = min(tau_max / 2.0, single_fit.tau_ms * 3.0)
                if tau_slow_seed <= tau_fast_seed:
                    tau_slow_seed = min(tau_max / 2.0, tau_fast_seed * 3.0)
                p0_d = [
                    amp_seed * 0.5,
                    tau_fast_seed,
                    amp_seed * 0.5,
                    tau_slow_seed,
                    offset_seed,
                ]
                bounds_d = (
                    [a_lo, _TAU_FLOOR_MS, a_lo, _TAU_FLOOR_MS, c_lo],
                    [a_hi, tau_max, a_hi, tau_max, c_hi],
                )
                double_fit = _fit_double_exp_decay(t_inact, i_inact, p0_d, bounds_d)
                if double_fit.converged and single_fit.rss > 0.0:
                    rss_drop = (single_fit.rss - double_fit.rss) / single_fit.rss
                    tau_fast = double_fit.tau_fast_ms
                    tau_slow = double_fit.tau_slow_ms
                    if (
                        rss_drop >= _DOUBLE_FIT_IMPROVEMENT
                        and not _tau_is_bound_pinned(tau_fast)
                        and not _tau_is_bound_pinned(tau_slow)
                        and tau_fast > 0.0
                        and tau_slow / tau_fast >= _DOUBLE_TAU_RATIO
                    ):
                        tau_inact = tau_fast
                        tau_inact_slow = tau_slow
                        is_double = True

    return TauVPoint(
        voltage_step=voltage_step,
        tau_activation_ms=tau_act,
        tau_inactivation_ms=tau_inact,
        tau_inactivation_slow_ms=tau_inact_slow,
        activation_converged=activation_converged,
        inactivation_converged=inactivation_converged,
        inactivation_is_double=is_double,
    )

double_exp_decay

double_exp_decay(t, A1, tau1, A2, tau2, C)

Evaluate a two-exponential decay toward an asymptote.

Computes A1 * exp(-t / tau1) + A2 * exp(-t / tau2) + C. Used to capture inactivation processes with two distinct kinetic components (e.g. a fast and a slow inactivation gate).

Parameters:

Name Type Description Default
t float | ndarray

Time in ms (scalar or 1-D array).

required
A1 float

First component amplitude.

required
tau1 float

First component time constant (ms).

required
A2 float

Second component amplitude.

required
tau2 float

Second component time constant (ms).

required
C float

Asymptote.

required

Returns:

Type Description
float | ndarray

The model evaluated at t.

Source code in neuroclamp/analysis/tau_v.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def double_exp_decay(
    t: float | np.ndarray,
    A1: float,
    tau1: float,
    A2: float,
    tau2: float,
    C: float,
) -> float | np.ndarray:
    """Evaluate a two-exponential decay toward an asymptote.

    Computes ``A1 * exp(-t / tau1) + A2 * exp(-t / tau2) + C``.  Used to
    capture inactivation processes with two distinct kinetic components
    (e.g. a fast and a slow inactivation gate).

    Args:
        t: Time in ms (scalar or 1-D array).
        A1: First component amplitude.
        tau1: First component time constant (ms).
        A2: Second component amplitude.
        tau2: Second component time constant (ms).
        C: Asymptote.

    Returns:
        The model evaluated at ``t``.
    """
    return A1 * np.exp(-t / tau1) + A2 * np.exp(-t / tau2) + C

single_exp_decay

single_exp_decay(t, A, tau, C)

Evaluate a single-exponential decay toward an asymptote.

Computes A * exp(-t / tau) + C.

Parameters:

Name Type Description Default
t float | ndarray

Time in ms (scalar or 1-D array, with t = 0 at the start of the decaying phase).

required
A float

Initial amplitude above the asymptote.

required
tau float

Inactivation time constant (ms).

required
C float

Asymptote that the trace approaches.

required

Returns:

Type Description
float | ndarray

The model evaluated at t.

Source code in neuroclamp/analysis/tau_v.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def single_exp_decay(
    t: float | np.ndarray,
    A: float,
    tau: float,
    C: float,
) -> float | np.ndarray:
    """Evaluate a single-exponential decay toward an asymptote.

    Computes ``A * exp(-t / tau) + C``.

    Args:
        t: Time in ms (scalar or 1-D array, with ``t = 0`` at the start of
            the decaying phase).
        A: Initial amplitude above the asymptote.
        tau: Inactivation time constant (ms).
        C: Asymptote that the trace approaches.

    Returns:
        The model evaluated at ``t``.
    """
    return A * np.exp(-t / tau) + C

single_exp_rise

single_exp_rise(t, A, tau, C)

Evaluate a single-exponential rise to a plateau.

Computes A * (1 - exp(-t / tau)) + C.

Parameters:

Name Type Description Default
t float | ndarray

Time in ms (scalar or 1-D array, with t = 0 at the start of the rising phase).

required
A float

Plateau amplitude.

required
tau float

Activation time constant (ms).

required
C float

Baseline / starting offset.

required

Returns:

Type Description
float | ndarray

The model evaluated at t.

Source code in neuroclamp/analysis/tau_v.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def single_exp_rise(
    t: float | np.ndarray,
    A: float,
    tau: float,
    C: float,
) -> float | np.ndarray:
    """Evaluate a single-exponential rise to a plateau.

    Computes ``A * (1 - exp(-t / tau)) + C``.

    Args:
        t: Time in ms (scalar or 1-D array, with ``t = 0`` at the start of
            the rising phase).
        A: Plateau amplitude.
        tau: Activation time constant (ms).
        C: Baseline / starting offset.

    Returns:
        The model evaluated at ``t``.
    """
    return A * (1.0 - np.exp(-t / tau)) + C