Activation threshold searches#
Use Thresholder to find the
amplitude that activates each cell. With a Population, activity callback,
spatial voltage and waveform, call
calculate_thresholds()
to obtain the upper and lower bounds.
from dendra.models.instruments import Thresholder
search = Thresholder(
model, active, space=spatial_voltage, time=waveform, ub=1.0, atol=0.001,
)
upper, lower = search.calculate_thresholds(tstop=10.0, dt=0.025)
For a compiled Population runner, pass the name of its activity callback.
See Run models with explicit state and the runnable
thresholding example.
- class Thresholder(model, active, space=None, time=None, bases=None, ub=None, lb=None, fix_bound_up=2.0, fix_bound_down=0.1, max_tries_bound_fix=10, max_tries_thresh=25, atol=None, rtol=None, chunklength=None, mode='arithmetic', *, peak=None, block_threshold=None)[source]#
Compute activation thresholds for a native or compiled Population.
Supply a spatial voltage and a
Waveform, or a precomputed spatiotemporal basis. The search scales this stimulus with a separate amplitude for each cell and batch entry. Useset_partition()to search separately over groups of compartments.calculate_thresholds()brackets the activation threshold between a subthreshold lower bound and an activating upper bound. It narrows the interval until the requested tolerances are met. Withblock_possible=True, the search uses peak voltage to distinguish a subthreshold response from possible conduction block. Native execution obtains the peak withRecorder.The search uses the model’s device and dtype without gradient tracking.
float()anddouble()change the dtype for native models. For a compiled runner, choose the dtype before compiling.- Parameters:
model (dendra.models.Population or dendra.func.CompiledRunner) – Native Population or the Population runner returned by
dn.compile. Compiled Network runners are currently unsupported.active (ThresholdCallback or str) – Native activity callback implementing
is_active(partition=...), or the name of a compiled callback returning one Boolean Tensor entry per search lane. Compiled callbacks are configured indn.compile.space (Optional[Union[npt.NDArray, Tensor]], optional) – Spatial extracellular potential distribution of the stimulus. It must be broadcastable to
model.shape == (*batch, model.np, model.nc). Used together withtimewhenbasesis not provided.time (Optional[Waveform], optional) – Temporal waveform of the stimulus. When used with
space, the effective extracellular potential passed to the model isspace * amp, with a final singleton compartment axis added toamp. Thus one independently searched amplitude is maintained for every batch and population lane. Compiled runners requireextra=dn.VarInput().bases (Optional[Union[npt.NDArray, Tensor]], optional) – Precomputed spatiotemporal bases for the extracellular potential. The canonical layout is time-first,
(nt, *model.shape); payload axes after time may broadcast tomodel.shape. The historical unbatched layout(model.np, nt, model.nc)is accepted when the canonical interpretation is not possible. Ambiguous layouts are rejected. Whenbasesis provided,spaceandtimeare ignored andchunklengthcannot be used. A compiled runner must have no bound extracellular stimulus; the basis length supplies its trial step count.ub (optional) – Initial upper bound(s) on threshold amplitudes, broadcastable to
model.shape[:-1]. IfNone, upper bounds are initialised heuristically frommodel.diametersusing0.2 / (diameter / 5)**2per element. Eitherubmust be provided ormodel.diametersmust be set. Compiled runners require an explicitubinstead of reading native geometry.lb (optional) – Initial lower bound(s) on threshold amplitudes, broadcastable to
model.shape[:-1]. IfNone, lower bounds are initialised to zero.fix_bound_up (float, optional) – Multiply the upper bound by this factor for a subthreshold response. The default is
2.0. The factor must exceed one.fix_bound_down (float, optional) – Multiply the upper bound by this factor when
block_possible=Trueand the response suggests conduction block. The default is0.1. The factor must be between zero and one.max_tries_bound_fix (int, optional) – Maximum number of attempts to repair the upper bounds before giving up and marking an element as ignored, by default
10.max_tries_thresh (int, optional) – Maximum number of bisection iterations per element, by default
25.atol (optional) – Absolute tolerance for the threshold interval
ub - lb. The search stops for an element once the absolute window falls below this value (and the relative criterion, if given, is also satisfied).rtol (optional) – Relative tolerance for the threshold interval, defined as
(ub - lb) / ub. The search stops for an element once this falls belowrtol(and the absolute criterion, if given, is also satisfied).chunklength (optional) – Chunk length (in time steps) to use when calling
longrun()instead ofrun()for long native simulations, by defaultNone. Configure compiled kernel width withchunk_stepsindn.compileinstead.mode ({"arithmetic", "geometric"}, optional) – Arithmetic mode tests the midpoint of the bounds and is the default. Geometric mode tests their geometric mean and requires strictly positive lower and upper bounds.
peak (str, optional) – Name of the compiled callback used by
block_possible=True. Supply aRecorder(("v",), max_only=True)recording every solver step, or a custom pure callback returning a floating-point peak voltage per search lane. The Recorder’s partition must match the model partition.block_threshold (float, optional) – Voltage cutoff for compiled conduction-block diagnostics. Omission uses the selected built-in activity callback’s voltage threshold. Custom activity callbacks require an explicit cutoff when block checking is used.
Examples
Given a
Population, define a spatial field and temporal waveform, and then callcalculate_thresholds():import numpy as np import dendra as dn from dendra.models.instruments import Thresholder # Assume ``model`` is an existing Population with diameters defined model = ... # type: dendra.models.Population # Build a simple temporal waveform (e.g., a Gaussian-like pulse) tstop = 5.0 dt = 0.005 times = np.arange(0.0, tstop, dt) values = np.exp(-0.5 * ((times - 1.0) / 0.2) ** 2) stim = dn.arbitrary(values=values, tpoints=times) # Compute the spatial extracellular potential at each compartment field = dn.anisotropic_point(z=200.0, rhox=100.0, rhoz=100.0) ve_space = field(model) # shape (model.np, model.nc) # Define an activity callback that detects spikes in a subset of nodes active = dn.callbacks.ActiveAL( threshold=20.0, node_check=list(range(model.nc))[::20], at_least=5, ) # Set up the thresholder and compute thresholds to 1% relative accuracy thresholder = Thresholder( model=model, active=active, space=ve_space, time=stim, ub=1.0, rtol=0.01, ) thr_ub, thr_lb = thresholder.calculate_thresholds(tstop=tstop, dt=dt) # ``thr_ub`` and ``thr_lb`` now contain per-element bounds on the # stimulus amplitude required to elicit an action potential.
Notes
model.shapemeans the underlying Population shape. For a compiled runner, read it fromprogram.functional.shape.Each amplitude trial starts independently. Native trials initialize the model. Compiled trials use the runner’s snapshot or fresh policy and run every configured callback. Snapshot policy repeats the captured neural and RNG states. Fresh policy follows the runner’s resampling settings.
Configure compiled activity partitions before
dn.compileand match them inset_partition(). Supplyatol,rtol, or both. A NaN in the stimulus excludes the affected cell or partition from the search. Excluded stimulus values are replaced with zero during trials.- set_partition(model_partition, active_partition=None)[source]#
Append a search axis for contiguous compartment groups.
model_partitiongives positive group lengths covering the complete compartment axis.active_partitiongives the corresponding lengths in the activity callback’s checked-node axis; omission uses the model lengths. Compiled callback partitions must already match these groups. Bound configuration is validated without changing the runner.
- check_active_with_rec(tstop, dt, bound)[source]#
Return activity and peak voltage for an independent amplitude trial.
- calculate_thresholds(tstop=None, dt=None, block_possible=False, reset_bounds=True, atol=None, rtol=None)[source]#
Search for the upper and lower activation bounds.
- Parameters:
tstop (float, optional) – Absolute simulation stop time in milliseconds. Omission on a compiled runner uses its configured horizon. An explicit stop is measured from its snapshot clock, or zero for fresh initialization. Basis trials use their tape length and ignore this argument.
dt (float, optional) – Simulation time step in milliseconds. Compiled runners use their effective timestep; an explicit value must match it. Native calls retain the timestep behavior of
Population.run.block_possible (bool, optional) – Whether to consider conduction block when fixing upper bounds, by default
False. Compiled execution requires a namedpeakdiagnostic and a built-in activity threshold orblock_threshold.reset_bounds (bool, optional) – Whether to reset upper and lower bounds to initial values before calculation, by default
True. Set toFalseto continue a previous calculation, e.g., with tighter tolerances.atol (optional) – Absolute tolerance for the threshold interval
ub - lb. IfNone, the value provided at construction is used.rtol (optional) – Relative tolerance for the threshold interval. If
None, the value provided at construction is used.
- Returns:
upper, lower – Upper and lower threshold bounds, in that order, on CPU. Both have shape
model.shape[:-1], or(*model.shape[:-1], n_partitions)afterset_partition(). Entries are NaN for cells or partitions excluded by NaN stimulus values, unsuccessful bound fixing, or failure to meet the requested tolerances within the iteration limit.- Return type:
torch.Tensor