Model measurements and descriptors#
dendra.models.analysis contains hard measurement functions and
graph-connected macroscopic descriptors. The training guide explains how to
choose a protocol, build a loss, update model parameters, and rerun the hard
measurement after each proposal: Training with differentiable macroscopic descriptors.
Supported trace descriptors#
These interfaces take a voltage tensor from any Dendra model. Their forward values use the matching hard event choices; their gradients follow the linearly interpolated crossings on the branch selected in the current replay.
- branch_conditioned_conduction_velocity(V, lengths_um, dt_ms, node_mask=None, *, V_th=0.0, dv_th=None, time_window=None, time_window_ms=None, interpolate=True, eps=1e-12)[source]#
Return hard conduction velocity with selected-crossing derivatives.
The arguments and measurement fields match
hard_conduction_velocity.Vhas shape (T, F, C), andlengths_umis scalar, (C,), or (F, C). Compartment midpoint positions are regressed on the first upward crossing times at the selected sites. A (C,) or (F, C)node_maskselects sites by nonzero entries, rather than supplying continuous regression weights.time_windowselects sample indices;time_window_msincludes roots on both boundaries. Pass only one window type.Discrete crossing pairs, spike presence, and site inclusion are selected without tracking gradients. The chosen roots are then linearly interpolated using graph-connected voltage endpoints, and the same spatial regression supplies the local derivative. The forward values are exactly the matching hard values, including NaN for invalid measurements.
epsis a minimum time variance in ms squared, not an offset in the regression denominator.In addition to all hard measurement fields, returns
velocity_validwith shape (F,),branch_signaturewith (F, C) integer fields, andbranch_matches_hardwith shape (F, C). The signature records crossing pairs (or -1 for absence), crossing presence, site inclusion, velocity validity, and velocity sign. The match diagnostic compares the selected roots and unanchored fit against the hard measurement.The derivative describes an existing propagated spike. It does not provide a direction for creating missing spikes or differentiating event identity switches. Recompute after every parameter update; a pair moving to an adjacent sample can still represent the same continuous physical event. With
interpolate=False, voltage timing derivatives are zero. Speed followsabs(v)and has its ordinary derivative at nonzero velocity.Example:
out = branch_conditioned_conduction_velocity( V, lengths_um, dt_ms, node_mask=node_mask, time_window_ms=(1.0, 8.0), ) loss = (out["v_m_per_s"][out["velocity_valid"]] - target).square().mean() loss.backward()
- differentiable_action_potential_width(V, dt_ms, node_mask=None, *, V_spk=0.0, dv_th=None, mode='half_height', baseline_pre_ms=1.0, baseline_guard_ms=0.15, baseline_mean_mode='sampled', peak_pre_ms=0.2, peak_post_ms=1.5, trough_pre_ms=0.3, trough_post_ms=3.0, width_pre_ms=1.0, width_post_ms=3.0, half_level=0.5, baseline_margin_mV=1.0, full_width_pre_ms=None, full_width_post_ms=8.0, amp_min_mV=5.0)#
AP widths with exact hard forward values and stable-branch derivatives.
The branch signature records the arrival crossing, baseline and peak windows, selected peak/trough, and rising/falling crossing pairs.
-1marks an absent choice. A fall or risekindof one marks a boundary substitution because the required crossing was not observed inside the measurement window. The caller selects the recording duration and search windows to contain the required events for the recording sites and stimulation protocol. Extending the recording alone does not extendwidth_post_msorfull_width_post_ms; their return searches must also contain the falling crossings. Inbaseline_mean_mode="continuous_time",baseline_start/endare-2because the baseline has no discrete sample-window branch; separatebaseline_start_clipped,baseline_end_clipped, andbaseline_emptyflags retain the genuine boundary/validity states.arrival_pairand rise/fall pairs identify interpolation segments, not persistent spike identities: a one-sample pair change may be benign when crossing time is continuous. Peak-window bounds can change without changing the selected peak, but can also admit a competing peak. Validity, boundary substitution, and selected-peak changes require closer inspection of the actual voltage event before declaring a stable derivative.
- differentiable_activity_dependent_slowing(V, pulse_times_ms, dt_ms, *, lengths_um=None, node_mask=None, response_window_ms=(0.1, 10.0), V_th=0.0, dv_th=10.0, baseline_pulse_indices=None, baseline_n_pulses=1, reference_latency_ms=None, reference_velocity_m_per_s=None, tail_n_pulses=10, interpolate=True, eps=1e-12, eps_time_ms2=None, eps_latency_ms=None, eps_velocity_m_per_s=None, window_margin_ms=None)#
Return hard ADS values with selected-crossing derivatives.
Spike presence, first-crossing interval, selected sites, earliest site, and baseline/tail inclusion are discrete choices. The derivative is meaningful only while these signatures remain fixed.
interpolate=Falsecorrectly gives zero voltage derivative of sampled crossing times.ads_percentis the percentage latency increase relative to baseline, so positive values mean slower arrival. Whenlengths_umis supplied,velocity_change_percentis the signed percentage change in propagation velocity and is therefore negative for slowing;velocity_slowing_percentis its sign-reversed, positive-for-slowing counterpart.eps_time_ms2regularizes the arrival-time variance in the velocity regression,eps_latency_msregularizes the latency normalization, andeps_velocity_m_per_sregularizes the velocity normalization. Omitted values fall back independently to the legacyepsargument, preserving existing calls and default forward values.
- differentiable_spike_timing(V, dt_ms, node_mask=None, *, V_spk=0.0, use_dv_gate=False, dv_spk=10.0, time_window=None, time_window_ms=None, refractory_ms=0.0, aggregate='mean')#
Return differentiable spike times and a span-based frequency.
The event times are linearly interpolated roots of sample pairs satisfying
V[i] < V_spk <= V[i+1]. Pair indices are selected from detached voltage; event times use graph-connected voltage. For N >= 2 events at a site,mean_isi_ms_comp = (t_last - t_first)/(N-1)andspan_frequency_hz_comp = 1000/mean_isi_ms_comp. These values are NaN andvalid_compis false for N < 2. The per-fiber frequency aggregates only selected, defined sites; it is NaN when no site is defined.interspike_intervals_msretains the ordered adjacent intervals, with NaN padding. A caller can form a protocol-defined loss over these intervals when regularity or local spacing matters: the mean span frequency sees only the first and last event times when count is fixed.time_window_msincludes events whose interpolated crossing times lie within the inclusive interval; its bounds need not align with samples.branch_signaturecontains retained global crossing-pair indices at selected sites (None for unselected sites). Compare it between evaluations when checking a local gradient. The derivative describes only the selected crossing branch; event births, losses, gate changes, and refractory changes are discrete and have no derivative here. There are no pulse bins.
- differentiable_firing_rate_trajectory(V, dt_ms, node_mask, *, tau_ms, V_spk=0.0, use_dv_gate=False, dv_spk=10.0, refractory_ms=0.0)#
Return a local differentiable rate trajectory, in Hz, for every neuron.
For each selected site, let
t_ibe its upward threshold-crossing times, linearly interpolated between recorded samples. At sample timet, the site rate is1000 * sum_i K_tau(t - t_i), whereK_tau(s) = 1{s >= 0} * s * exp(-s/tau) / tau**2has units1/ms. The per-neuronrate_hzhas shape(T, F)and is the mean of the selected site rates.node_maskmust select at least one site per neuron; it can have shape(C,)or(F, C).tau_msis a caller-chosen temporal smoothing scale. This causal kernel integrates to one event on an unbounded time axis; its integral on a finite recording can differ from the fixed-window crossing count because of onset lag and end truncation.The crossing-pair indices, optional upstroke gate, and refractory filter are discrete decisions made from detached voltage. Interpolated crossing times remain connected to the voltage graph, so spike-timing changes have gradients. Births and losses of events do not: in particular, a silent neuron has zero rate and no voltage gradient from this descriptor alone.
branch_signatureexposes the selected pair indices for local gradient checks; it is not a rule for rejecting candidate parameter updates. The fixed-window count and this kernelized event train are distinct hard descriptors: a spike’s event count is discrete, while its contribution to this sampled trajectory depends on event time andtau_ms. This is a local existing-event descriptor, not a birth/loss training objective. A separate voltage-intensity trajectory based on the smooth occupancy up-crossings indendra.models.analysis.firing_rate()could supply birth/loss gradients, but needs its own hard-value and gradient validation.
- compare_branch_signatures(left, right)[source]#
Compare signatures from two reruns, returning masks for each choice.
The
all_stablemask has the common signature shape. A false entry means at least one recorded integer choice changed; it does not establish that the hard descriptor jumped. Adjacent arrival/rise/fall pair changes can represent the same linearly interpolated crossing passing a sample time. Compare event times and neighboring traces before treating such a change as a different spike. A changed sampled baseline index can alter the mean discontinuously; continuous-time baseline mode records clipping/emptiness instead of those sample indices.
- hard_spike_timing(V, dt_ms, node_mask=None, *, V_spk=0.0, use_dv_gate=False, dv_spk=10.0, time_window=None, time_window_ms=None, refractory_ms=0.0, aggregate='mean')[source]#
Hard reference for
branch_conditioned_spike_timing().
- hard_firing_rate_trajectory(V, dt_ms, node_mask, *, tau_ms, V_spk=0.0, use_dv_gate=False, dv_spk=10.0, refractory_ms=0.0)[source]#
Hard event-train reference for the matching branch-conditioned trajectory.
The implementation names branch_conditioned_action_potential_width,
branch_conditioned_activity_dependent_slowing,
branch_conditioned_spike_timing, and
branch_conditioned_firing_rate_trajectory are equivalent public aliases.
differentiable_conduction_velocity is an alias for the preferred explicit
name branch_conditioned_conduction_velocity.
Standalone conduction velocity#
branch_conditioned_conduction_velocity has the exact
hard_conduction_velocity value on its forward pass. It selects the first
hard upward threshold crossing at every included site, linearly interpolates
each selected crossing with the voltage graph intact, and differentiates the
spatial ordinary-least-squares fit through those arrival times. A valid
velocity requires at least two included sites with crossings and arrival-time
variance greater than eps. Use node_mask and the optional time window
to select recording sites and isolate the propagated action potential of
interest.
The derivative is local to those event choices. It does not describe the creation of a missing distal response, the loss of a response, or a switch to a different spike. Rerun the full protocol and recompute the descriptor after every parameter update so that the selected branch follows the current model.
The conduction_velocity function is a distinct smooth
estimator based on soft upstroke localization and soft spike-presence weights.
It estimates a smooth response rather than the exact hard-forward
measurement above.
Threshold-derived training objectives#
A complete hard search supplies each threshold and bracket. A nearby voltage
replay supplies a validated local direction. The composition helpers preserve
the hard threshold values on the forward pass and propagate their directions
through activation probability, a strength-duration fit, or a paired-pulse
ratio. The complete threshold and chronaxie example shows the required hard
search, amplitude JVP, replay ordering, parameter gradients, and independent
hard finite-difference checks.
- select_trace_tangent_threshold_probe(hard_threshold, hard_bracket, *, hard_is_active, trace_and_tangent, min_tangent_norm, max_relative_linearization_error, mask=None, relative_gaps=(1e-06, 1e-05, 0.0001, 0.001), check_step_fraction=0.5, sides=('inactive',), verify_bracket_endpoints=False, stability_parameters=None, max_relative_gradient_disagreement=None)[source]#
Select the first locally valid probe from a dimensionless gap ladder.
hard_bracketis(inactive_amplitude, active_amplitude)from a complete hard activation search. Its order may be increasing or decreasing; this supports either stimulus polarity. The hard threshold must lie between the two endpoints. By default the supplied bracket is trusted, avoiding two redundant hard simulations. Setverify_bracket_endpointsto replay its hard decisions.For each relative gap
g, definescale = max(abs(T), bracket_width)and moveg * scalebeyond the corresponding bracket endpoint. The second replay moves anothercheck_step_fraction * g * scaleoutward. The hard decision callback must confirm both amplitudes are on the requested side, even when the bracket’s activation response is not monotonic outside its endpoints.trace_and_tangent(A, True)returns the differentiable probe trace and its amplitude JVP; the call at the second amplitude usesFalseand needs only the voltage. The check replay runs first and its voltage is snapshotted. The gradient-bearing probe replay must be the callback’s final simulator forward before the caller takes a backward pass, because a later simulator run may mutate saved VJP buffers. A callback that computes a JVP with another forward should do so before its fresh, gradient-bearing probe replay. A fixedmaskcan select protocol-relevant sites and times. The caller may derive a new mask from its hard event protocol on each threshold call; this selector holds that mask fixed across the local probe ladder and never chooses a voltage event or branch itself.The selected candidate delegates the weighted trace projection and same-side linearity calculation to
trace_tangent_threshold_proxy. Rejected traces are not stored inattempts; accepted candidates retain one proxy graph so a single backward pass reaches all connected model parameters.min_tangent_normhas the caller’s voltage/amplitude units and must be chosen for that protocol. A valid result is only a candidate descent direction: complete hard-search parameter secants remain the independent validation target.Optionally pass
stability_parametersto compute a detached gradient vector for each locally valid candidate in one VJP per candidate. Withmax_relative_gradient_disagreement, the first two accepted probes on the same side whose gradient vectors agree within the stated relative Euclidean tolerance confirm the current, latest-forward probe. The selected proxy retains its graph for a later training backward pass. This costs extra reverse passes during probe selection, but never finite differences in model parameters. Agreement across probes still cannot prove agreement with the hard threshold gradient: an unsuitable observation mask or horizon can induce the same bias at every probe.
- trace_tangent_threshold_proxy(hard_threshold, probe_amplitude, voltage, amplitude_tangent, *, min_tangent_norm, mask=None, check_amplitude=None, check_voltage=None, max_relative_linearization_error=None)[source]#
Attach a trace-based direction to a hard protocol threshold.
The caller obtains
hard_thresholdusing its complete hard activation protocol. It then runs a differentiable trial at the fixed, normally subthresholdprobe_amplitudeand supplies its voltage traceVand amplitude tangentJ_A = partial V / partial A. The tangent can be computed with a simulator JVP or approximated by a same-side finite difference in stimulus amplitude. Only the latter scalar input is differenced; no model parameter coordinate is differenced. The tangent is detached here so no second-order simulator derivative is needed. One reverse pass through the returned scalar proxy reaches every parameter connected tovoltage.For parameter
q, the backward slope is the weighted least-squares amplitude shift that offsets the trace perturbation,dT_proxy/dq = -<J_A, J_q>_w / <J_A, J_A>_w.maskis a broadcastable, nonnegative sample weight; omitted means all samples. Units of the returned slope are amplitude units per unit ofq. The probe amplitude is an experimental choice. If its tensor has an autograd connection, its direct derivative is cancelled; model parameter gradients through the trace remain. The forward value is the detached hard threshold, irrespective of the trace’s numerical value.Optionally supply a second same-side voltage trace and its amplitude to measure
||V(A+delta)-V(A)-delta J_A||_w / ||delta J_A||_w. A limit on this error rejects a locally nonlinear amplitude response. This check cannot establish that the trace direction follows the hard activation boundary; compare it against complete hard threshold searches when selecting probe amplitudes and trace windows.
- gaussian_expected_activation(center, threshold, noise_std)[source]#
Return activation probability for a Gaussian-distributed amplitude.
The complete hard protocol is assumed to change from inactive to active at the scalar
threshold. If the delivered amplitude isA = center + noise_std * Z, withZ ~ N(0, 1), this function returnsP(A >= threshold) = Phi((center - threshold) / noise_std).thresholdcan be the proxy fromtrace_tangent_threshold_proxy(). Its forward value is then the complete hard threshold, while autograd uses the validated local trace-tangent direction. The Gaussian width is a user-selected smoothing scale in the same amplitude units; it describes the training objective and is not inferred from the voltage trace.- Parameters:
center (float | Tensor) – Mean stimulus amplitude. A tensor may have any shape.
threshold (Tensor) – A scalar floating-point tensor. Gradients propagate through it.
noise_std (float | Tensor) – Positive Gaussian standard deviation in stimulus-amplitude units.
- chronaxie_from_threshold_proxies(pulse_widths_ms, threshold_proxies, *, weights=None, require_positive_chronaxie=True)[source]#
Fit rheobase and chronaxie from validated hard-forward thresholds.
Each input result should represent the complete hard activation threshold at one fixed pulse width. The function stacks their hard-forward proxies and fits the current-domain Weiss relation
T(d) = r + b/d = r * (1 + c/d),where
dis pulse width in milliseconds,Tis threshold stimulus strength,ris rheobase,bis the strength-duration slope, andc = b/ris chronaxie in milliseconds. Ordinary or weighted least squares is used without a denominator regularizer, so a valid result has the exact fit and gradient for the supplied hard-forward thresholds.Pulse widths and weights define the fixed protocol and are detached. Gradients propagate through every threshold proxy to all connected model parameters. The fit is rejected when a proxy is invalid or disconnected, when the design lacks two distinct positive pulse widths with positive weight, or when the fitted physiological quantities are invalid. Rejected results contain explicit
rejection_reasonsrather than a regularized numerical answer.- Parameters:
pulse_widths_ms (Sequence[float] | Tensor) – One positive, finite pulse width per threshold proxy.
threshold_proxies (Sequence[TraceTangentThresholdResult]) – Valid results returned by
trace_tangent_threshold_proxy().weights (Sequence[float] | Tensor | None) – Optional fixed nonnegative fit weights. Zero excludes a point.
require_positive_chronaxie (bool) – Reject nonpositive fitted chronaxie values when true (the default).
- paired_pulse_recovery_ratio_from_trace_tangents(conditioned, baseline)[source]#
Compose two matched hard-forward threshold proxies as
C / B.conditionedandbaselinemust come from the same chosen recovery protocol and parameter coordinate. This function supplies no simulation or matching policy: the caller must run the full conditioned and time-matched unconditioned hard searches, and validate each trace tangent against hard parameter secants. When both inputs are valid, ordinary Torch division gives the quotient gradient through both searches,d(C/B)/dq = (B dC/dq - C dB/dq) / B**2.The forward ratio is exactly the ratio of the two reported hard thresholds. A nonpositive baseline or a malformed proxy returns
ratio=Nonewith an explicit reason. No denominator regularizer is added, since that would change the hard protocol’s ratio.
- class ProbeTrace(voltage, amplitude_tangent=None)[source]#
One voltage replay;
amplitude_tangentis needed only at the probe.The tangent is a voltage JVP with respect to the scalar stimulus amplitude. A same-side amplitude secant is also acceptable. Neither construction needs a finite difference along any model-parameter coordinate.
- class ProbeAttempt(side, relative_gap, probe_amplitude, check_amplitude, hard_probe_active, hard_check_active, diagnostics, parameter_gradient, relative_gradient_disagreement, rejection_reasons)[source]#
Detached record of one candidate, including explicit rejection reasons.
- class ProbeSelectionResult(threshold, selected_attempt_index, attempts, rejection_reasons)[source]#
The selected hard-forward proxy and a graph-free history of attempts.
- class TraceTangentDiagnostics(selected_samples, amplitude_tangent_l2, relative_linearization_error, secant_gain)[source]#
Detached checks in the caller’s trace and amplitude units.
- class TraceTangentThresholdResult(proxy, diagnostics, rejection_reasons)[source]#
Hard value with a trace-projection backward, or a rejection reason.
General hard-transition expectation#
Use this lower-level composition when a complete hard scan contains more than one transition or signed, nonmonotone jumps.
- gaussian_expected_hard_from_transition_roots(center, roots, jumps, left_value, noise_std)[source]#
Compose sorted hard transitions under Gaussian stimulus variation.
Suppose the complete hard protocol at amplitude
Ais the step functionH(A) = H_left + sum_j Delta_j 1{A >= r_j},with strictly increasing roots
r_jand signed jumpsDelta_j. ForA = center + noise_std * ZandZ ~ N(0, 1), returnG(center) = E[H(A)] = H_left + sum_j Delta_j Phi((center-r_j)/noise_std).rootsandjumpsare one-dimensional tensors of equal length; an empty table gives the constantH_left.centermay have any shape, so one root table can be evaluated on an amplitude grid. The other two inputs are scalars. Torch autograd propagates throughcenter,roots,jumps,left_value, and a tensornoise_std. For hard count/success descriptors,jumpsandleft_valueare fixed event values; keeping them constant gives the parameter derivativedG/dq = -sum_j Delta_j phi((center-r_j)/noise_std) (dr_j/dq)/noise_std.A root may be a hard-forward trace-tangent proxy, allowing one backward pass through all connected model parameters. This is a valid local training direction only if the root identities and jump sizes remain stable, all transitions with relevant Gaussian mass are included, and each root tangent follows the corresponding complete hard boundary. Signed jumps represent nonmonotone firing or following responses; the function does not assume monotone recruitment. Duplicate roots must be combined into one signed jump before calling. A full Gaussian requires the hard protocol to be defined on its amplitude support; truncation or omitted tails require an explicit error bound from the caller.
Tensor inputs must share dtype and device with
roots; Python scalar inputs are converted using the roots’ dtype and device. Unsorted, duplicate, nonfinite, or malformed transition tables are rejected.
Additional measurements#
These functions measure responses and protocol results. For training, use the
hard-forward interfaces above when their measurement contracts apply. frequency_following is experimental as an optimization
objective; use it for diagnostics unless its direction has been validated for
the declared model and protocol.
- action_potential_width(V, dt_ms, node_mask=None, *, t_hat_ms=None, p_spike=None, mode='half_height', beta=50.0, dv0=0.0, dv_scale=1.0, lambda_early=0.0, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, use_dv_gate=False, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, baseline_pre_ms=1.0, baseline_guard_ms=0.15, peak_pre_ms=0.2, peak_post_ms=1.5, trough_pre_ms=0.3, trough_post_ms=3.0, width_pre_ms=1.0, width_post_ms=3.0, gate_t_scale_ms=0.05, full_width_pre_ms=None, full_width_post_ms=8.0, baseline_margin_mV=1.0, V_full_width_scale=None, return_tail_ms=0.5, kappa_peak=10.0, kappa_trough=10.0, half_level=0.5, V_width_scale=1.0, amp_min_mV=20.0, amp_scale_mV=5.0, min_ess=3.0, min_amp_mV=5.0, reg_ess_weight=0.0, reg_amp_weight=0.0, reg_full_width_weight=0.0, max_full_width_ms=8.0, reg_return_weight=0.0, eps=1e-06, return_time_traces=False)[source]#
Differentiable AP width surrogate.
- Returns per-fiber AP width estimates by:
localizing the main spike per compartment,
constructing a differentiable half-amplitude level,
integrating a soft indicator of V > V_half over time.
Also returns a differentiable baseline-relative full-width metric for the threshold excursion connected to the localized spike peak. The connectivity envelope stops after the first return below
V_base + baseline_margin_mV, so a later spike in the window does not contribute to this spike’s width.The extra return diagnostic measures whether the trace is still above the baseline-plus-margin level near the end of the post-spike search window.
Assumes these are available in the outer scope:
import torch import torch.nn.functional as F
and that _soft_arrival_and_spike_gate(…) is defined.
- active(V, dt_ms, node_mask=None, *, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, use_dv_gate=True, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, time_window=None, aggregate='softmax', min_ess=1.0, reg_ess_weight=0.0, eps=1e-06)[source]#
Differentiable spike-present / “active” surrogate.
active[f] is a smooth confidence that at least one AP occurred in the user-selected readout region of fiber f within the analysis window.
Aggregation options#
- softmax:
Region-level smooth max over time and selected compartments. Best default for “did any selected trace spike?”
- soft_or:
Probabilistic soft-OR over per-compartment activity confidences.
- mean:
Literal mean local activity confidence over selected compartments.
- returns:
out – “active” : (F,) aggregated readout-region activity confidence “active_comp” : (F, C) per-compartment activity confidence “p_spike” : (F, C) alias for active_comp “score_comp” : (F, C) pre-sigmoid voltage score per compartment “weights” : (F, C) selected compartment weights / mask “ess” : (F,) effective sample size of the readout weights “window_ms” : scalar analyzed duration in ms “reg” : scalar optional regularizer
- rtype:
dict[str, torch.Tensor]
- activity_dependent_slowing(V, pulse_times_ms, dt_ms, *, lengths_um=None, node_mask=None, response_window_ms=(0.1, 10.0), gate_t_scale_ms=0.05, window_margin_ms=None, chunk_pulses=None, return_compartment_metrics=True, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, use_dv_gate=True, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, beta=50.0, dv0=0.0, dv_scale=1.0, lambda_early=0.0, baseline_pulse_indices=None, baseline_n_pulses=1, reference_latency_ms=None, reference_velocity_m_per_s=None, tail_n_pulses=10, success_threshold=0.5, min_ess=1.0, min_var_ms2=0.001, min_success_prob=0.5, reg_ess_weight=0.0, reg_var_weight=0.0, reg_success_weight=0.0, eps=1e-08, eps_time_ms2=None, eps_latency_ms=None, eps_velocity_m_per_s=None, return_time_traces=False)[source]#
Differentiably estimate activity-dependent slowing (ADS), train following, latency drift, and optional velocity drift from pulse-train simulations.
This optimized implementation avoids the original per-pulse full-time gating cost. Instead of constructing a
T x F x Csoft gate for every pulse in the train, it gathers a short pulse-locked local window around each stimulus and performs all soft maxima / soft arrivals on the resultingF x N x K x Ctensor, whereKis the number of samples inresponse_window_msplus a small sigmoid-gate margin. For long ADS traces this changes the dominant cost from approximatelyO(N*T*F*C)toO(N*K*F*C)withK << T.Required input data#
- Vtorch.Tensor
Simulated voltage traces with shape
(T, F, C):T: number of time samplesF: number of fibers / model instancesC: number of compartments or recording sites
The trace must contain the whole pulse train. Units are typically mV. Gradients propagate through
Vand therefore through the upstream differentiable simulator.- pulse_times_msarray-like or torch.Tensor
Stimulus pulse onset times in ms. Accepts shape
(N,)for a pulse train shared by all fibers,(1, N)for broadcastable pulse times, or(F, N)for fiber-specific pulse times.Nis the number of pulses in the train.- dt_msfloat or torch.Tensor
Simulation time step in milliseconds.
Simulations required to produce the input data#
To compute ADS, run a train-stimulation simulation such as:
for n in range(N):deliver the same suprathreshold pulse at
pulse_times_ms[n]
and record the membrane potential across the compartments used for propagation readout. The response window should be long enough for each pulse-evoked spike to reach the selected readout region but short enough to avoid overlap with the next pulse. Select distal compartments in
node_maskwhen ADS should reflect propagation to a distal endpoint.Performance controls#
- window_margin_msfloat, optional
Extra time included before and after the response window when gathering local samples. If
None, this defaults tomax(6*gate_t_scale_ms, 2*dt_ms). Increasing this makes the local-window result closer to a full-trace sigmoid gate; decreasing it saves memory.- chunk_pulsesint, optional
If provided, process at most this many pulses at once. This keeps the fast local-window method memory bounded while retaining vectorization within each chunk. Use e.g.
chunk_pulses=16for very largeF*C*N*K.- return_compartment_metricsbool, default=True
If True, return compartment-level arrays such as
p_success_compandt_hat_ms_comp. Set to False inside optimization loops to reduce memory retained in the autograd graph; fiber-level outputs are still returned.
Optional velocity inputs#
- lengths_umscalar, torch.Tensor, or sequence, optional
Compartment lengths in micrometers. Accepts a scalar, shape
(C,), or shape(F, C). When provided, a per-pulse conduction velocity is estimated by weighted regression of compartment position against pulse-locked soft arrival time. If omitted, the function still returns latency-based ADS.- node_masktorch.Tensor, optional
Compartment mask/weights with shape
(C,)or(F, C). Use this to select the readout region. For latency-only ADS, this is often a distal compartment or distal group. For velocity ADS, it should include multiple compartments spanning a meaningful propagation distance.
- returns:
out – Main outputs:
"pulse_times_ms"torch.Tensor, shape(F, N)Pulse onset times used for the analysis.
"p_success"torch.Tensor, shape(F, N)Smooth train-following / spike-success confidence for each pulse.
"follow_fraction"torch.Tensor, shape(F,)Mean pulse-following probability across the train.
"latency_ms"torch.Tensor, shape(F, N)Pulse-locked latency relative to each stimulus onset.
"ads_percent"/"latency_slowing_percent"torch.Tensor, shape(F, N)Percent latency increase relative to baseline. Positive values indicate slowing.
"final_ads_percent"and"tail_ads_percent"torch.Tensor, shape(F,)ADS at the final pulse and success-weighted mean ADS over the final pulses.
Optional velocity outputs, returned as
Nonewhenlengths_umis omitted:"v_m_per_s","velocity_change_percent", and"velocity_slowing_percent".- rtype:
dict[str, Any]
Notes
All main outputs are differentiable with respect to
V. Pulse times and gathered sample indices are treated as experiment-design constants.If the train contains multiple spikes per response window, the soft arrival estimator returns the dominant upstroke in the local window. Use shorter windows or positive
lambda_earlyto bias toward the first pulse-evoked spike.return_time_traces=Trueno longer stores dense pulse-by-time gates; the function returns a note because storing those gates would defeat the optimization.eps_time_ms2regularizes the arrival-time variance in the velocity regression,eps_latency_msregularizes latency and interstimulus-time denominators, andeps_velocity_m_per_sregularizes percentage velocity changes. If any is omitted, the legacyepsvalue is used for that quantity, preserving the behavior of existing calls. When an explicit velocity epsilon is supplied, its square regularizes the smooth speed magnitude so the units remain(m/s)^2under the square root.
- chronaxie_from_trials(V, amplitudes, pws_ms, *, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, node_mask=None, time_window=None, activation_mode='soft_max', at_least=1, count_scale=0.25, count_event='crossing', count_V_scale=None, crossing_count_threshold=0.5, crossing_count_scale=0.1, use_activation_straight_through=False, count_grad_scale=None, count_V_grad_scale=None, crossing_count_grad_scale=None, fraction_threshold=0.9, fraction_scale=0.05, partition_masks=None, partition_combine='any', dt_ms=None, use_dv_gate=False, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, strength=None, use_abs_strength=False, pw_round_decimals=None, enforce_min_trials_per_pw=True, min_trials_per_pw=2, threshold_method='onset_midpoint', p_target=0.5, alpha_thresh=200.0, alpha_extreme=50.0, membership_power=10.0, gap_alpha=200.0, below_gate_frac=0.02, compute_block=True, p_low=0.05, p_high=0.95, reg_bracket_weight=0.0, reg_monotone_weight=0.0, reg_unimodal_weight=0.0, unimodal_beta_peak=50.0, unimodal_tau_idx=1.0, reg_weiss_fit_weight=0.0, weiss_fit_domain='charge', log_current_iterations=25, log_current_min_chronaxie_ms=0.0001, log_current_max_chronaxie_ms=1000.0, eps=1e-08)[source]#
Differentiably estimate chronaxie and rheobase from trial-wise voltage recordings.
Each trial
pcorresponds to one stimulus amplitude / pulse-width pair:V[t, p, c],amplitudes[p],pws_ms[p].The function first computes a differentiable activation confidence per trial, then extracts a differentiable onset threshold for each pulse width, and finally fits the Weiss charge-duration relation
Q_th(d) = d * I_th(d) ~= I_r * d + I_r * c.This version supports multiple activation aggregators. The default
activation_mode='soft_max'preserves the previous behavior: a smooth max over time and selected compartments. For extracellular stimulation, where the field can strongly depolarize compartments under the electrode without producing a robust propagating AP, useactivation_mode='soft_count'. In that mode the function first computes a per-compartment event probability and then activates the trial only when approximatelyat_leastselected compartments spike, providing a differentiable analogue of Dendra’sActiveALcallback. By default, count-based modes usecount_event='crossing'so that a compartment contributes when it has an upward threshold crossing, rather than merely a large smooth maximum voltage.use_dv_gate=Truecan additionally suppress passive depolarizations by requiring a strong upstroke.Recommended extracellular usage:
chron = chronaxie_from_trials( V_distal, amps, pws_ms, V_spk=-20.0, dt_ms=0.005, activation_mode="soft_count", at_least=3, count_event="crossing", count_V_scale=1.0, count_scale=0.25, use_dv_gate=True, dv_spk=10.0, threshold_method="onset_midpoint", )
Threshold extraction#
For each pulse-width group, the function estimates:
I_on: soft lowest activating strength;I_pre_inactive: soft nearest inactive strength below onset;I_th: by default0.5 * (I_pre_inactive + I_on).
This matches the empirical midpoint between the highest inactive and lowest active amplitudes, while remaining differentiable and robust to high-amplitude block.
Returns include
p_spike_trial(P,),p_spike_comp(P, C), optionalsoft_active_count(P,), threshold boundaries, fitted rheobase/chronaxie, and regularization terms. Gradients propagate throughV; amplitudes and pulse widths are treated as experiment-design constants.
- compute_rheobase_chronaxie(pws, thresholds, *, weights=None, fit_domain='current', log_current_iterations=50, log_current_min_chronaxie_ms=0.0001, log_current_max_chronaxie_ms=1000.0, return_dict=False, eps=1e-12)[source]#
Estimate rheobase and chronaxie from strength-duration thresholds.
This is a standalone analogue of the common NumPy/polyfit helper:
x = 1 / pws y = thresholds b, a = np.polyfit(x, y, deg=1) rheobase = a chronaxie = b / a
but with an explicit fit-domain choice matching
chronaxie_from_trials.- Parameters:
pws (array-like or torch.Tensor) – One-dimensional pulse widths with shape
(D,). Units are arbitrary but determine the returned chronaxie units. For Dendra chronaxie analyses this is usually milliseconds.thresholds (array-like or torch.Tensor) – One-dimensional activation thresholds with shape
(D,), in current units.weights (array-like or torch.Tensor, optional) – Optional one-dimensional nonnegative weights with shape
(D,), one for each pulse-width/threshold pair.fit_domain ({"current", "charge", "log_current"}, default="current") –
How to fit the Weiss/Lapicque relation
I(PW) = Irh * (1 + Tch / PW).
"current"Ordinary least-squares fit of
Iagainst1/PW. This exactly matches the supplied NumPypolyfitmethod whenweights=None."charge"Ordinary least-squares fit of charge
Q = PW * IagainstPW. This is the historical/default behavior used by earlier versions ofchronaxie_from_trials."log_current"Thio-style log-current fit:
log10(Ith) = log10(Irh * (1 + Tch / PW)).
The implementation minimizes squared residuals in log current. The log base does not affect the optimum; diagnostics are reported in log10 units for interpretability.
log_current_iterations (int, default=50) – Number of differentiable Gauss-Newton iterations used for the nonlinear one-dimensional
log_currentfit.log_current_min_chronaxie_ms (float) – Bounds for chronaxie during the log-current fit. Despite the
_mssuffix, these are in the same units aspws.log_current_max_chronaxie_ms (float) – Bounds for chronaxie during the log-current fit. Despite the
_mssuffix, these are in the same units aspws.return_dict (bool, default=False) – If False, return
(rheobase, chronaxie). If True, return the full fit dictionary including predictions and residual diagnostics.eps (float, default=1e-12) – Numerical stability constant.
- Returns:
rheobase, chronaxie – If the inputs are NumPy/list-like, returns Python floats by default. If any input is a torch.Tensor, returns differentiable torch tensors.
- Return type:
float or torch.Tensor
Notes
The
log_currentfit is the closest analogue to the Thio et al. equation. It is useful when thresholds span a large dynamic range because it fits relative/multiplicative threshold errors rather than absolute current errors.
- conduction_velocity(V, lengths_um, dt_ms, node_mask=None, *, beta=50.0, dv0=0.0, dv_scale=1.0, lambda_early=0.0, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, use_dv_gate=False, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, min_ess=3.0, min_var_ms2=0.001, reg_ess_weight=0.0, reg_var_weight=0.0, eps=1e-06, eps_speed=1e-08)[source]#
Differentiably estimate per-fiber conduction velocity from spatiotemporal membrane potentials.
This function computes a smooth, differentiable surrogate for conduction velocity for each fiber in a multicompartment model, given a tensor of membrane potentials V[t, f, c] and per-compartment physical lengths.
The estimator has three conceptual steps:
Compartment positions \(x_{f,c}\) in \(\mu m\) are formed from the cumulative sum of compartment lengths (midpoint convention).
Soft arrival times \(\hat{t}_{f,c}\) (ms) are estimated per compartment using a soft-argmax over time of an upstroke score based on \(dV/dt\).
(Weighted) linear regression estimates a propagation speed by fitting \(x_{f,c} \approx b_f + v_f \hat{t}_{f,c}\) across compartments within each fiber. Optional weights (gating) reduce the influence of compartments where an AP does not “arrive” or where the compartment should be excluded (e.g., internodes).
All operations are differentiable w.r.t. V (and thus w.r.t. upstream model parameters).
- Parameters:
V (torch.Tensor) –
Membrane potentials with shape
(T, F, C)where:T: number of time samplesF: number of fibersC: number of compartments per fiber
Units in Axon are typically mV (but any consistent voltage units are acceptable; see Notes).
lengths_um (scalar, array-like, or torch.Tensor) –
Compartment physical lengths in micrometers. Accepts:
scalar: every compartment in every fiber has this length;
shape
(C,): a compartment-length vector shared by all fibers;shape
(F, C): fiber-specific compartment lengths.
These are used to compute compartment midpoint positions along each fiber. For dn.Myelinated, this should be internodal length (model.deltax(model.diameters)[:, None].expand_as(model.dx)).
dt_ms (float or torch.Tensor) – Time step between samples in milliseconds. If provided as a tensor, it will be cast to
V.dtypeand moved toV.device.node_mask (torch.Tensor or None, optional) –
Optional compartment inclusion mask with shape
(F, C). If provided:boolean mask:
Trueentries are included,Falseexcludedfloat mask: values act as multiplicative weights (e.g., soft node-ness)
This is useful for complex myelinated models (e.g., MRG) where APs are generated only at nodes of Ranvier. If
None, all compartments are eligible.beta (float, default=50.0) – Soft-argmax sharpness over time for arrival time estimation. Larger values approach a hard argmax (peakier gradients); smaller values yield smoother arrival times.
dv0 (float, default=0.0) – Baseline upstroke threshold in mV/ms applied to \(dV/dt\) before the softplus. Increasing this can suppress small passive slopes.
dv_scale (float, default=1.0) – Softness (scale) in mV/ms for the upstroke score \(U=\mathrm{softplus}((dV/dt - dv0)/dv\_scale)\).
lambda_early (float, default=0.0) – Optional early-time bias (units 1/ms). The time logits are:
beta * U - lambda_early * t_mid. Uselambda_early > 0when multiple spikes may occur and you want to bias toward earlier events.V_spk (float, default=0.0) – Voltage reference (mV) for spike-present gating. The gating uses a smooth max of
V - V_spkover time. Common choices: 0 mV, -20 mV, etc.kappa_V (float, default=20.0) – Sharpness of the smooth max over time for voltage gating. Larger values approach a hard maximum (more threshold-like).
gate_V_scale (float, default=5.0) – Softness (mV) of the sigmoid converting the smooth max voltage score into a confidence.
use_dv_gate (bool, default=False) – If
True, additionally gates weights using a smooth max of \(dV/dt\) over time. This can help prevent passive compartments with small voltage peaks from contributing.dv_spk (float, default=10.0) – Reference threshold (mV/ms) for the optional \(dV/dt\) gating.
kappa_dv (float, default=10.0) – Sharpness for the smooth max over time applied to
(dV/dt - dv_spk)in the dv gate.gate_dv_scale (float, default=5.0) – Softness for the sigmoid converting dv smooth max into a confidence.
min_ess (float, default=3.0) – Minimum desired effective sample size (ESS) of contributing compartments per fiber. If the ESS is too small (e.g., too few nodes/compartments have non-negligible weight), the regression slope becomes noisy.
min_var_ms2 (float, default=1e-3) – Minimum desired weighted variance of estimated arrival times (ms^2). If the time spread is too small, the velocity estimate can explode because the regression denominator approaches zero.
reg_ess_weight (float, default=0.0) – Weight for an optional differentiable penalty encouraging ESS >=
min_ess. The penalty returned inout["reg"]includes:reg_ess_weight * softplus(min_ess - ess).mean().reg_var_weight (float, default=0.0) – Weight for an optional differentiable penalty encouraging Var(t_hat) >=
min_var_ms2. The penalty returned inout["reg"]includes:reg_var_weight * softplus(min_var_ms2 - var_t).mean().eps (float, default=1e-6) – Small constant for numerical stability in denominators.
eps_speed (float, default=1e-8) – Small constant used for smooth absolute value:
speed = sqrt(v^2 + eps_speed).
- Returns:
out – Dictionary of per-fiber estimates and intermediate quantities:
"v_m_per_s"torch.Tensor, shape(F,)Signed conduction velocity estimate in meters/second.
"speed_m_per_s"torch.Tensor, shape(F,)Smooth speed (m/s), computed as
sqrt(v^2 + eps_speed)(differentiable at 0).
"v_um_per_ms"torch.Tensor, shape(F,)Same as
v_m_per_sbut in micrometers/millisecond. Note: \(1~\mu m/ms = 10^{-3}~m/s\).
"t_hat_ms"torch.Tensor, shape(F, C)Soft arrival time per compartment (ms), computed via soft-argmax of an upstroke score.
"p_spike"torch.Tensor, shape(F, C)Spike-present confidence per compartment prior to applying
node_mask. Values in (0, 1).
"weights"torch.Tensor, shape(F, C)Final regression weights per compartment, equal to
p_spike * node_mask(orp_spikeifnode_mask is None).
"ess"torch.Tensor, shape(F,)Soft effective sample size per fiber: \(ESS = (\sum w)^2 / \sum w^2\).
"var_t_ms2"torch.Tensor, shape(F,)Weighted variance of
t_hat_msused in the regression denominator (ms^2).
"reg"torch.Tensor, scalarOptional regularization penalty (0 if
reg_ess_weight==reg_var_weight==0). Add this to your task loss if you want to enforce robustness constraints.
- Return type:
dict[str, torch.Tensor]
Notes
Arrival time definition. Arrival times are computed from the time derivative:
dV = (V[t+1] - V[t]) / dt_ms(mV/ms)upstroke score
U = softplus((dV - dv0)/dv_scale)soft-argmax weights over time
softmax(beta*U - lambda_early*t_mid)t_hat = sum_t w_t * t_mid
This tends to be more stable than threshold-crossing times because it uses a smooth peak of the upstroke rather than an event time.
Gating and node masks. In myelinated models, internodes may not generate spikes. Passing
node_mask(nodes=1, internodes=0) ensures the regression is based on node-to-node timing. Ifnode_maskis omitted, the voltage gate often downweights internodes automatically, but explicit masking is usually cleaner.When to use the optional dv gate. If you observe that some compartments reach modest voltages (raising
p_spike) but do not exhibit a strong upstroke, enablinguse_dv_gatecan suppress their influence.Units. The code assumes lengths are in \(\mu m\) and time is in ms, producing \(\mu m/ms\). This is consistent with Dendra’s internal practice of representing lengths in \(\mu m\), therefore model.dx etc. can often be used directly. For dn.Myelinated, internodal length should be used instead of compartment length. The conversion to m/s is a fixed factor of \(10^{-3}\).
Directionality. The returned
v_m_per_sis signed: positive means increasing x with increasing arrival time. Usespeed_m_per_swhen you only care about magnitude.Assumptions. This estimator is best behaved when:
a single traveling AP (or a dominant one) is present within the time window,
recordings exclude the initiation region,
compartments used for fitting span a meaningful propagation distance.
Examples
Basic usage (single AP, known nodes):
>>> out = conduction_velocity( ... V, lengths_um, dt_ms, ... node_mask=node_mask, ... V_spk=-10.0, ... beta=60.0, ... ) >>> v = out["v_m_per_s"] # (F,) >>> loss = task_loss(v) + out["reg"] >>> loss.backward()
Add robustness penalties when training:
>>> out = conduction_velocity( ... V, lengths_um, dt_ms, ... node_mask=node_mask, ... reg_ess_weight=1e-2, min_ess=4.0, ... reg_var_weight=1e-2, min_var_ms2=5e-3, ... ) >>> loss = task_loss + out["reg"]
See also
torch.logsumexpUsed to compute smooth maxima (differentiable approximation).
torch.softmaxUsed to implement soft-argmax over time.
- firing_rate(V, dt_ms, node_mask=None, *, p_spike=None, V_spk=0.0, gate_V_scale=5.0, use_dv_gate=True, dv_spk=10.0, kappa_V=20.0, kappa_dv=10.0, gate_dv_scale=5.0, time_window=None, min_ess=1.0, reg_ess_weight=0.0, eps=1e-06, confidence_weighted=False)[source]#
Differentiable firing-rate surrogate in Hz.
- For each compartment:
s[t] = sigmoid((V[t] - V_spk) / gate_V_scale)
- Then count soft upward crossings:
up[t] = relu(s[t+1] - s[t])
For a full 0->1->0 excursion, sum_t up[t] is approximately 1, so each AP contributes about one count. Optionally, up is multiplied by a smooth dV/dt gate to reject slow threshold crossings.
- Returns:
out – “rate_hz” : (F,) weighted per-fiber firing-rate surrogate “rate_hz_comp” : (F, C) per-compartment firing-rate surrogate “count” : (F,) weighted soft spike count over the window “count_comp” : (F, C) per-compartment soft spike count “p_spike” : (F, C) spike-present confidence used for weighting “weights” : (F, C) final aggregation weights “ess” : (F,) effective sample size of weights “window_ms” : scalar analyzed duration in ms “reg” : scalar optional regularizer
- Return type:
dict[str, torch.Tensor]
- frequency_following(V, pulse_times_ms, dt_ms, *, frequency_hz=None, lengths_um=None, node_mask=None, initiation_node_mask=None, response_window_ms=(0.1, 10.0), initiation_response_window_ms=None, gate_t_scale_ms=0.05, window_margin_ms=None, chunk_pulses=None, return_compartment_metrics=False, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, use_dv_gate=True, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, beta=50.0, dv0=0.0, dv_scale=1.0, lambda_early=0.0, frequency_round_decimals=6, accommodation_skip_pulses=0, tail_n_pulses=10, success_threshold=0.5, success_scale=0.05, max_isi_error_ms=None, max_isi_error_frac=0.1, entrainment_isi_scale_ms=0.1, target_follow_fraction=0.9, target_follow_scale=0.05, max_frequency_beta=5.0, baseline_pulse_indices=None, baseline_n_pulses=1, reference_latency_ms=None, reference_velocity_m_per_s=None, min_ess=1.0, min_var_ms2=0.001, min_success_prob=0.5, reg_ess_weight=0.0, reg_var_weight=0.0, reg_success_weight=0.0, eps=1e-08)[source]#
Differentiably estimate frequency following, entrainment, and conduction failure.
Warning
This descriptor is experimental as an optimization objective. Its voltage gradient has not been established as a useful direction for the complete
hard_frequency_followingprotocol. Use the smooth outputs as diagnostics unless the direction has been validated for the declared model, stimulus, recording sites, and response windows.This metric is intended for pulse-train simulations in which the same axon/fiber is driven at one or more stimulation frequencies and the model should be scored by how reliably pulse-evoked spikes propagate to a readout region. It reuses the optimized local-window activity-dependent-slowing estimator internally, so it avoids materializing dense
T x N x F x Cgates for long trains.Required input data#
- Vtorch.Tensor
Voltage traces with shape
(T, F, C).Fcan represent fibers, parameter sets, or trial instances. To compare multiple frequencies in one call, batch them alongFand pass either fiber-specificpulse_times_msorfrequency_hz.- pulse_times_msarray-like or torch.Tensor
Pulse onset times in milliseconds. Accepts shape
(N,)for a common train,(1, N)for broadcastable pulse times, or(F, N)for fiber/trial-specific trains.- dt_msfloat or torch.Tensor
Simulation time step in milliseconds.
Simulations required to produce the input data#
Run one train-stimulation simulation per tested frequency, amplitude, and model condition. For example, to estimate a maximum following frequency, simulate trains at 5, 10, 20, 50, and 100 Hz, recording voltage at a distal readout region. If different frequencies are batched together in
F, passfrequency_hzwith shape(F,). Iffrequency_hzis omitted, a nominal frequency is inferred from the mean pulse interval of each row ofpulse_times_ms.Readout and conduction failure#
node_maskselects the distal/readout compartments used to decide whether a pulse was followed. Ifinitiation_node_maskis also provided, the function separately scores local initiation and distal propagation. It then returns a differentiable conduction-failure scorep_conduction_failure = p_initiated * (1 - p_success)for each pulse. This distinguishes failure to initiate from failure to propagate.
What it returns#
The output dictionary includes the full ADS-style pulse-locked outputs from the distal readout, plus these frequency-following summaries:
p_success(F, N)Smooth probability-like confidence that each pulse produced a distal/readout spike.
follow_fraction(F,)Mean
p_successacross evaluated pulses afteraccommodation_skip_pulses.tail_follow_fraction(F,)Mean
p_successover the lasttail_n_pulses.p_entrained_pair(F, N-1)orNoneSmooth confidence that adjacent output spikes both occurred and preserved the input ISI within
max_isi_error_msormax_isi_error_frac * input_isi.entrainment_interval_ms(F,)Success-weighted output ISI over the tail of the train.
block_fraction/p_conduction_failureoptionalReturned when
initiation_node_maskis supplied. These score pulse-evoked initiation without distal propagation.*_by_frequency(D,)Grouped summaries across all fibers/trials with the same nominal frequency.
soft_max_following_frequency_hzscalarA differentiable soft estimate of the highest tested frequency whose tail following fraction exceeds
target_follow_fraction.
Notes
Main outputs are differentiable with respect to
V. Frequency grouping and pulse times are experiment-design constants.p_successis a smooth confidence, not a calibrated probability unless externally calibrated.Optimization with this smooth score is experimental: its gradient has not been validated as a descent direction for the complete
hard_frequency_followingprotocol. Separate hard-forward event and expected-hard prototypes are also experimental and estimate different training targets.For high-frequency trains, choose
response_window_msso one pulse’s readout window does not include the next pulse’s response.Use
initiation_node_maskplus distalnode_maskwhen you specifically need conduction block/failure rather than simple readout failure.
Example
>>> out = frequency_following( ... V_train, ... pulse_times_ms, ... dt_ms, ... frequency_hz=freqs_hz, ... lengths_um=recording_spacing_um, ... node_mask=distal_mask, ... initiation_node_mask=stim_region_mask, ... response_window_ms=(0.5, 20.0), ... ) >>> diagnostic = out["tail_follow_fraction"]
- hard_action_potential_width(V, dt_ms, node_mask=None, *, V_spk=0.0, dv_th=None, mode='half_height', baseline_pre_ms=1.0, baseline_guard_ms=0.15, baseline_mean_mode='sampled', peak_pre_ms=0.2, peak_post_ms=1.5, trough_pre_ms=0.3, trough_post_ms=3.0, width_pre_ms=1.0, width_post_ms=3.0, half_level=0.5, baseline_margin_mV=1.0, full_width_pre_ms=None, full_width_post_ms=8.0, amp_min_mV=5.0)[source]#
Hard AP half-width and baseline-relative full-width descriptors.
This is the non-differentiable reference analogue of
action_potential_width. At each site it uses the first upwardV_spkcrossing to define a pre-spike baseline and local peak. Full width is the interval between the last upward crossing ofV_base + baseline_margin_mVbefore that peak and the first downward crossing afterward, with linear interpolation between samples.full_width_post_msbounds the search for that first return; it is not accumulated above-threshold time. If the trace is still above the level at the search boundary, that boundary is used as a censored endpoint.baseline_mean_mode="sampled"preserves the historical mean over the floor/ceil-selected sample slice."continuous_time"integrates the piecewise-linear voltage trace over the exact pre-spike time window, with endpoints clipped to the recording. It avoids jumps solely from a baseline window endpoint crossing a sample boundary; peak and crossing event selections remain discrete.
- hard_active(V, dt_ms, node_mask=None, *, V_spk=0.0, use_dv_gate=True, dv_spk=10.0, time_window=None, time_window_ms=None)[source]#
Hard non-differentiable active/inactive descriptor.
A compartment is active if it crosses
V_spkupward in the specified window, optionally requiringdV/dt >= dv_spkon the crossing interval. A fiber is active if any selected compartment is active.
- hard_activity_dependent_slowing(V, pulse_times_ms, dt_ms, *, lengths_um=None, node_mask=None, response_window_ms=(0.1, 10.0), V_th=0.0, dv_th=10.0, baseline_pulse_indices=None, baseline_n_pulses=1, reference_latency_ms=None, reference_velocity_m_per_s=None, tail_n_pulses=10, interpolate=True, eps=1e-12, eps_time_ms2=None, eps_latency_ms=None, eps_velocity_m_per_s=None, window_margin_ms=None)[source]#
Hard non-differentiable activity-dependent slowing descriptor.
This optimized hard reference is the conventional threshold-crossing analogue of
activity_dependent_slowing. It gathers pulse-locked local windows for all pulses and fibers at once, detects the first upward threshold crossing in each selected compartment, computes latency relative to pulse onset, and optionally estimates conduction velocity from hard per-compartment crossing times.It is intended for hard-vs-surrogate comparisons, not gradient-based fitting.
eps_time_ms2,eps_latency_ms, andeps_velocity_m_per_sregularize the time-variance, latency/time, and velocity denominators in their stated units. An omitted value falls back to the legacyepsargument, so existing calls retain their numerical behavior.
- hard_chronaxie_from_trials(V, amplitudes, pws_ms, dt_ms=None, *, V_spk=0.0, use_dv_gate=True, dv_spk=10.0, node_mask=None, time_window=None, time_window_ms=None, strength=None, use_abs_strength=False, pw_round_decimals=None, threshold_method='onset_midpoint', activation_mode='any', at_least=1, weiss_fit_domain='charge', log_current_iterations=25, log_current_min_chronaxie_ms=0.0001, log_current_max_chronaxie_ms=1000.0, eps=1e-12)[source]#
Hard non-differentiable rheobase/chronaxie descriptor from strength-duration trials.
Activation is determined by a hard spike detector in selected readout compartments. Per-pulse width thresholds are empirical onset boundaries, and rheobase/chronaxie are fit using the Weiss charge-duration relation. Use this as the hard reference for
chronaxie_from_trials.
- hard_conduction_velocity(V, lengths_um, dt_ms, node_mask=None, *, V_th=0.0, dv_th=None, time_window=None, time_window_ms=None, interpolate=True, eps=1e-12)[source]#
Hard non-differentiable conduction velocity from first threshold-crossing times.
Arrival times are extracted by
hard_spike_arrival_timesand then used in ordinary least-squares regression of compartment position against arrival time, ignoring inactive or masked compartments. Returns NaN when fewer than two selected compartments spike.
- hard_firing_rate(V, dt_ms, node_mask=None, *, V_spk=0.0, use_dv_gate=False, dv_spk=10.0, time_window=None, time_window_ms=None, refractory_ms=0.0, aggregate='mean')[source]#
Hard spike-count and firing-rate descriptor based on upward threshold crossings.
This is non-differentiable and intended as an experimental reference for validating the smooth
firing_ratesurrogate. By default, per-fiber counts are averaged across selected compartments, matching the surrogate’s mean-over-compartments convention. A millisecond window includes interpolated crossing times on either boundary;window_msis the requested interval clipped to the recorded duration.
- hard_frequency_following(V, pulse_times_ms, dt_ms, *, frequency_hz=None, lengths_um=None, node_mask=None, initiation_node_mask=None, response_window_ms=(0.1, 10.0), initiation_response_window_ms=None, V_th=0.0, dv_th=10.0, interpolate=True, frequency_round_decimals=6, accommodation_skip_pulses=0, tail_n_pulses=10, success_threshold=0.5, success_scale=0.05, max_isi_error_ms=None, max_isi_error_frac=0.1, entrainment_isi_scale_ms=0.1, target_follow_fraction=0.9, target_follow_scale=0.05, max_frequency_beta=5.0, baseline_pulse_indices=None, baseline_n_pulses=1, reference_latency_ms=None, reference_velocity_m_per_s=None, eps=1e-12, window_margin_ms=None)[source]#
Hard non-differentiable reference descriptor for frequency following and conduction failure.
This is the threshold-crossing analogue of
frequency_following. It useshard_activity_dependent_slowingto detect pulse-locked distal responses and, optionally, initiation-region responses. It is intended for hard-vs-surrogate validation, not training.
- hard_paired_pulse_recovery_from_trials(V, test_amplitudes, isis_ms, dt_ms, *, condition_pulse_time_ms=0.0, test_pulse_times_ms=None, response_window_ms=(0.1, 10.0), baseline_threshold=None, reference_latency_ms=None, reference_velocity_m_per_s=None, lengths_um=None, node_mask=None, V_th=0.0, dv_th=10.0, strength=None, use_abs_strength=False, isi_round_decimals=None, threshold_method='onset_midpoint', interpolate=True, eps=1e-12)[source]#
Hard reference descriptor for paired-pulse threshold recovery cycles.
Each trial contains a conditioning pulse and a test pulse. The hard descriptor scores only the test-pulse response in a pulse-locked window, extracts empirical second-pulse thresholds per ISI when test amplitude is swept, and optionally computes hard latency / velocity recovery. This is the non-differentiable reference analogue of
paired_pulse_recovery_from_trials.
- hard_spike_arrival_times(V, dt_ms, *, V_th=0.0, dv_th=None, time_window=None, time_window_ms=None, interpolate=True)[source]#
Non-differentiable first upward-threshold-crossing arrival times.
This hard reference descriptor is intended for comparisons against smooth surrogates. It uses boolean threshold crossings and therefore does not provide useful gradients. Crossings are detected independently for every fiber and compartment. A millisecond window includes interpolated crossing times on either boundary.
Returns
t_cross_msandhas_crossingwith shape(F, C).
- paired_pulse_recovery_from_trials(V, test_amplitudes, isis_ms, dt_ms, *, condition_pulse_time_ms=0.0, test_pulse_times_ms=None, response_window_ms=(0.1, 10.0), gate_t_scale_ms=0.05, baseline_threshold=None, reference_latency_ms=None, reference_velocity_m_per_s=None, lengths_um=None, node_mask=None, V_spk=0.0, kappa_V=20.0, gate_V_scale=5.0, use_dv_gate=True, dv_spk=10.0, kappa_dv=10.0, gate_dv_scale=5.0, compute_latency=True, beta=50.0, dv0=0.0, dv_scale=1.0, lambda_early=0.0, min_ess=1.0, min_var_ms2=0.001, reg_ess_weight=0.0, reg_var_weight=0.0, strength=None, use_abs_strength=False, isi_round_decimals=None, enforce_min_trials_per_isi=True, min_trials_per_isi=2, threshold_method='onset_midpoint', p_target=0.5, alpha_thresh=200.0, alpha_extreme=50.0, membership_power=10.0, gap_alpha=200.0, below_gate_frac=0.02, compute_block=True, success_aggregate='mean', success_beta=50.0, p_low=0.05, p_high=0.95, reg_bracket_weight=0.0, reg_monotone_weight=0.0, reg_unimodal_weight=0.0, unimodal_beta_peak=50.0, unimodal_tau_idx=1.0, eps=1e-08, return_time_traces=False)[source]#
Differentiably estimate paired-pulse recovery and threshold recovery-cycle metrics.
This function implements a smooth surrogate for the electrophysiological paired-pulse recovery / threshold recovery-cycle experiment. Each trial should contain a conditioning pulse followed by a test pulse. The metric scores the response to the test pulse only in a pulse-locked differentiable readout window.
The function supports two common protocols:
- 1. Threshold recovery cycle.
For each interstimulus interval (ISI), simulate a sweep over second-pulse/test-pulse amplitudes. The first/conditioning pulse is usually fixed and suprathreshold. The input tensor therefore contains one trial per
(ISI, test_amplitude)pair. The function extracts a differentiable second-pulse threshold for each ISI. Ifbaseline_thresholdis supplied, it returnsthreshold_ratio[isi] = I_th_test[isi] / baseline_threshold.Values greater than 1 indicate elevated threshold / relative refractoriness. Values less than 1 indicate supernormal excitability.
- 2. Fixed-amplitude paired-pulse success, latency, or velocity recovery.
For each ISI, simulate one or more paired-pulse trials at fixed test-pulse amplitude. Threshold extraction is not well bracketed in this mode, but the function still returns smooth test-response probabilities, latencies, and optional velocity recovery. Set
enforce_min_trials_per_isi=Falseif there is only one amplitude per ISI.
Required input data#
- Vtorch.Tensor
Voltage recordings with shape
(T, P, C):T: number of time samplesP: number of paired-pulse trialsC: number of compartments / recording sites
Vshould include both the conditioning response and the test response. The test response is scored only within a window relative to the test-pulse time. Units are usually mV. Gradients propagate throughVand thus through the upstream simulator.- test_amplitudestorch.Tensor
Test-pulse amplitudes with shape
(P,). These are the second-pulse amplitudes, not the conditioning-pulse amplitudes. Units are arbitrary but must matchbaseline_thresholdand any target threshold data.- isis_mstorch.Tensor
Interstimulus intervals with shape
(P,). Trials with the same ISI are grouped to define one recovery-cycle point.- dt_msfloat or torch.Tensor
Simulation time step in ms.
Simulations required to produce the input data#
For threshold recovery, run a batched grid such as:
for isi in ISIs:for amp in test_amplitudes_for_this_isi:simulate a conditioning pulse at
condition_pulse_time_msand a test pulse atcondition_pulse_time_ms + isi; store the voltage trace as one trial.
The conditioning pulse should usually be suprathreshold and fixed across trials. The test-pulse amplitude should span subthreshold and suprathreshold responses for each ISI. The readout compartments selected by
node_maskshould reflect the experimental endpoint: use distal compartments for propagation recovery, or local compartments for local excitability recovery.To normalize the threshold recovery cycle, separately simulate a single-pulse threshold experiment with the same test-pulse waveform and readout site but without the conditioning pulse. Pass that threshold as
baseline_threshold. It can be obtained with a compatible single-pulse threshold extractor, e.g. a fixed-pulse-width use ofchronaxie_from_trials.Timing convention#
If
test_pulse_times_msisNone, trialpusest_test[p] = condition_pulse_time_ms + isis_ms[p].If your simulations use absolute test-pulse times that differ from this convention, pass them directly via
test_pulse_times_ms. The test response is scored in[t_test + response_window_ms[0], t_test + response_window_ms[1]].For C-fibers or long axons, this window should be long enough for the test spike to reach the selected readout site.
- returns:
out – Main threshold-recovery outputs:
"isi_unique_ms"torch.Tensor, shape(D,)Sorted unique ISIs defining the recovery-cycle x-axis.
"I_th_test"torch.Tensor, shape(D,)Differentiable second-pulse threshold per ISI. The default method,
threshold_method="onset_midpoint", estimates the midpoint between the nearest inactive strength below onset and the lowest active strength."threshold_ratio"torch.Tensor or None, shape(D,)I_th_test / baseline_thresholdifbaseline_thresholdis supplied."threshold_percent_change"torch.Tensor or None, shape(D,)100 * (threshold_ratio - 1)ifbaseline_thresholdis supplied. Positive values indicate refractoriness; negative values indicate supernormality."p_response_trial"torch.Tensor, shape(P,)Smooth test-response confidence for each paired-pulse trial.
"p_response_by_isi"torch.Tensor, shape(D,)Group-level response confidence per ISI. This is most interpretable for fixed-amplitude paired-pulse success curves. For amplitude sweeps, it is a diagnostic summary across all tested amplitudes.
"isi_weight"torch.Tensor, shape(D,)Reliability weight per ISI. This is high when the group contains evidence of both low-strength non-activation and at least one activating trial.
"boundaries"dict[str, torch.Tensor]Per-ISI boundary diagnostics, each shape
(D,):I_on,I_pre_inactive,I_last_active,I_post_inactive, andI_block_mid. The last three are useful when high-amplitude block occurs.
Optional latency / velocity outputs:
"latency_ms_trial"and"latency_ms_by_isi"Test-spike latency relative to test-pulse onset, computed from a soft upstroke arrival time in the test-response window.
"latency_shift_ms"and"latency_shift_percent"Returned when
reference_latency_msis supplied."v_m_per_s_trial"and"v_m_per_s_by_isi"Optional velocity recovery estimates when
lengths_umis supplied. Velocity is computed by weighted regression of compartment position against soft test-spike arrival time.lengths_ummay be scalar, shape(C,), or shape(P, C)."velocity_percent_change"Returned when both
lengths_umandreference_velocity_m_per_sare supplied. Negative values correspond to conduction slowing.
Other diagnostics include
p_response_comp,p_dv_comp,test_pulse_times_ms,isi_group_id, latency effective sample size, arrival-time variance, andreg.- rtype:
dict[str, Any]
Notes
Outputs are differentiable with respect to
V. Grouping by ISI is discrete because ISIs are experimental design constants.If cathodic stimuli are negative-valued, pass
strength=-test_amplitudesso that larger strength means stronger stimulation. Alternatively setuse_abs_strength=True.If high-amplitude block can occur, prefer
threshold_method="onset"or"onset_midpoint". Avoid"bracket_midpoint"and monotonicity regularization under block because blocked high-amplitude trials are inactive but should not define the onset.For propagation recovery rather than local excitability, select distal readout compartments via
node_mask.
Examples
Threshold recovery curve with cathodic-negative second pulses:
>>> out = paired_pulse_recovery_from_trials( ... V_pair, amps_test, isis, dt_ms, ... condition_pulse_time_ms=5.0, ... strength=-amps_test, ... baseline_threshold=I0, ... node_mask=distal_mask, ... response_window_ms=(0.2, 8.0), ... ) >>> loss = ((out["threshold_ratio"] - target_ratio) ** 2).mean() + out["reg"]
Fixed-amplitude paired-pulse success curve:
>>> out = paired_pulse_recovery_from_trials( ... V_pair_fixed, amps_fixed, isis, dt_ms, ... condition_pulse_time_ms=5.0, ... enforce_min_trials_per_isi=False, ... node_mask=distal_mask, ... ) >>> p_success = out["p_response_by_isi"]
- plot_activation_heatmap_from_chronaxie_output(chron_out, amplitudes, *, mode='binary', p_thresh=0.5, agg='mean', amp_round_decimals=None, ax=None, show_colorbar=True, cmap=None, title=None, xlabel='Pulse width (ms)', ylabel='Amplitude', max_xticks=20, max_yticks=20, overlay_threshold=True, threshold_kind='I_th', overlay_points=True, overlay_line=True, overlay_bracket_band=False, threshold_line_kwargs=None, threshold_point_kwargs=None, bracket_line_kwargs=None, bracket_fill_kwargs=None, overlay_empirical_threshold=False, empirical_kind='all', empirical_use_thresholded_prob_in_prob_mode=True, empirical_low_kwargs=None, empirical_high_kwargs=None, empirical_mid_kwargs=None)[source]#
Plot an activation heatmap (activated vs non-activated) vs amplitude and pulse width, with optional overlays for (i) estimated strength-duration threshold curves and (ii) empirical threshold points derived directly from the binned heatmap.
This helper is intended to work with the dictionary output from
chronaxie_from_trials(...)(or a compatible estimator that returns per-trial activation confidences and pulse-width grouping information).The plot is constructed by binning trials onto a 2D grid:
x-axis: pulse width (ms)
y-axis: stimulus amplitude (or a monotone “strength” variable you pass as amplitudes)
cell value: activation (binary) or activation confidence (probability-like)
The plot include various overlays:
Estimated threshold curve overlay (overlay_threshold=True)
threshold_kind=”I_th” overlays chron_out[“I_th”] vs chron_out[“pw_unique_ms”]
threshold_kind=”fit” overlays the Lapicque curve
I_fit(d) = I_r * (1 + c / d)computed from chron_out[“rheobase”] and chron_out[“chronaxie_ms”]threshold_kind=”both” overlays both, if available
If overlay_bracket_band=True and chron_out[“bracket”] exists with keys “I_low” and “I_high”, the function can optionally overlay those bracket lines and a filled band between them.
Empirical threshold points overlay (overlay_empirical_threshold=True)
Empirical thresholds are derived directly from the binned heatmap grid, per pulse width:
lowest_active(d): the smallest amplitude level in that PW column with activation == 1
highest_inactive(d): the largest amplitude level with activation == 0
midpoint(d): 0.5*(lowest_active + highest_inactive), when both exist
These are useful to visually compare the estimator output (I_th / fit) against the “data-derived” boundary.
This assumes that “activation likelihood increases monotonically with amplitude/strength” within each pulse-width column. If your design violates this, empirical thresholds may be ambiguous (you can use the monotonicity regularizer during fitting, or inspect manually).
If a column has only active trials or only inactive trials (or missing data), the corresponding empirical threshold for that column will be undefined (NaN) and not plotted.
- Parameters:
chron_out (dict) –
Output dictionary from
chronaxie_from_trials(or equivalent). Required keys:"p_spike_trial"torch.Tensor, shape (P,)Smooth activation confidence per trial in (0, 1).
"pw_group_id"torch.Tensor, shape (P,)Integer group id mapping each trial to a pulse-width index.
"pw_unique_ms"torch.Tensor, shape (D,)Unique pulse widths (ms), sorted ascending.
Optional keys used for estimated-threshold overlays:
"I_th": torch.Tensor, shape (D,)"rheobase": torch.Tensor scalar (or float)"chronaxie_ms": torch.Tensor scalar (or float)"bracket": dict with keys"I_low","I_high"(each shape (D,))
amplitudes (array-like) –
Per-trial amplitude values with shape
(P,), aligned with the trials used to compute chron_out.Important sign/strength convention If your chronaxie estimator used a different monotone “strength” variable than raw amplitudes (e.g., strength = -amplitudes for cathodic negative pulses), you should pass that same strength array here. The heatmap y-axis and all overlays assume the same coordinate system.
mode ({"binary", "prob"}, default="binary") –
Heatmap cell values:
"binary": after aggregating p_spike within each (PW, amplitude) cell, mark activated if >= p_thresh."prob": show aggregated p_spike in [0, 1].
p_thresh (float, default=0.5) – Threshold used for binary heatmap mode, and also for empirical threshold extraction when mode=”prob” and empirical_use_thresholded_prob_in_prob_mode=True.
agg ({"mean", "max", "min"}, default="mean") – Aggregation rule when multiple trials map to the same (PW, amplitude) cell.
amp_round_decimals (int, optional) – If provided, amplitudes are grouped after rounding to this number of decimals.
ax (matplotlib.axes.Axes, optional) – Axes to plot into. If None, a new figure/axes is created.
show_colorbar (bool, default=True) – If True, add a colorbar.
cmap (matplotlib colormap, optional) – Colormap passed to pcolormesh. If None, matplotlib default is used.
title (str, optional) – Plot title. If None, a default is chosen from mode.
xlabel (str) – Axis labels.
ylabel (str) – Axis labels.
max_xticks (int, optional) – Maximum number of tick labels; values are subsampled for readability when exceeded.
max_yticks (int, optional) – Maximum number of tick labels; values are subsampled for readability when exceeded.
overlay_threshold (bool, default=True) – Overlay estimator-derived threshold curve(s).
threshold_kind ({"I_th", "fit", "both"}, default="I_th") – Which estimator-derived threshold curve(s) to overlay.
overlay_points (bool, default=True) – Plot threshold points at each pulse width.
overlay_line (bool, default=True) – Connect threshold points with a line.
overlay_bracket_band (bool, default=False) – Overlay the bracket band’s I_low/I_high lines and fill between them if available.
threshold_line_kwargs (dict, optional) – Matplotlib kwargs for overlay artists. Colors are not set explicitly by default.
threshold_point_kwargs (dict, optional) – Matplotlib kwargs for overlay artists. Colors are not set explicitly by default.
bracket_line_kwargs (dict, optional) – Matplotlib kwargs for overlay artists. Colors are not set explicitly by default.
bracket_fill_kwargs (dict, optional) – Matplotlib kwargs for overlay artists. Colors are not set explicitly by default.
overlay_empirical_threshold (bool, default=False) – If True, overlay empirical threshold points derived from the binned heatmap.
empirical_kind ({"lowest_active", "highest_inactive", "midpoint", "all"}, default="all") – Which empirical threshold points to overlay.
empirical_use_thresholded_prob_in_prob_mode (bool, default=True) – If mode=”prob”, compute empirical thresholds by thresholding the aggregated probabilities at p_thresh (i.e., treat >=p_thresh as active). If False, empirical overlay is skipped in prob mode unless mode=”binary”.
empirical_low_kwargs (dict, optional) –
Matplotlib kwargs for plotting empirical threshold points:
low (lowest_active): defaults to marker ‘^’
high (highest_inactive): defaults to marker ‘v’
mid (midpoint): defaults to marker ‘x’
Colors are not set explicitly by default.
empirical_high_kwargs (dict, optional) –
Matplotlib kwargs for plotting empirical threshold points:
low (lowest_active): defaults to marker ‘^’
high (highest_inactive): defaults to marker ‘v’
mid (midpoint): defaults to marker ‘x’
Colors are not set explicitly by default.
empirical_mid_kwargs (dict, optional) –
Matplotlib kwargs for plotting empirical threshold points:
low (lowest_active): defaults to marker ‘^’
high (highest_inactive): defaults to marker ‘v’
mid (midpoint): defaults to marker ‘x’
Colors are not set explicitly by default.
- Returns:
fig (matplotlib.figure.Figure) – Figure handle.
ax (matplotlib.axes.Axes) – Axes handle.
mesh (matplotlib.collections.QuadMesh) – Result of ax.pcolormesh.
grid (torch.Tensor) – The plotted grid, shape (A_unique, D). Values are NaN where no trials exist for a cell.
amp_unique (torch.Tensor) – Sorted unique amplitude levels used for y-axis binning, shape (A_unique,).
pw_unique_ms (torch.Tensor) – Sorted unique pulse widths used for x-axis binning, shape (D,).
Notes
This is a visualization utility; tensors are detached and moved to CPU.
If your trials do not form a full Cartesian grid, missing cells remain NaN and are masked.
For non-uniform amplitude/PW spacing, pcolormesh with computed bin edges preserves geometry.
Experimental event creation and removal#
Voltage-margin objectives for creating or extinguishing events require
additional carrier and hard-rerun checks. They remain available from
dendra.models.analysis.event_margin_training and are described in
Training event presence with voltage margins (experimental).