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.PARAMETER and implement fn(). Call the instance, for example waveform(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() and poisson() 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 explicit FUNCTIONAL_PURE = True declaration 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 Waveform instance 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 fn determines 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 trailing 1 is 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 length T.

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.Hz for 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, and tau:

  • scalar: one oscillator component, output shape [T].

  • [K]: K oscillator components, summed to output shape [T].

  • [B, K]: B batches of K oscillator components, summed over components to output shape [B, T].

  • For rank three or higher, a final dimension of length 1 or T is 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 treats N as 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. delay moves both the onset gate and the carrier phase; when off_after determines the stop, delay moves that edge too. Only the earlier of off and delay + off_after receives 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 example waveform.delay.requires_grad_(True). Samples near an edge supply its gradient, so a tau much smaller than the sampling interval can make edge contributions numerically negligible.

Scalars and singleton dimensions broadcast over components and batches. For example, delay with 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.Hz for 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, and tau:

  • scalar: one oscillator component, output shape [T].

  • [K]: K oscillator components, summed to output shape [T].

  • [B, K]: B batches of K oscillator components, summed over components to output shape [B, T].

  • For rank three or higher, a final dimension of length 1 or T is 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 treats N as 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. delay moves both the onset gate and the carrier phase; when off_after determines the stop, delay moves that edge too. Only the earlier of off and delay + off_after receives 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 example waveform.delay.requires_grad_(True). Samples near an edge supply its gradient, so a tau much smaller than the sampling interval can make edge contributions numerically negligible.

Scalars and singleton dimensions broadcast over components and batches. For example, delay with 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 amp when delay <= t < delay + pw and zero elsewhere. The forward edges remain abrupt; backward evaluation uses the sigmoid gate, with tau clamped 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 trailing 1 is 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 when C=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. Thus interval=0 returns amp1 + amp2 at 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 amp and the second has amplitude -amp * pw1 / max(pw2, 1e-12). The phases occupy the same inclusive intervals as bi_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 when interval=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 T produces [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(...) or cos(...).

  • t (torch.Tensor, optional) – Explicit time vector. If omitted, tstart, tstop, and dt are 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 t is not supplied. The default grid is endpoint-exclusive.

  • dt (float, optional) – Time step for an internally constructed grid. Required if t is not supplied.

  • include_endpoint (bool, optional) – Include tstop in 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, use 1.0. Default is 1e-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 just integral 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' returns R * integral I^2 dt in joules, while mode='voltage' returns integral V^2/R dt in 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 through dendra.models.slice.Slice.inject().

init(t)[source]#
__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_tuples is ignored.

forward()[source]#