Stimulation and waveforms#
Use dendra.models.slice.Slice.inject() to attach an intracellular
waveform to selected sites. Supply extra=(field, waveform) or a list of
such pairs for extracellular stimulation. Intracellular current is in mA;
the extracellular field-waveform product is in mV. Overlapping intracellular
injections add, and each waveform retains its own parameters.
See Extracellular fields for field normalization and
Stimulation, input tapes and randomness for sampled inputs, Poisson replay,
and runtime-variable extracellular stimulation.
Waveform construction#
A waveform is a PyTorch module evaluated at times in milliseconds. Temporal parameters use milliseconds; amplitude units follow the stimulation target. Arithmetic composes waveforms without collapsing their parameter sources.
- class Waveform(**kwargs)[source]#
A parameterized temporal waveform evaluated at times in milliseconds.
Declare subclass parameters with
Waveform.PARAMETERand implementfn(). Call the instance, for examplewaveform(t), so registered PyTorch hooks are honored. Waveform outputs use time as the final axis; parameters can add leading batch or stimulus dimensions through broadcasting.- Parameters:
**kwargs – Values for parameters declared by the concrete waveform class.
Notes
Waveforms support addition, subtraction, multiplication, and division with other waveforms or numerical constants.
repeat()andpoisson()create repeated event trains without changing the original waveform. Amplitude units follow the target: intracellular current in mA, or the amplitude that makes an extracellular field-waveform product mV.Custom deterministic waveforms used in functional execution must not mutate module state or consume implicit randomness. This contract is trusted by default.
dn.ctx(CHECK_PURITY=True)enables diagnostics and requires an explicitFUNCTIONAL_PURE = Truedeclaration on each authored concrete class. Poisson wrappers use Dendra’s explicit sampling protocol.- fn(t)[source]#
Core waveform implementation. Must be implemented by subclasses.
Note
Although the waveform recipe needs to be defined within this function, one should call the
Waveforminstance afterwards instead of this since the former takes care of running any registered hooks while the latter silently ignores them.
- forward(t)[source]#
Evaluate
fn()on a Tensor time grid in milliseconds.- Parameters:
t (Tensor or array-like) – Evaluation times. A Tensor keeps its device; broadcasting within
fndetermines the result’s leading dimensions.- Returns:
Waveform samples with time on the final axis.
- Return type:
torch.Tensor
- repeat(freq, delay=0.0, off=inf, *, tau=0.01)[source]#
Return a periodically repeating copy of this waveform.
- Parameters:
freq (float) – Frequency of repetition in kHz.
delay (float, optional) – Delay before the first repetition in ms. Default is 0.0.
off (float, optional) – Time after which the waveform stops repeating in ms. Default is infinity. Initialize to a finite value to optimize the stop time.
tau (float or torch.Tensor, optional) – Sigmoid temperature in ms for surrogate gradients of the outer delay/off gate. Default is 0.01 ms. Forward values retain abrupt edges; gradients use a smooth approximation around each edge. This is independent of any edge temperature on the repeated waveform.
- Returns:
A waveform that repeats periodically according to the specified parameters.
- Return type:
_repeat
- poisson(interval, n=10, start=0.0, noise=1.0, off=inf, randomize_every_call=False, generator=None, **kwargs)[source]#
Return a Poisson-distributed copy of this waveform.
- Parameters:
interval (float) – Mean interval between events in ms.
n (int, optional) – Number of events to generate. Default is 10.
start (float, optional) – Start time in ms. Default is 0.0.
noise (float, optional) – Noise factor for interval variability. Default is 1.0.
off (float, optional) – Time after which the waveform stops. Default is infinity.
randomize_every_call (bool, optional) – If True, generates a new Poisson schedule on each call. Default is False.
generator (Optional[torch.Generator], optional) – A PyTorch random number generator for reproducibility. Default is None.
- Returns:
A waveform that follows a Poisson distribution according to the specified parameters.
- Return type:
_poisson
- assemble(start, end, dt)[source]#
Evaluate this waveform on the endpoint-exclusive grid
[start, end).- Parameters:
start (float) – Time bounds in milliseconds.
end (float) – Time bounds in milliseconds.
dt (float) – Time spacing in milliseconds.
- Returns:
Samples on a grid using the waveform’s parameter or buffer device/dtype.
- Return type:
torch.Tensor
- class constant(**kwargs)[source]#
Constant amplitude broadcast over the evaluation time grid.
- Parameters:
value (float or Tensor, default 0.0) – Output amplitude, in units determined by the stimulation target.
Notes
For a one-dimensional time grid of length
T, a scalar produces[T]. A non-scalar value gains a final time axis unless it already ends in a singleton dimension. That trailing1is an explicit time axis even for rank-three or higher values:[B, N, C, 1]produces[B, N, C, T]. The value is not interpreted as time-varying because an axis happens to have lengthT.Examples
>>> import dendra as dn >>> waveform = dn.constant(value=5.0)
- class sin(**kwargs)[source]#
Sinusoidal waveform generator.
Generates either a single sinusoid or a sum of sinusoidal oscillator components. Each component is active on the half-open interval
delay <= t < min(off, delay + off_after)and zero elsewhere.- Parameters:
amp (float or torch.Tensor, optional) – Amplitude in the desired output units (for example, mA for a current waveform). Default is 1.0.
freq (float or torch.Tensor, optional) – Frequency in kHz (equivalently, ms⁻¹). For example, use
100 * dendra.units.Hzfor 100 Hz. Default is 1.0 kHz.phase (float or torch.Tensor, optional) – Phase offset in radians. Default is 0.0.
delay (float or torch.Tensor, optional) – Start time in ms. Default is 0.0.
off (float or torch.Tensor, optional) – Absolute off time in ms. Default is infinity.
off_after (float or torch.Tensor, optional) – Off time relative to delay, in ms. The effective off time is
min(off, delay + off_after). Default is infinity.tau (float or torch.Tensor, optional) – Sigmoid temperature in ms for differentiable delay/off edges. The forward pass uses a hard gate with soft straight-through gradients. Default is 0.01 ms.
Notes
For
amp,freq,phase,delay,off,off_after, andtau:scalar: one oscillator component, output shape
[T].[K]:Koscillator components, summed to output shape[T].[B, K]:Bbatches ofKoscillator components, summed over components to output shape[B, T].For rank three or higher, a final dimension of length
1orTis an explicit time axis. The preceding axis contains components, which are summed, leaving output shape[..., T].Otherwise a time axis is appended and the final parameter axis contains components. Include an explicit time axis to avoid ambiguity when the component count equals
T.
A trailing singleton is therefore not an additional batch axis. For one component over two leading axes, use parameter shape
[B, N, 1, 1];[B, N, 1]instead treatsNas the component axis and sums it. These conventions describe evaluation on a one-dimensional time grid.Timing parameters use surrogate gradients while the forward waveform keeps abrupt edges.
delaymoves both the onset gate and the carrier phase; whenoff_afterdetermines the stop,delaymoves that edge too. Only the earlier ofoffanddelay + off_afterreceives the stop gradient; equal finite cutoffs split it equally. Initialize a cutoff to a finite value to optimize it. An infinite cutoff has zero gradient. Enable gradients on the waveform parameters to be optimized, for examplewaveform.delay.requires_grad_(True). Samples near an edge supply its gradient, so ataumuch smaller than the sampling interval can make edge contributions numerically negligible.Scalars and singleton dimensions broadcast over components and batches. For example,
delaywith shape[B, 1]gives one delay per batch, shared by all components in that batch.For component
k:\[y_k(t) = a_k g_k(t) \sin(2\pi f_k (t - d_k) + \phi_k)\]and the returned waveform is
sum_k y_k(t).Examples
>>> import torch >>> import dendra as dn >>> from dendra.units import Hz, ms >>> t = torch.linspace(0, 100 * ms, 1000) >>> waveform = dn.sin(amp=2.0, freq=10 * Hz) >>> values = waveform(t) # [T]
>>> waveform = dn.sin( ... amp=torch.tensor([1.0, 0.5, 0.25]), ... freq=torch.tensor([5.0, 7.0, 11.0]) * Hz, ... ) >>> values = waveform(t) # [T], sum of 3 components
>>> waveform = dn.sin( ... amp=torch.ones(4, 3), ... freq=torch.tensor([[5.0, 7.0, 11.0]]).expand(4, 3) * Hz, ... ) >>> values = waveform(t) # [4, T], 4 batched multitone waveforms
- class cos(**kwargs)[source]#
Cosine waveform generator.
Generates either a single cosine or a sum of cosine oscillator components. Each component is active on the half-open interval
delay <= t < min(off, delay + off_after)and zero elsewhere.- Parameters:
amp (float or torch.Tensor, optional) – Amplitude in the desired output units (for example, mA for a current waveform). Default is 1.0.
freq (float or torch.Tensor, optional) – Frequency in kHz (equivalently, ms⁻¹). For example, use
100 * dendra.units.Hzfor 100 Hz. Default is 1.0 kHz.phase (float or torch.Tensor, optional) – Phase offset in radians. Default is 0.0.
delay (float or torch.Tensor, optional) – Start time in ms. Default is 0.0.
off (float or torch.Tensor, optional) – Absolute off time in ms. Default is infinity.
off_after (float or torch.Tensor, optional) – Off time relative to delay, in ms. The effective off time is
min(off, delay + off_after). Default is infinity.tau (float or torch.Tensor, optional) – Sigmoid temperature in ms for differentiable delay/off edges. The forward pass uses a hard gate with soft straight-through gradients. Default is 0.01 ms.
Notes
For
amp,freq,phase,delay,off,off_after, andtau:scalar: one oscillator component, output shape
[T].[K]:Koscillator components, summed to output shape[T].[B, K]:Bbatches ofKoscillator components, summed over components to output shape[B, T].For rank three or higher, a final dimension of length
1orTis an explicit time axis. The preceding axis contains components, which are summed, leaving output shape[..., T].Otherwise a time axis is appended and the final parameter axis contains components. Include an explicit time axis to avoid ambiguity when the component count equals
T.
A trailing singleton is therefore not an additional batch axis. For one component over two leading axes, use parameter shape
[B, N, 1, 1];[B, N, 1]instead treatsNas the component axis and sums it. These conventions describe evaluation on a one-dimensional time grid.Timing parameters use surrogate gradients while the forward waveform keeps abrupt edges.
delaymoves both the onset gate and the carrier phase; whenoff_afterdetermines the stop,delaymoves that edge too. Only the earlier ofoffanddelay + off_afterreceives the stop gradient; equal finite cutoffs split it equally. Initialize a cutoff to a finite value to optimize it. An infinite cutoff has zero gradient. Enable gradients on the waveform parameters to be optimized, for examplewaveform.delay.requires_grad_(True). Samples near an edge supply its gradient, so ataumuch smaller than the sampling interval can make edge contributions numerically negligible.Scalars and singleton dimensions broadcast over components and batches. For example,
delaywith shape[B, 1]gives one delay per batch, shared by all components in that batch.For component
k:\[y_k(t) = a_k g_k(t) \cos(2\pi f_k (t - d_k) + \phi_k)\]and the returned waveform is
sum_k y_k(t).Examples
>>> import torch >>> import dendra as dn >>> from dendra.units import Hz, ms >>> t = torch.linspace(0, 100 * ms, 1000) >>> waveform = dn.cos(amp=2.0, freq=10 * Hz) >>> values = waveform(t) # [T]
>>> waveform = dn.cos( ... amp=torch.tensor([1.0, 0.5, 0.25]), ... freq=torch.tensor([5.0, 7.0, 11.0]) * Hz, ... ) >>> values = waveform(t) # [T], sum of 3 components
>>> waveform = dn.cos( ... amp=torch.ones(4, 3), ... freq=torch.tensor([[5.0, 7.0, 11.0]]).expand(4, 3) * Hz, ... ) >>> values = waveform(t) # [4, T], 4 batched multitone waveforms
- class mono_rect(**kwargs)[source]#
A rectangular pulse on the half-open interval
[delay, delay + pw).- Parameters:
amp (float or Tensor, default 1.0) – Pulse amplitude in the desired output units, such as mA for current.
delay (float or Tensor, default 0.0) – Pulse onset in milliseconds.
pw (float or Tensor, default 1.0) – Pulse width in milliseconds.
tau (float or Tensor, default 0.1) – Sigmoid temperature in milliseconds for surrogate edge gradients.
Notes
The forward value is
ampwhendelay <= t < delay + pwand zero elsewhere. The forward edges remain abrupt; backward evaluation uses the sigmoid gate, withtauclamped to at least 1e-6 ms.For a one-dimensional time grid of length
T, scalar parameters produce[T]. Non-scalar parameters gain a final time axis unless they already end in a singleton dimension. That trailing1is the explicit time axis even for tensors of rank three or higher. For example,[B, N, C, 1]retains all three leading axes and produces[B, N, C, T], including whenC=1. Parameter dimensions broadcast together before evaluation.Examples
>>> import torch >>> import dendra as dn >>> waveform = dn.mono_rect(amp=-2.0, pw=0.5) >>> values = waveform(torch.linspace(0, 2, 100))
- class bi_rect(**kwargs)[source]#
Two rectangular phases with independently configured amplitudes and widths.
- Parameters:
amp1 (float or Tensor, default -1.0) – First-phase amplitude in the desired output units.
amp2 (float or Tensor, default 1.0) – Second-phase amplitude in the same units.
delay (float or Tensor, default 0.0) – First-phase onset in milliseconds.
pw1 (float or Tensor, default 1.0) – First-phase width in milliseconds.
pw2 (float or Tensor, default 1.0) – Second-phase width in milliseconds.
interval (float or Tensor, default 0.0) – Gap between the first-phase stop and second-phase start, in milliseconds.
tau (float or Tensor, default 0.1) – Sigmoid temperature in milliseconds for surrogate edge gradients.
Notes
The phases occupy
[delay, delay + pw1]and[delay + pw1 + interval, delay + pw1 + interval + pw2]. Both endpoints are included and the phase contributions add wherever they overlap. Thusinterval=0returnsamp1 + amp2at the shared boundary.Parameter broadcasting and the hard-forward/surrogate-gradient edge contract follow
mono_rect. In particular, a trailing singleton parameter dimension is an explicit time axis.Examples
>>> import dendra as dn >>> waveform = dn.bi_rect(amp1=-2.0, amp2=1.0, pw1=0.5, pw2=1.0)
- class bi_rect_balanced(**kwargs)[source]#
Biphasic rectangular pulse with equal and opposite continuous phase areas.
- Parameters:
amp (float or Tensor, default 1.0) – First-phase amplitude in the desired output units.
delay (float or Tensor, default 0.0) – First-phase onset in milliseconds.
pw1 (float or Tensor, default 1.0) – First-phase width in milliseconds.
pw2 (float or Tensor, default 1.0) – Second-phase width in milliseconds. Use positive widths for charge balance.
interval (float or Tensor, default 0.0) – Gap between the phases in milliseconds.
tau (float or Tensor, default 0.1) – Sigmoid temperature in milliseconds for surrogate edge gradients.
Notes
The first phase has amplitude
ampand the second has amplitude-amp * pw1 / max(pw2, 1e-12). The phases occupy the same inclusive intervals asbi_rect; contributions add at overlapping endpoints. Charge balance describes the continuous pulse areas for widths above the denominator’s 1e-12 ms floor, rather than an exact sum on every sampled grid.Parameter broadcasting and surrogate gradients follow
mono_rect, including the explicit trailing singleton time axis.Examples
>>> import dendra as dn >>> waveform = dn.bi_rect_balanced(amp=2.0, pw1=0.5, pw2=1.0)
- class bi_rect_symm(**kwargs)[source]#
Biphasic rectangular pulse with equal widths and opposite amplitudes.
- Parameters:
amp (float or Tensor, default 1.0) – First-phase amplitude; the second phase has amplitude
-amp.delay (float or Tensor, default 0.0) – First-phase onset in milliseconds.
pw (float or Tensor, default 1.0) – Width of each phase in milliseconds.
interval (float or Tensor, default 0.0) – Gap between the phases in milliseconds.
tau (float or Tensor, default 0.1) – Sigmoid temperature in milliseconds for surrogate edge gradients.
Notes
The phases occupy
[delay, delay + pw]and[delay + pw + interval, delay + 2*pw + interval]. Both endpoints are included; opposite contributions cancel at the shared boundary wheninterval=0. The continuous phase areas are equal and opposite.Parameter broadcasting and surrogate gradients follow
mono_rect, including the explicit trailing singleton time axis.Examples
>>> import dendra as dn >>> waveform = dn.bi_rect_symm(amp=2.0, pw=0.5, interval=0.1)
- class arbitrary(**kwargs)[source]#
Piecewise-linear waveform through supplied time/amplitude samples.
- Parameters:
values (array-like or Tensor, optional) – Amplitudes at the interpolation knots. Shape
[Q]or[B, Q]; defaults to[0.0, 0.0].tpoints (array-like or Tensor, optional) – Corresponding knot times in milliseconds, sorted in ascending order. Shape
[Q]or[B, Q]; defaults to[0.0, 1.0]. Use at least two distinct knots. One shared row can broadcast over amplitude rows.
Notes
Values outside the knot range are zero; values at the endpoints are retained. A one-dimensional evaluation grid of length
Tproduces[T]for one unbatched table, or[B, T]for batched tables. Knot values and times must have matching final dimensions and broadcastable row counts.Gradients propagate through amplitudes, knot times, and query times within the selected interpolation segments. Segment selection is discrete; preserve sorted knot order when optimizing times.
Examples
>>> import dendra as dn >>> waveform = dn.arbitrary(tpoints=[0.0, 0.5, 1.0], values=[0.0, 1.0, 0.0])
- energy(waveform, t=None, *, tstart=0.0, tstop=None, dt=None, include_endpoint=False, time_scale=0.001, resistance=None, mode='current', method='trapezoid')[source]#
Compute waveform energy by integrating the squared waveform over time.
This function is intentionally numerical rather than analytic. It therefore works for scalar sin/cos, multitone sin/cos, batched multitone sin/cos, and any other Waveform whose output has time on the last dimension.
- Parameters:
waveform (callable) – Waveform/module to evaluate. For example,
sin(...)orcos(...).t (torch.Tensor, optional) – Explicit time vector. If omitted,
tstart,tstop, anddtare used to construct one. Times should use the same unit as the waveform’s delay/off/frequency convention, usually milliseconds in dendra.tstart (float, optional) – Start time for an internally constructed grid. Default is 0.0.
tstop (float, optional) – Stop time for an internally constructed grid. Required if
tis not supplied. The default grid is endpoint-exclusive.dt (float, optional) – Time step for an internally constructed grid. Required if
tis not supplied.include_endpoint (bool, optional) – Include
tstopin the constructed grid. Default is False.time_scale (float, optional) – Multiplier converting the supplied time unit to seconds. For ms, use
1e-3. For seconds, use1.0. Default is1e-3.resistance (float or torch.Tensor, optional) – If provided, convert the normalized integral to physical energy using
mode.mode ({'current', 'voltage'}, optional) – Unit interpretation. With
resistance=None, the return value is justintegral waveform(t)^2 dt_seconds. If waveform is current in amps, this has units J/Ohm. If waveform is voltage in volts, this has units J*Ohm. With resistance supplied,mode='current'returnsR * integral I^2 dtin joules, whilemode='voltage'returnsintegral V^2/R dtin joules.method ({'trapezoid', 'left', 'right'}, optional) – Quadrature method. Default is trapezoid.
- Returns:
Energy integrated over the last/time dimension. For a scalar waveform this is a scalar tensor. For a batched waveform with output
[B, T], this has shape[B].- Return type:
torch.Tensor
Examples
>>> w = sin(amp=1.0, freq=5.0, off_after=10.0) >>> e_norm = energy(w, tstop=10.0, dt=0.005) # integral I^2 dt_seconds
>>> w = sin(amp=torch.ones(4, 3), freq=torch.ones(4, 3) * 5.0) >>> e_norm = energy(w, tstop=1.0, dt=0.005) # shape [4]
Stimulation handlers#
The execution methods create these handlers from the model’s registered
injections and supplied extracellular configuration. Most users work through
Slice.inject, extra= and dendra.func.Inputs.
- class Intra(model, stims)[source]#
Build an intracellular-current handler from registered waveform injections.
- Parameters:
model (Population) – Receiver whose voltage shape, device, and dtype define the current layout.
stims (sequence of tuple) – Registered
(waveform, label, indices)triples supplying current in mA. Overlapping injections add. Most users configure these throughdendra.models.slice.Slice.inject().
- __call__(stims, inds)[source]#
Compute total intracellular current at the given time index.
This method is called by the model during simulation to get the total intracellular current for the current time step.
- Parameters:
idx (int) – Current time index in the simulation.
vm (torch.Tensor) – Current membrane potential values.
- Returns:
Tensor of intracellular current values with the full model shape
[*batch, n_cells, n_comps]. Each per-step waveform value may be scalar, exactly match its indexed selection, use ordinary trailing broadcasting, or (when that fails) broadcast over explicit batch axes ([B]to[B, 1, 1]). Use explicit singleton axes when equal-sized batch and spatial axes would otherwise be ambiguous.- Return type:
torch.Tensor
- class Extra(field_waveform_tuples, precomputed=None)[source]#
Handles extracellular stimulation for models.
Initialize extracellular stimulation handler.
- Parameters:
field_waveform_tuples (list of (torch.Tensor, Waveform)) – Each tuple contains a spatial field (shape (n_cell, n_comp)) and a temporal waveform (Waveform instance).
precomputed (torch.Tensor, optional) – Spatial-first, time-last extracellular voltage in mV. When supplied,
field_waveform_tuplesis ignored.