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. Use set_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. With block_possible=True, the search uses peak voltage to distinguish a subthreshold response from possible conduction block. Native execution obtains the peak with Recorder.

The search uses the model’s device and dtype without gradient tracking. float() and double() 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 in dn.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 with time when bases is not provided.

  • time (Optional[Waveform], optional) – Temporal waveform of the stimulus. When used with space, the effective extracellular potential passed to the model is space * amp, with a final singleton compartment axis added to amp. Thus one independently searched amplitude is maintained for every batch and population lane. Compiled runners require extra=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 to model.shape. The historical unbatched layout (model.np, nt, model.nc) is accepted when the canonical interpretation is not possible. Ambiguous layouts are rejected. When bases is provided, space and time are ignored and chunklength cannot 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]. If None, upper bounds are initialised heuristically from model.diameters using 0.2 / (diameter / 5)**2 per element. Either ub must be provided or model.diameters must be set. Compiled runners require an explicit ub instead of reading native geometry.

  • lb (optional) – Initial lower bound(s) on threshold amplitudes, broadcastable to model.shape[:-1]. If None, 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=True and the response suggests conduction block. The default is 0.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 below rtol (and the absolute criterion, if given, is also satisfied).

  • chunklength (optional) – Chunk length (in time steps) to use when calling longrun() instead of run() for long native simulations, by default None. Configure compiled kernel width with chunk_steps in dn.compile instead.

  • 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 a Recorder(("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 call calculate_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.shape means the underlying Population shape. For a compiled runner, read it from program.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.compile and match them in set_partition(). Supply atol, 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_partition gives positive group lengths covering the complete compartment axis. active_partition gives 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.

reset_bounds()[source]#

Reset upper and lower bounds to initial values.

float()[source]#

Use float32 for native thresholding; compiled dtype must already match.

double()[source]#

Use float64 for native thresholding; compiled dtype must already match.

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 named peak diagnostic and a built-in activity threshold or block_threshold.

  • reset_bounds (bool, optional) – Whether to reset upper and lower bounds to initial values before calculation, by default True. Set to False to continue a previous calculation, e.g., with tighter tolerances.

  • atol (optional) – Absolute tolerance for the threshold interval ub - lb. If None, 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) after set_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