Callbacks and recording#

Pass dn.Recorder or a callback from dn.callbacks to native execution. Recorder, LFP, threshold and activity callbacks, and Population scopes also work with functional execution. For custom callbacks, implement dendra.func.FunctionalCallback or derive from dn.callbacks.Callback for native hooks. See Recording and online analysis for usage and result shapes.

Recording#

class Recorder(states, max_only=False, node_indices=None, dt=None, partition=None, *, region=None)[source]#

Record and store model states during simulation.

This callback records specified model states (membrane potentials, ion concentrations, channel states, etc.) at regular intervals during simulation. It can save data directly in memory or cache to HDF5 files for large-scale simulations.

Parameters:
  • states (list of str) – List of state names to record. Can be model attributes (e.g., ‘v’) or mechanism states (e.g., ‘hh.m’).

  • max_only (bool, optional) – If True, only the maximum value across the final compartment axis is recorded for each state. All leading batch and population axes are preserved. Default is False.

  • node_indices (list of int, optional) – Indices of specific nodes to record. If None, all nodes are recorded. Default is None.

  • dt (float, optional) – Recording interval, converted to the integer stride int(dt/model.dt) without rounding. Default is None (record every step). A fresh in-memory recording retains the initial boundary, then post-step frames stride, 2 * stride, and so on.

  • partition (sequence of int, optional) – With max_only=True, contiguous segment lengths along the final compartment axis. One maximum per segment is appended as the final output axis.

  • region (Slice, optional) – Physical Population coordinates to select for v, vc, and i_membrane. Scalar t is left unchanged. Cannot be combined with node indices, maximum reduction, or partitions.

Notes

Apply temporal filtering or averaging to the recorded tensors as a separate postprocessing step.

For large-scale simulations, use the set_hdf5 method to enable caching to an HDF5 file, which helps manage memory usage.

states#

List of state names being recorded.

Type:

list of str

rec#

Dictionary mapping state names to lists of recorded tensors.

Type:

dict

save_dt#

Recording time step.

Type:

float

save_every#

Number of simulation steps between recordings.

Type:

int

i#

Current step counter.

Type:

int

hdf5_path#

Path to HDF5 file if using HDF5 storage.

Type:

str

cache_with_hdf5#

Whether to cache data to HDF5 file.

Type:

bool

cache_every#

Number of steps between HDF5 cache operations.

Type:

int

set_partition(partition=None)[source]#
property dt#
set_hdf5(hdf5, cache_every=10000)[source]#

Write recorded samples to HDF5 with bounded host buffering.

Parameters:
  • hdf5 (str) – Destination file path.

  • cache_every (int, default 10000) – Positive number of solver iterations between flushes. A fresh recording session also counts its initial boundary. Recorder dt selects which samples are retained independently of this flush interval.

Returns:

This recorder for method chaining.

Return type:

Recorder

Notes

Call close() to finish writing before reading the file with dendra.data.H5Reader. HDF5 storage detaches samples from autograd; use in-memory results when the recorded values must retain gradients.

reset()[source]#

Reset the recorder’s state.

This method clears all recorded data and resets the step counter. It’s useful when you want to reuse the same recorder instance for multiple simulation runs without the data from previous runs.

Parameters:

None

Return type:

None

See also

close

Close resources used by the recorder

Examples

>>> recorder = Recorder(['v'])
>>> model.run(ve, callbacks=[recorder])
>>> # Get data from first run
>>> first_run_data = recorder.numpy()
>>> # Reset recorder for another run
>>> recorder.reset()
>>> model.run(ve2, callbacks=[recorder])
>>> # Get data only from second run
>>> second_run_data = recorder.numpy()
close()[source]#

Close resources used by the callback.

If HDF5 caching is enabled, this method sends a termination signal to the writer thread and waits for it to complete. This ensures that all cached data is properly written to the HDF5 file before the callback is destroyed.

Return type:

None

See also

reset

Reset the recorder’s state

set_hdf5

Enable HDF5 caching for recorded data

stack(var=None)[source]#

Stack retained in-memory samples.

Parameters:

var (str, optional) – Recorded field name, such as "v" or "mech.hh.m". When omitted, stack all fields on an axis immediately before the final recorded-site or partition axis; the fields must have compatible shapes.

Returns:

With var supplied, samples retain their leading time axis, including when max_only=True. With var=None, the legacy max_only=True form additionally takes the maximum over time; otherwise time is retained.

Return type:

torch.Tensor

Notes

max_only already reduces the selected spatial sites or partitions when samples are recorded. numpy() uses the same stacking convention and then detaches and moves the result to CPU.

numpy(var=None)[source]#

Convert recorded tensors to NumPy arrays.

This method converts the stacked tensor data to NumPy arrays by detaching from the computation graph and moving the data to CPU memory. If a specific state name is provided, only that state’s data is converted.

Parameters:

var (str, optional) – Name of the specific state to convert to NumPy array. If None, all recorded states are stacked and converted. Default is None.

Returns:

NumPy array containing the recorded data.

Return type:

numpy.ndarray

class RecorderLambda(funcs)[source]#

Record arbitrary derived values using user-defined callables.

Pass a mapping of name -> func where each func accepts the model and returns a tensor (or list of tensors) to store. Useful for recording composite metrics that are not direct model attributes.

Parameters:

funcs (Mapping[str, Callable]) – Dictionary of callables. Each is invoked every step with the model and its output is appended to the list under the same key in rec.

Notes

Each function should be designed to work with the model’s current state.

funcs#

User-defined functions for recording data.

Type:

Mapping[str, Callable]

rec#

Per-key lists that collect outputs from funcs across steps.

Type:

dict[str, list]

reset()[source]#
stack(var=None)[source]#

Stack recorded tensors into a single tensor.

If a specific variable name is provided, only that variable’s data is stacked. Otherwise, all recorded variables are stacked and concatenated.

Parameters:

var (str, optional) – Name of the specific variable to stack. If None, all recorded variables are stacked and concatenated along dimension 2. Default is None.

Returns:

A tensor containing the stacked recorded data.

Return type:

torch.Tensor

numpy(var=None)[source]#
class LFP(v_unit, rule=None)[source]#

Record extracellular potentials from transmembrane currents.

For each recording contact, this callback takes the dot product between the model’s absolute transmembrane current and a reciprocal lead field. Public model.i_membrane is in mA, so a lead field in mV/mA produces a recorded potential in mV.

Parameters:
  • v_unit (list of torch.Tensor) – Non-empty list containing one reciprocal lead-field tensor per recording contact. Each tensor must have the same shape and should be broadcast-compatible with model.i_membrane under rule. Lead-field values must be in mV/mA (numerically equivalent to Ω); the constructor stacks the list along a leading contact dimension. Pass [lead_field] for one contact.

  • rule (str, optional) – Explicit Einstein summation rule for computing the dot product. The default sums the physical cell and compartment axes, preserving batch axes, and produces (*batch, contacts) per sample. An explicit rule is passed to torch.einsum without changing its reductions.

Notes

Requires the axon model to be compiled with fast membrane current calculation enabled (IMEM=1). Use with dendra.ctx(IMEM=1): model = … when creating the model.

v_unit#

Stacked lead fields in mV/mA, moved to the model’s device.

Type:

torch.Tensor

Examples

>>> # Create a point recording contact at (0, 0, 100) μm.
>>> import torch
>>> from dendra.models import callbacks
>>>
>>> # Isotropic reciprocal lead field: rhoe / (4*pi*r), in mV/mA.
>>> rhoe = 500.0  # Ω·cm
>>> r_cm = torch.sqrt(
...     model.x**2 + model.y**2 + (model.z - 100.0)**2
... ) * 1e-4
>>> lead_field = rhoe / (4 * torch.pi * r_cm)
>>>
>>> # The constructor takes a list, with one tensor per recording contact.
>>> lfp_callback = callbacks.LFP([lead_field])
>>>
>>> # Run the simulation with the callback
>>> model.run(tstop, callbacks=[lfp_callback])
>>>
>>> # Get the LFP signal as a NumPy array
>>> lfp_signal = lfp_callback.numpy()
>>> # or as a PyTorch tensor
>>> lfp_tensor = lfp_callback.lfp
property lfp#

Return potentials in mV with shape (samples, *batch, contacts) by default.

property t#

Return the sample times in ms, in the same order as lfp.

numpy()[source]#

Return the recorded LFP samples as a detached CPU NumPy array.

reset()[source]#

Thresholds and activity#

class ThresholdCallback(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=[5, -5], dt=None)[source]#

Base class for callbacks that detect threshold crossings in membrane potential.

This class provides common functionality for action potential detection by monitoring when membrane potential crosses a specified threshold at selected nodes. It serves as a base class for specialized callbacks like APCount, Active, and Raster.

The final model dimension is always interpreted as compartments. For a model shaped (*batch, N, C), callback state for K checked compartments is shaped (*batch, N, K). Activity criteria reduce only that final K axis and therefore return (*batch, N) (or (*batch, N, P) for P checked-compartment partitions).

Parameters:
  • threshold (float, optional) – Voltage threshold in mV to detect crossings. Default is 0.0.

  • t_start_check (float, optional) – Time in ms after which to start checking for threshold crossings. Default is 0.0 (check from beginning).

  • t_end_check (float, optional) – End of the detection window in milliseconds, excluded from checking. None uses the native sentinel of 1e9 ms. Window boundaries are converted to solver-step indices using dt.

  • node_check (list of int, optional) – Indices of nodes to check for threshold crossings. Default is [5, -5] (check at node 5 from beginning and node 5 from end).

  • dt (float, optional) – Time step in ms. If None, uses the default from backend. Default is None.

record#

Records detection results while preserving all model axes before the final compartment axis (specific format depends on subclass).

Type:

torch.Tensor

state_cache#

Cache of state to track threshold crossings between time steps.

Type:

torch.Tensor

threshold#

Voltage threshold for detection.

Type:

float

t_start_check#

Time after which detection starts.

Type:

float

node_check#

Indices of nodes being monitored.

Type:

list of int

i#

Time step counter.

Type:

int

property dt#

Time step size in ms.

reset_timer()[source]#

Reset the time step counter to zero.

reset_count()[source]#

Reset the detection record to None.

reset_state_cache()[source]#

Reset the state cache used for threshold detection.

reset()[source]#

Reset all internal state.

This method resets the time step counter, detection record, and state cache all at once.

numpy()[source]#

Return detection results as a NumPy array.

Returns:

Detection results as a NumPy array, or None if no results are available.

Return type:

numpy.ndarray or None

class APCount(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=[5, -5], dt=None)[source]#

Callback for counting action potentials during axon model simulation.

This class detects and counts the number of times membrane potential crosses above a specified voltage threshold at selected nodes. Each crossing is counted as an action potential (AP).

Parameters:
  • threshold (float, optional) – Voltage threshold in mV for AP detection. Default is 0.0.

  • t_start_check (float, optional) – Time in ms after which to start checking for APs. Default is 0.0 (check from beginning).

  • t_end_check (float, optional) – End of the detection window in milliseconds, excluded from checking. None uses the native sentinel of 1e9 ms. Window boundaries are converted to solver-step indices using dt.

  • node_check (list of int, optional) – Indices of nodes to monitor for AP detection. Default is [5, -5] (check at node 5 from beginning and node 5 from end).

  • dt (float, optional) – Time step in ms. If None, uses the default from backend. Default is None.

See also

Active

Callback for detecting if axons fire at any point during simulation

Raster

Callback for recording spike times for raster plots

Examples

>>> ap_counter = APCount(threshold=20.0)  # Count when v crosses +20 mV
>>> model.run(ve, callbacks=[ap_counter])
>>> ap_counts = ap_counter.numpy()  # Get AP counts for each axon
record#

Int32 tensor of shape (*batch, N, n_check_nodes) storing AP counts.

Type:

torch.Tensor

state_cache#

Boolean tensor tracking membrane potential state relative to threshold.

Type:

torch.Tensor

property n#

Return an owned int32 Tensor of per-node spike counts.

class Raster(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=[5, -5], dt=None)[source]#

Record upward voltage threshold crossings at selected compartments.

Each retained post-step sample contains one Boolean value per checked compartment. The window selects zero-based step indices from int(t_start_check / dt) inclusive to int(t_end_check / dt) exclusive.

Parameters:
  • threshold (float, optional) – Voltage threshold in mV. The default is 0.0.

  • t_start_check (float, optional) – Start of the observation window in ms. The default is 0.0.

  • t_end_check (float or None, optional) – End of the observation window in ms. Omission uses 1e9 ms.

  • node_check (sequence of int, optional) – Compartment indices to check. The default is [5, -5]. Choose indices that exist in the model, such as [0] for point cells.

  • dt (float or None, optional) – Solver timestep in ms. Native execution supplies its timestep. For functional execution, omit this or specify the plan’s timestep.

See also

APCount

Count threshold crossings at each checked compartment.

Active

Test whether any checked compartment crossed the threshold.

Examples

For an initialized, unbatched Population with at least two cells:

import numpy as np
from dendra import callbacks

raster = callbacks.Raster(threshold=20.0, node_check=[0])
model.run(steps=40, dt=0.025, callbacks=[raster])
crossings = raster.stack()
ax = raster.plot(np.arange(model.np), "Cell index")
record#

Retained Boolean rows, each shaped (*batch, N, K), where K is the number of checked compartments.

Type:

list of torch.Tensor

state_cache#

Boolean flags indicating whether each checked compartment was below threshold at the previous observation.

Type:

torch.Tensor

stack()[source]#

Return a Boolean tensor shaped (samples, *batch, N, K).

Only post-step rows inside the observation window are included. An initialized recording with no retained samples has a zero-length leading axis.

numpy()[source]#

Return stack() as a detached CPU NumPy array.

plot(var, varname, dt=None, ax=None, cmap=None, node_idx=None, axon_idx=None)[source]#

Plot one checked compartment of an unbatched raster.

Parameters:
  • var (numpy.ndarray) – Numeric y-coordinates, such as fiber diameters in μm. Supply one value per selected cell, with at least two values in increasing order.

  • varname (str) – Label for the y-axis.

  • dt (float, optional) – Timestep in ms. Omission uses the recording timestep. Plotted times are relative to the first retained row.

  • ax (matplotlib.axes.Axes, optional) – Axes to draw on. Omission creates a new figure and axes.

  • cmap (str or matplotlib.colors.Colormap, optional) – Colormap for the y-coordinates. The default is viridis.

  • node_idx (int, optional) – Index within the checked compartments. The default is 0.

  • axon_idx (slice or sequence of int, optional) – Selection along the cell axis. Omission selects every cell.

Returns:

The axes containing the raster plot.

Return type:

matplotlib.axes.Axes

class Active(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=[5, -5], dt=None, inv=False)[source]#

Callback for detecting if axons fire at any point during simulation.

This class detects if the membrane potential crosses above a specified voltage threshold at selected nodes at any point during the simulation. It subclasses ActiveAL with at_least=1 to mark an axon as “active” (fired) as soon as the first threshold crossing is detected.

Parameters:
  • threshold (float, optional) – Voltage threshold in mV for spike detection. Default is 0.0.

  • t_start_check (float, optional) – Time in ms after which to start checking for threshold crossings. Default is 0.0 (check from beginning).

  • t_end_check (float, optional) – End of the detection window in milliseconds, excluded from checking. None uses the native sentinel of 1e9 ms. Window boundaries are converted to solver-step indices using dt.

  • node_check (list of int, optional) – Indices of nodes to monitor for spike detection. Default is [5, -5] (check at node 5 from beginning and node 5 from end).

  • dt (float, optional) – Time step in ms. If None, uses the default from backend. Default is None.

  • inv (bool, optional) – If True, inverts the active detection (marks axons as inactive if they fired). Default is False.

See also

APCount

Callback for counting total spikes during simulation

Raster

Callback for recording spike times for raster plots

Examples

>>> active_detector = Active(threshold=20.0)  # Detect when v crosses +20 mV
>>> model.run(ve, callbacks=[active_detector])
>>> active_axons = active_detector.numpy()  # Get boolean array of active axons
>>> active_count = active_axons.sum()  # Count how many axons fired
record#

Int32 per-slot spike counters of shape (*batch, N, K), inherited from APCount. is_active() returns the Boolean activity mask shaped (*batch, N).

Type:

torch.Tensor

state_cache#

Boolean tensor of shape (*batch, N, K) tracking membrane potential state at the K checked compartments.

Type:

torch.Tensor

is_active(partition=None)#

Determine which axons are active based on spike counts.

By default, a logical population entry is active if the number of nonzero entries along the final axis of record is at least at_least. When partition is provided, the check is performed independently over contiguous segments of the final axis, and a boolean mask is returned for each segment.

Parameters:

partition (sequence of int, optional) – Segment lengths that partition record along its final axis. The sum of the sequence must equal record.shape[-1] and every value must be at least at_least. If None, the full row is used.

Returns:

Boolean tensor of shape (*batch, N) when partition is None, otherwise (*batch, N, len(partition)). If inv is True, the result is inverted.

Return type:

torch.Tensor

Raises:

ValueError – If partition is empty, not 1D, does not sum to record.shape[-1], or any segment length is less than at_least.

numpy(partition=None)#
class ActiveAL(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=[5, -5], dt=None, at_least=1, inv=False)[source]#

Detect activity in at least a specified number of checked slots.

A checked slot qualifies after any upward voltage-threshold crossing. Repeated crossings at one slot contribute only once to this criterion; use ActiveALCount to compare the total number of crossings instead.

Parameters:
  • threshold (float, optional) – Voltage threshold in mV for spike detection. Default is 0.0.

  • t_start_check (float, optional) – Time in ms after which to start checking for threshold crossings. Default is 0.0 (check from beginning).

  • t_end_check (float, optional) – End of the detection window in milliseconds, excluded from checking. None uses the native sentinel of 1e9 ms. Window boundaries are converted to solver-step indices using dt.

  • node_check (list of int, optional) – Indices of nodes to monitor for spike detection. Default is [5, -5] (check at node 5 from beginning and node 5 from end).

  • dt (float, optional) – Time step in ms. If None, uses the default from backend. Default is None.

  • at_least (int, optional) – Minimum number of checked slots with at least one crossing required to mark a logical population entry as active. Must be a positive integer; Boolean values are not accepted. Default is 1.

  • inv (bool, optional) – If True, inverts the active detection (marks axons as inactive if they meet the threshold). Default is False.

See also

APCount

Callback for counting total spikes during simulation

Active

Callback for detecting if axons fire at any point during simulation

ActiveALCount

Callback for a total crossing-count criterion

Examples

>>> # Require a crossing at each of three checked slots.
>>> detector = ActiveAL(threshold=20.0, node_check=[0, 1, -1], at_least=3)
>>> model.run(ve, callbacks=[detector])
>>> active_axons = detector.numpy()  # Get boolean array of active axons
>>> active_count = active_axons.sum()  # Count axons firing at three checked slots
record#

Tensor of shape (*batch, N, n_check_nodes) storing spike counts.

Type:

torch.Tensor

state_cache#

Boolean tensor tracking membrane potential state relative to threshold.

Type:

torch.Tensor

at_least#

Positive integer number of checked slots with at least one crossing.

Type:

int

is_active(partition=None)[source]#

Determine which axons are active based on spike counts.

By default, a logical population entry is active if the number of nonzero entries along the final axis of record is at least at_least. When partition is provided, the check is performed independently over contiguous segments of the final axis, and a boolean mask is returned for each segment.

Parameters:

partition (sequence of int, optional) – Segment lengths that partition record along its final axis. The sum of the sequence must equal record.shape[-1] and every value must be at least at_least. If None, the full row is used.

Returns:

Boolean tensor of shape (*batch, N) when partition is None, otherwise (*batch, N, len(partition)). If inv is True, the result is inverted.

Return type:

torch.Tensor

Raises:

ValueError – If partition is empty, not 1D, does not sum to record.shape[-1], or any segment length is less than at_least.

numpy(partition=None)[source]#
class ActiveALCount(threshold=0.0, t_start_check=0.0, t_end_check=None, node_check=[5, -5], dt=None, at_least=1, inv=False)[source]#

Callback for determining whether an axon fired based on the total spike count.

This class extends APCount to determine if an axon is “active” based on whether the total number of threshold crossings across all monitored nodes meets or exceeds a specified count. Repeated crossings at one checked slot contribute separately to this total, including the multiplicity of repeated node_check entries.

Parameters:
  • threshold (float, optional) – Voltage threshold in mV for spike detection. Default is 0.0.

  • t_start_check (float, optional) – Time in ms after which to start checking for threshold crossings. Default is 0.0 (check from beginning).

  • t_end_check (float, optional) – End of the detection window in milliseconds, excluded from checking. None uses the native sentinel of 1e9 ms. Window boundaries are converted to solver-step indices using dt.

  • node_check (list of int, optional) – Indices of nodes to monitor for spike detection. Default is [5, -5] (check at node 5 from beginning and node 5 from end).

  • dt (float, optional) – Time step in ms. If None, uses the default from backend. Default is None.

  • at_least (int, optional) – Minimum total spike count across all monitored nodes required to mark an axon as active. Must be a positive integer; Boolean values are not accepted. Default is 1.

  • inv (bool, optional) – If True, inverts the active detection (marks axons as inactive if they meet the count threshold). Default is False.

is_active(partition=None)[source]#

Determine which axons are active based on total spike count.

A logical population entry is active if the sum of counts across the final checked-node axis in record is at least at_least. When partition is provided, the check is performed independently over contiguous segments of that final axis.

Returns:

Boolean tensor of shape (*batch, N) when partition is None, otherwise (*batch, N, len(partition)). If inv is True, the result is inverted.

Return type:

torch.Tensor

numpy(partition=None)[source]#
class AnomalyDetector[source]#

Flag NaN/Inf occurrences in membrane voltage during simulation.

The detector keeps a boolean mask per axon indicating whether any invalid values have appeared so far. The mask is updated every step and can be retrieved as a tensor or NumPy array for inspection after a run.

Construct with dn.callbacks.AnomalyDetector().

reset()[source]#

Clear the anomaly mask so the detector can be reused.

numpy()[source]#

Return the anomaly mask as a NumPy array.

Network scopes and custom native hooks#

class PopulationCallback(population, callback)[source]#

Apply a callback to one top-level Population in a Network.

Parameters:
  • population (str) – Exact Population name in the Network’s populations mapping. A concatenated MultiPopulation is one owner; use its named physical Slices with a Recorder’s region argument to select components.

  • callback (Callback or dendra.func.FunctionalCallback) – Observation configuration for the selected Population. Native Network execution forwards hooks to a native Callback. Functional execution accepts supported native configurations and pure callbacks.

Notes

Inspect native results through the supplied inner callback, also available as callback. Functional execution captures the configuration and returns independently owned results without importing the inner callback’s native history. Scopes cannot be nested. Use the inner callback directly for a standalone Population.

Examples

>>> counts = APCount(node_check=[0, -1])
>>> scoped = PopulationCallback("left", counts)
>>> network.run(10.0, callbacks=[scoped])
>>> native_counts = counts.numpy()
class Callback(*args, **kwargs)[source]#

Base class for simulation callbacks in Dendra.

This class defines the interface for callbacks that can be passed to run or longrun methods of models to monitor and interact with the simulation at specific points in the execution flow. Subclasses override hook methods to record state, detect events, or stream data during a run.

Notes

The default implementations are no-ops; override only the hooks you need. Multiple callbacks can be used simultaneously by passing them in a list to the model’s run method or by wrapping them in CallbackList.

See also

Recorder

Records model states during simulation

LFP

Records Local Field Potential signals

APCount

Counts action potentials during simulation

Active

Detects if axons fire during simulation

Raster

Records spike events for raster plots

Examples

>>> class CustomCallback(Callback):
...     def pre_loop_hook(self, model):
...         print(f"Starting simulation with {model.n()} axons")
...     def post_loop_hook(self, model):
...         print(f"Finished simulation at t={model.t} ms")
>>>
>>> callback = CustomCallback()
>>> model.run(ve, callbacks=[callback])

Initialize internal Module state, shared by both nn.Module and ScriptModule.

pre_loop_hook(model)[source]#

Run once before entering the solver loop.

Override to allocate buffers, move indices to the correct device, or otherwise initialize state based on the provided model.

pre_chunk_hook(model, timepoints=None)[source]#

Run before processing a chunk of timepoints.

Override to prepare per-chunk scratch space or bookkeeping using the supplied timepoints.

post_chunk_hook(model, timepoints=None)[source]#

Run after finishing a chunk of timepoints.

Override to flush results accumulated during the chunk or to update metrics that depend on the completed block.

pre_step_hook(model)[source]#

Run before each solver step (single timestep).

Override to inspect or modify model state just before integration.

post_step_hook(model)[source]#

Run after each solver step (single timestep).

Override to record outputs or update counters after the model advances.

post_loop_hook(model)[source]#

Run once after the solver loop completes.

Override to finalize results or free resources.

class CallbackList(callbacks=None)[source]#

Lightweight container that forwards hook calls to multiple callbacks.

Parameters:

callbacks (list[Callback], optional) – Sequence of callback instances to run. The list is stored as a torch.nn.ModuleList so callbacks are registered buffers.