Populations and model construction#
A Population owns voltage, mechanisms and simulation state. Use dn.SingleCompartment
for point cells, dn.Cable or dn.Tree for native morphologies, and the axon
classes for repeating cable structures. Native execution updates the model;
Functional execution describes execution with explicit state and source tensors.
Population lifecycle and inputs#
- class Population(N=1, C=1, integrator=None, v_init=-65.0, *, preserve_mechanism_population_axis=None, device=None, dtype=None, **kwargs)[source]#
Population of neurons with a shared compartment layout.
- Parameters:
N (int, default 1) – Number of population rows (cells).
C (int, default 1) – Compartments per row.
integrator (integrator class, optional) – Numerical integrator. Defaults to
bwd_euler_sc.v_init (scalar or Tensor, default -65.0) – Initial membrane voltage in mV, broadcastable to the voltage shape.
preserve_mechanism_population_axis (bool or None, optional) – Preserve separate population and support axes for eligible distributed mechanisms.
Noneuses the construction context, then the model family’s default. This layout policy is fixed at construction.device (str or torch.device, optional) – Tensor device. Uses the Dendra context, defaulting to CPU.
dtype (torch.dtype or str, optional) – Floating-point dtype. Uses the Dendra context, defaulting to float32.
**kwargs – Declared model parameters, including
cmin µF/cm²,rhoain Ω·cm, andcelsiusin °C.
Notes
Insert mechanisms and configure geometry before calling
initialize(). Userun()to advance the model orlongrun()to prepare stimulation in chunks. Use the same model definition withdn.compileordn.func.make_functional.- batch(n)[source]#
Materialize explicit batch copies of state tensors.
- Parameters:
n (int) – Number of batch replicas to create.
- Returns:
The population instance with replicated buffers.
- Return type:
- bfloat16()[source]#
Cast population parameters and buffers to
torch.bfloat16.- Returns:
The population instance with converted dtype.
- Return type:
- bind_input(target, source)[source]#
Route a declared State INPUT from another mechanism in this Population.
targethas formmechanism.DE.State.input.sourcenames a declared state, carry, saved current, or parameter tensor asmechanism.fieldormechanism.DE.State.field. Bindings read the source when the consumer advances, preserving mechanism execution order. Initialization uses the INPUT declaration’s scalar default.
- build(force_rebuild=False)[source]#
Compile and register mechanisms, assembling ion bookkeeping.
- Parameters:
force_rebuild (bool, optional) – If True, rebuild even when a compiled configuration already exists.
- Returns:
The population instance, ready for simulation.
- Return type:
- cache(name=None)[source]#
Cache the current model state with an optional identifier.
This method saves a snapshot of the model’s current state dictionary to an internal cache. The state can later be restored using the restore() method with the same name.
- Parameters:
name (str, optional) – Identifier for the cached state. If None, the state is cached with the name ‘latest’. Default is None.
- Return type:
None
See also
restoreRestore a previously cached state
Examples
>>> model.cache('before_training') # Cache state before training >>> # ... training or simulation ... >>> model.restore('before_training') # Return to cached state
- clear_jit_cache()[source]#
Drop lazily compiled functions attached to this population.
torch.compilecallables are process-local and may capture TorchDynamo/Inductor configuration objects that cannot be pickled. The compiled helpers are regenerated lazily byrun/initializeafter unpickling, so clearing them does not discard model state.
- cpu()[source]#
Move the population to CPU memory, rebuilding mechanisms if needed.
- Returns:
The population instance on CPU.
- Return type:
- cuda(device=None)[source]#
Move the population to a CUDA device, rebuilding mechanisms if needed.
- Parameters:
device (int or torch.device, optional) – CUDA device identifier.
- Returns:
The population instance on the requested device.
- Return type:
- delete(mechanism, index=None, *, strict=False)[source]#
Delete a mechanism class everywhere or where it intersects a region.
- Parameters:
mechanism (type) – Exact mechanism class to remove.
index (IndexSpec or object, optional) – Physical population-core selection to remove.
None(the default) removes every configured placement ofmechanism.strict (bool, default False) – If True, require the mechanism to exist at every selected physical compartment and fail atomically otherwise. If False, delete only the intersection between the selection and current support; a missing class or empty intersection is a no-op.
Notes
Deletion subtracts selected support from every overlapping insertion record, including all duplicate/copy slots at those compartments. Reinitialize the population after a successful deletion.
- delete_all(index=None)[source]#
Delete every mechanism class present in a population region.
- Parameters:
index (IndexSpec or object, optional) – Physical population-core selection.
None(the default) removes every configured mechanism placement from the Population.
Notes
This operation uses intersection semantics for every exact configured mechanism class. Planning and projection are transactional across classes: if any affected configuration cannot be projected safely, no mechanism configuration or lifecycle state is changed.
- delete_injections()[source]#
Remove all registered intra-cellular and mechanism-level injections.
- Return type:
None
- detach()[source]#
Truncate simulation history while retaining state values and raw sources.
The next positive-step, gradient-enabled training call rebuilds effective parameter, derived and solver graphs from the current raw sources. Retained RAND draws are replayed without resampling; NOISE stays detached. Evaluation, no-grad, inference-mode and zero-step calls defer that refresh. Clocks and recurrent state are not reset. Raw parameter objects and externally computed nonleaf source graphs remain caller-owned.
Reconnecting trainable reparameterized RAND values requires retained explicit draws from a pure distribution draw_sampler/transform contract. Callback history is separate; detach its returned carry through the owning callback collection when continuing observations.
- Returns:
The population instance with detached states.
- Return type:
- device()[source]#
Device on which population buffers reside.
- Returns:
Device handle inferred from the registered dummy buffer.
- Return type:
torch.device
- double()[source]#
Cast population parameters and buffers to
torch.float64.- Returns:
The population instance with converted dtype.
- Return type:
- dtype()[source]#
Default tensor dtype for the population.
- Returns:
Data type inferred from the registered dummy buffer.
- Return type:
torch.dtype
- expanded_v_init(target_shape=None)[source]#
Return
v_initas a tensor expanded to the model voltage shape.Supported
v_initforms are:scalar: broadcast to every element of
model.v;one-dimensional tensor/array/list of length
model.nc: broadcast across the population axis and any batch axes;tensor/array with shape
(model.np, model.nc)or the current full voltage shape: used as explicit per-element initial voltages.
- Parameters:
target_shape (tuple of int, optional) – Shape to expand into. Defaults to
self.v.shapeaftervhas been registered.- Returns:
A tensor view with shape
target_shapeon this model’s device and dtype. The returned tensor may be expanded; callers that will mutate it should clone first.- Return type:
torch.Tensor
- find(include=None, exclude='branchpoint', fuzzy=True, match_case=False, full_report=False, as_list=False, loc=None)[source]#
Locate compartment indices matching inclusion/exclusion rules.
- Parameters:
include (str or list of str, optional) – Patterns that must be present.
exclude (str or list of str, optional) – Patterns that must not be present. Defaults to
'branchpoint'.fuzzy (bool, optional) – If True, use token-aware glob matching. For example,
"soma"matches"MelnickSG_soma(0.5)"and"Cell.soma[0](0.5)", while"soma[0]"matches only that literal indexed section. Adjacent letters or digits are not delimiters, so"myelin"does not match"unmyelin"or"myelinated". Use"*myelin"to request the broader suffix match explicitly. Default is True.match_case (bool, optional) – If True, perform case-sensitive matching. Default is False.
full_report (bool, optional) – If True, return the full
FindResult. Default is False.as_list (bool, optional) – If True and the result is a slice, convert it to a list.
loc (float, optional) – Optional location refinement parameter in
[0, 1].
- Returns:
Either the result object or the indices, depending on
full_report.- Return type:
FindResult or Union[list, slice]
- find_not(exclude=None, fuzzy=True, match_case=False)[source]#
Find indices that do not match provided patterns.
- Parameters:
exclude (str or list of str, optional) – Patterns describing compartments to omit.
fuzzy (bool, optional) – If True, use token-aware glob matching. Punctuation, including underscores, dots, brackets, and parentheses, separates name tokens;
*explicitly matches zero or more characters. Default is True.match_case (bool, optional) – If True, perform case-sensitive matching. Default is False.
- Returns:
Indices of entries that do not match
exclude.- Return type:
list or slice
- float()[source]#
Cast population parameters and buffers to
torch.float32.- Returns:
The population instance with converted dtype.
- Return type:
- freeze_group(*groups)[source]#
Freeze parameter groups stored as module attributes.
- Parameters:
*groups (str) – Attribute names of iterable parameter collections to freeze.
- Returns:
The population instance for chaining.
- Return type:
- half()[source]#
Cast population parameters and buffers to
torch.float16.- Returns:
The population instance with converted dtype.
- Return type:
- initialize(force_rebuild=False, populate_parameter_buffers=True, *, draws=None)[source]#
Build, populate, and initialize mechanisms for simulation.
- Parameters:
force_rebuild (bool, optional) – If True, force rebuilding of mechanisms even if a built graph already exists.
populate_parameter_buffers (bool, default True) – Materialize parameter buffers before fresh initialization. Cached restoration follows its own parameter and RNG policy.
draws (dendra.func.InitializationDraws, optional) – Replay explicit initialization draws on a compatible initialized population. Capture a packet with
dn.func.sample_initialization_draws(population). Explicit replay does not support forced rebuilding.
- Returns:
The initialized population instance.
- Return type:
- insert(mechanism, alias=None, index_spec=None, ic=None, preserve_duplicate_indices=False, preserve_multiplicity=None, copies=1, **kwargs)[source]#
Insert a mechanism into the model.
- Parameters:
mechanism (Mechanism) – The mechanism to be inserted into the model.
alias (str, optional) – An optional alias for the mechanism. If not provided, the mechanism’s name will be used.
index_spec (IndexSpec, optional) – An optional index specification that defines where the mechanism should be inserted. If not provided, the mechanism will be inserted everywhere.
ic (dict, optional) – Initial values for mechanism state fields. For region-restricted insertions these values are class-wide because all regions of one mechanism class compile into one mechanism instance.
preserve_duplicate_indices (bool, optional) – If True, duplicate compartment indices selected by this insertion are retained as independent mechanism slots instead of being collapsed into the usual unique union. This is useful for colocated point processes or synapse banks that should maintain independent state while scattering their currents back to the same compartment.
preserve_multiplicity (bool, optional) – User-facing synonym for
preserve_duplicate_indices.copies (int, optional) – Number of independent copies of this insertion region to allocate.
copies > 1impliespreserve_duplicate_indices=Trueand is intended for compact banks of colocated point processes.**kwargs – Mechanism parameters. RANGE/BATCH values are restricted to the insertion region. GLOBAL values are class-wide; later insertion records for the same class must use compatible GLOBAL values.
- load(state_dict)[source]#
Load model weights from a state dictionary.
This method supports loading weights from: 1. A file path as a string 2. An actual state dictionary object
The loaded weights are matched to the model’s current state dict structure and only compatible weights are loaded.
- Parameters:
state_dict (str or dict) – Can be one of: - A file path to a saved model state - A state dictionary object
- Returns:
The model instance with loaded weights
- Return type:
self
- longrun(tstop=None, chunklength=None, dt=None, extra=None, callbacks=None, progressbar=False, *, steps=None, duration=None, inputs=None, draws=None, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#
Run a long simulation by dividing it into multiple smaller chunks.
This method splits the overall simulation into chunks of a given length, allowing for more efficient memory management during long simulations. The model’s state (e.g., voltage variables,
v_prev, etc.) is maintained between chunks, ensuring continuity across the entire simulation period.- Parameters:
tstop (float) – Simulation duration in milliseconds to advance from the current model time
self.t. Only complete fixed timesteps are executed; fractional physical duration is retained and shared with subsequent duration-based Population execution calls.steps (int, optional) – Exact non-negative step count, leaving fractional duration carry unchanged. Mutually exclusive with
durationandtstop.duration (float, optional) – Non-negative elapsed milliseconds, accumulating the same physical duration carry as
tstop. Supply exactly one horizon argument.chunklength (int) – The number of time steps to process in each chunk.
dt (float, optional) – The simulation time step in milliseconds. If
None, the default value from the backend will be used.inputs (dendra.func.Inputs, optional) – Strict time-first voltage/current tapes matching the accepted steps for the selected horizon. Tapes are indexed at actual chunk boundaries. Omitted current retains Slice injections; explicit current conflicts with those injections. Explicit voltage conflicts with
extra.extra (tuple or sequence of tuples, optional) –
Extracellular input specification(s).
Each specification is a tuple
(ve_s, time):ve_sis normalized to[*batch, n_p, n_comp].timeis either aWaveformor a time-last tensor normalized to[*batch, n_p, n_timesteps].
Both use ordinary trailing broadcasting first, followed only on failure by a low-rank, right-aligned batch-only fallback. Explicit singleton axes disambiguate equal-size batch and spatial dimensions.
If a single tuple is provided, the method uses a single-contact formulation with
op_sc(). If a sequence of tuples is provided, each tuple is treated as one electrode contact, and the method automatically switches to multi-contact mode withop_mc():In multi-contact mode, spatial fields are stacked to shape
[n_contacts, *batch, n_p, n_comp].For a functional specification (all
timeareWaveform), each waveform is evaluated per chunk and per contact and then expanded/concatenated to shape[n_contacts, *batch, n_p, n_t_chunk].For a non-functional specification (all
timeare tensors), the raw time tensors are pre-split into chunks and concatenated to the same shape[n_contacts, *batch, n_p, n_t_chunk].
Mixing
Waveformand tensor time specifications across contacts is not supported and will raise aValueError.draws (dendra.func.RuntimeDraws, optional) – Time-leading explicit draws and RNG boundaries matching accepted steps. Mechanism-owned waveform injections consume their accepted-step invocation recipes in native numerical order. Poisson bank recipes replay per step independently of chunklength; other waveforms retain per-chunk preparation. Omitted draws retain automatic sampling. Supplied base draws are detached while model, waveform and input gradients are preserved.
callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with
dn.func.make_callbacksfor this Population or a compatible initialized Population. Requesteddtmust honor prepared Recorder cadence and threshold timing. Pure observations read this receiver’s state with fixed prepared selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.progressbar (bool or tqdm, optional) – If
True(or if atqdm.tqdminstance is provided), displays a progress bar to track simulation progress across chunks. Default isFalse.callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through
callbacksorfunctional_callbacks. Resumes sampling phase and reducer totals without another initial observation.functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside
callbacks=[...]to combine native hooks and pure observations. Supply the collection through only one argument.functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for
callback_state. Supply carry through only one argument; either collection spelling is accepted.
- Returns:
Pure observations return their named results and carry when supplied. Existing calls without them return
None. Cadence and gradients are preserved across chunks and continued calls.- Return type:
Notes
Multi-contact handling follows the number of
extraentries.When
extrais provided, the method uses it to assemble the extracellular voltageveviaop_sc()(single contact) orop_mc()(multi-contact).Chunk processing helps manage memory usage during extended simulations by processing data in manageable segments.
- longrun_checkpointed(tstop=None, chunklength=None, dt=None, extra=None, callbacks=None, progressbar=False, *, steps=None, duration=None, inputs=None, draws=None, safe_checkpoint=False, restore_state_after_backward=True, return_final_state=False, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#
Run a long simulation in chunks using activation checkpointing.
This is a checkpointed analogue of
longrun(). Each chunk is wrapped intorch.utils.checkpoint.checkpoint()(withuse_reentrant=False), so intermediate activations inside the chunk are discarded and recomputed during the backward pass. This enables full BPTT across the entiretstophorizon while bounding activation memory by the chunk size.- Parameters:
tstop (float) – Simulation duration in milliseconds to advance from the current model time
self.t. This uses the same cumulative complete-step budget and retained physical-duration semantics aslongrun().steps (int, optional) – Exact non-negative step count, preserving fractional-duration carry. Mutually exclusive with
durationandtstop.duration (float, optional) – Non-negative elapsed milliseconds, using the same physical-duration budget as
tstop. Supply exactly one horizon argument.chunklength (int) – Number of time steps per checkpointed chunk.
dt (float, optional) – Time step size in milliseconds. If None, uses the global default
A.dt.inputs (dendra.func.Inputs, optional) – Strict time-first voltage/current tapes matching accepted steps. Checkpoint recomputation reuses each chunk’s original input slices, preserving gradients to their caller-owned sources. Omitted fields retain registered stimulation; duplicate drive sources are rejected.
draws (dendra.func.RuntimeDraws, optional) – Time-leading explicit draws and RNG boundaries matching accepted steps. Checkpoint recomputation reuses the original step recipes without sampling again. Keep tape tensors unchanged until backward completes. Checkpointed training requires mutation counters; clone inference tensors outside
torch.inference_mode()before passing them here. Omission retains automatic sampling and its bank preparation cadence.extra (ExtraSpec, optional) – Extracellular configuration with the same
(ve_s, time)shape and trailing-first broadcasting contract aslongrun().callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with
dn.func.make_callbacksfor this Population or a compatible initialized Population. Requesteddtmust honor prepared Recorder cadence and threshold timing. Pure observations read this receiver’s state with fixed prepared selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.progressbar (bool, optional) – If True, display a progress bar during the run. Default is False.
safe_checkpoint (bool, optional) – If True, clone checkpoint boundary state to avoid in-place mutation of checkpoint inputs. This is safer but may incur a memory overhead. Default is False.
restore_state_after_backward (bool, optional) – If True, isolate checkpoint replay from the live model so backward,
autograd.grad, and higher-order derivatives do not leave its buffers at an internal chunk boundary. This is useful when further simulation or evaluation is needed after differentiation. Default is True.return_final_state (bool, optional) – If True, return a tuple (loss, final_state) where final_state is a checkpoint state dictionary suitable for restore_dict_from_checkpoint. Default is False.
callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through
callbacksorfunctional_callbacks. Resumes sampling phase and reducer totals without another initial observation.functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside
callbacks=[...]to combine native hooks and pure observations. Supply the collection through only one argument.functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for
callback_state. Supply carry through only one argument; either collection spelling is accepted.
- Returns:
If return_final_state is False (default): returns the total loss contribution from callbacks, or None if no hook returned a non-None value. If return_final_state is True: returns (loss_or_none, final_state_dict). With a prepared pure collection, its result is appended:
(loss_or_none, callback_results)or(loss_or_none, final_state_dict, callback_results).- Return type:
torch.Tensor or None or tuple
Notes
In-place update contract
torch.utils.checkpointforbids in-place mutation of checkpoint inputs. If your stepping code (integrator/mechanisms) is strictly out-of-place with respect to the boundary state tensors, you may keepsafe_checkpoint=False(default) for best performance. If you are unsure, setsafe_checkpoint=Trueto clone the boundary state at chunk entry.Callback contract (restricted)
For correctness under checkpointing, callbacks used here must be replay-safe:
Hooks must be free of persistent side effects (e.g., do not append to Python lists intended to be consumed after the run).
Hooks must not mutate model state in a way that changes simulation dynamics.
If a hook uses internal temporary state, it must fully clear that state within the hook call itself.
Loss aggregation
Hooks may optionally return a scalar tensor loss contribution. Any non-None returns from the following hooks are summed:
post_step_hook(model)post_chunk_hook(model, t_chunk)post_loop_hook(model)
- material(name, fields=None, *, initial_values=None, min_values=None, specs=None, domain=None, units=None, conserved=None, **field_initials)[source]#
Register or override a generic population-wide Material.
- Parameters:
name (str) – Material name, e.g.
"ip3". For registered ions such as"ca", continue to useconcentrations()/equilibria(); ions are already Material-like and may be read throughUSEIONorUSEMATERIAL.fields (Mapping or Sequence, optional) – Field declarations passed to
Material. A mapping specifies initial values, e.g.fields={"ip3i": 0.1}; a sequence declares fields initialized to zero unlessinitial_valuessupplies values.initial_values (Mapping, optional) – Per-field initial value overrides. When the material has been registered globally, these override the registered initial values while preserving other field metadata such as min values and units.
min_values (Mapping, optional) – Per-field minimum-value guards.
specs (Mapping[str, MaterialFieldSpec], optional) – Fully specified field specs. This is the most explicit form and is forwarded directly to
Material.domain (str or Mapping[str, str], optional) – Spatial-domain metadata applied to every field or selected per field. Common aliases are
"i"/"intracellular","o"/"extracellular", and"membrane". Geometry-aware material processes use this metadata to choose an appropriate volume or area.units (str or Mapping[str, str], optional) – Descriptive unit label applied to every field or selected per field, for example
{"ip3i": "mM"}. Dendra preserves this label inMaterialFieldSpec, but does not convert values or perform dimensional analysis; mechanism and process equations must use a consistent numeric convention.conserved (bool or Mapping[str, bool], optional) – Descriptive conservation intent applied to every field or selected per field. This flag is retained as field metadata; setting it does not itself enforce conservation. Conservation follows from the selected operation (for example finite-volume diffusion or an
ExchangeProcess) and compatible geometry/units.**field_initials – Convenience initial values, e.g.
model.material("ip3", ip3i=0.1).
Notes
Generic materials have no universal physical unit. Declare
unitswhen a field has one, and keep all initial values, mechanism writes, additive sources, and material-process parameters consistent with it. Ion concentration fields are the important built-in special case: their intracellular and extracellular values use mM.Examples
A concentration-like intracellular field can make all three metadata declarations explicit:
model.material( "ip3", fields={"ip3i": 0.1}, min_values={"ip3i": 0.0}, domain={"ip3i": "intracellular"}, units={"ip3i": "mM"}, conserved={"ip3i": True}, )
- Returns:
The population instance for chaining.
- Return type:
- material_geometry(name)[source]#
Return a copy of a named material-transport geometry configuration.
The returned mapping contains registered Population source names (buffers or parameters) rather than detached tensor snapshots.
- pickleable(*, inplace=False, clone=False, reset_global_compiler=False)[source]#
Return a pickle-friendly population handle.
By default this method is non-mutating and simply returns
self. Pickling then uses__getstate__(), which strips process-local JIT callables from the serialized state without clearing the live object’s compiled caches. This lets users checkpoint a running model and keep using the already-compiled kernels afterward.- Parameters:
inplace (bool, default False) – If True, also clear this live population’s local JIT caches. The next JIT-enabled run may need to recompile.
clone (bool, default False) – If True, return a sanitized deep copy. This avoids mutating the live population but duplicates tensor storage, so it is usually not appropriate for very large models.
reset_global_compiler (bool, default False) – Also clear global Torch compiler caches. This can force recompiles and should usually be False when saving mid-simulation.
- register_injection(waveform, index_spec)[source]#
Register a waveform injection on both solver and mechanism paths.
The solver path preserves the existing
Intrabehavior used by standard voltage integrators. The mechanism path offers the same waveform/index information to every built mechanism throughMechanism.inject(...); mechanisms that do not override that method simply ignore it.
- register_material_geometry(name, *, domain, volume, edge_area=None, edge_distance=None, edge_factor=None)[source]#
Register named finite-volume geometry for material transport.
A named geometry describes a chemical storage/transport domain. It is deliberately independent of electrical extracellular parameters such as
xraxial,xc, andxg. Reference it fromDiffusionProcess.DIFFUSE()withgeometry=name.- Parameters:
name (str) – Geometry identifier referenced by
DiffusionProcess.DIFFUSE(..., geometry=name).domain (str) – Chemical/material domain represented by this geometry, for example
"extracellular"or"intracellular".volume – Scalar or node/control-volume tensor in
um^3, or the name of a registered Population buffer/parameter containing it. It must broadcast to the material field; a non-scalar tensor normally has final dimensionC(the compartment count).edge_area – Scalar or interface-aligned area in
um^2and center-to-center transport distance inum. Both must broadcast over the population’s interfaces. Non-scalar 1-D tensors normally have final dimensionC - 1. A Tree uses compact edge dimensionEin the stable order exposed bymaterial_edge_index. Dendra formsedge_factor = edge_area / edge_distance.edge_distance – Scalar or interface-aligned area in
um^2and center-to-center transport distance inum. Both must broadcast over the population’s interfaces. Non-scalar 1-D tensors normally have final dimensionC - 1. A Tree uses compact edge dimensionEin the stable order exposed bymaterial_edge_index. Dendra formsedge_factor = edge_area / edge_distance.edge_factor – Scalar or interface-aligned precomputed geometry factor in
um. Specify this instead ofedge_areaandedge_distance. Diffusive edge conductance isD_edge * edge_factorinum^3 / ms.
- Returns:
self, so registration may be chained.- Return type:
Notes
String-valued components must name registered buffers or parameters so they participate in dtype/device moves and
state_dicthandling. Direct ordinary tensor-like values are registered as Population buffers by this method. A directnn.Parameteris instead registered as a Population parameter and is discoverable throughmodel.parameters(). Differentiable sources preserve autograd.A bound DiffusionProcess samples current source values whenever its spatial operator is configured (normally on the first step after initialization or after explicit timestep reconfiguration), rather than reading them on every timestep. Reconfigure after changing a geometry source.
On the active process region, unbranched control volumes must be finite and positive. Implicit Tree diffusion also permits finite zero-volume algebraic junctions, provided every conductive component contains at least one positive-volume node; explicit Tree diffusion requires every active volume to be positive. Interface area/factor must be finite and non-negative, and explicit edge distances finite and positive. A zero edge factor seals that interface. Validation that depends on the eventual process region is deferred until process binding/operator configuration. Every field using this geometry must declare the same effective chemical domain as
domain.Named Tree geometry reuses the morphology’s immutable parent-child topology while replacing chemical storage volumes and edge weights. It may seal existing edges but cannot add edges or define an independent chemical transport graph.
- register_parametrization(name, parametrization, unsafe=True)[source]#
Register a parametrization hook on a parameter tensor.
- Parameters:
name (str) – Name of the parameter to parametrize.
parametrization (torch.nn.Module) – Module providing the parametrization transform.
unsafe (bool, optional) – Forwarded to
torch.nn.utils.parametrize.register_parametrization().
- register_post_initialize_hook(fn)[source]#
Register a hook executed after model initialization.
- Parameters:
fn (Callable) – Callback invoked with the population instance once initialization completes.
- register_post_initialize_transform(name, module, reads=(), writes=(), inputs=None)[source]#
Register a pure tensor transform after mechanism initialization.
Parameters are canonical tensor references.
inputsis an ordered mapping of explicit tensor inputs owned by the registered action. The stateless module receives(*reads, *inputs)and must return one tuple entry per declared write.- Returns:
The registered private action, including its explicit input buffers.
- Return type:
_InitializationTransformAction
- register_pre_initialize_hook(fn)[source]#
Register a hook executed before model initialization.
- Parameters:
fn (Callable) – Callback invoked with the population instance just prior to mechanism initialization.
Notes
Pre-initialization hooks affect the state from which a steady-state cache is derived. Registering one therefore invalidates any existing steady-state snapshot.
- register_pre_initialize_transform(name, module, reads=(), writes=(), inputs=None)[source]#
Register a pure tensor transform before mechanism initialization.
Parameters are canonical tensor references.
inputsis an ordered mapping of explicit tensor inputs owned by the registered action. The stateless module receives(*reads, *inputs)and must return one tuple entry per declared write.- Returns:
The registered private action, including its explicit input buffers.
- Return type:
_InitializationTransformAction
- restore(name=None)[source]#
Restore a previously cached model state.
This method loads a previously cached state dictionary from the internal cache and applies it to the model. It’s used in conjunction with the cache() method, which saves states.
- Parameters:
name (str, optional) – Identifier for the cached state to restore. If None, restores the state cached as ‘latest’. Default is None.
- Return type:
None
See also
cacheCache the current model state
Examples
>>> model.cache('before_training') # Cache state before training >>> # ... training or simulation ... >>> model.restore('before_training') # Return to cached state
- restore_dict_from_checkpoint(state_dict)[source]#
Restore model state from a checkpoint state dictionary.
- Parameters:
state_dict (dict) – State dictionary containing model parameters and buffers.
- retain_grad(*names)[source]#
Retain gradients for model buffers.
- Parameters:
*names (str) – Variable length argument list of buffer names. If empty, all buffers will have their gradients retained. Otherwise, only buffers matching any of these names will have their gradients retained.
- run(ve=None, extra=None, tstop=None, dt=None, callbacks=None, progressbar=False, *, steps=None, duration=None, inputs=None, draws=None, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#
Run the Population simulation.
- Parameters:
ve (Tensor, optional) – Precomputed time-first extracellular voltage, normalized to
[n_timesteps, *batch, np, n_comp]. Payload axes after time use ordinary trailing broadcasting first; low-rank payloads may use a right-aligned batch-only fallback. Use[n_timesteps, *batch, 1, 1]for explicit per-batch, spatially shared input. The number of time steps is inferred fromve.shape[0].inputs (dendra.func.Inputs, optional) – Strict time-first Tensor tapes. With an explicit horizon, tapes must match its accepted complete steps; otherwise their common leading length determines the horizon. The legacy
ve=/tstopcombination retains the voltage tape’s authoritative length. Explicit voltage cannot duplicateve=orextra=; explicit current cannot replace registered solver-level Slice injections.draws (dendra.func.RuntimeDraws, optional) – Explicit time-leading draw and RNG tapes matching the accepted steps. Mechanism-owned waveform injections consume their accepted-step invocation recipes in native numerical order. Populations with randomized Poisson bank waveforms replay their banks per accepted step. Other waveforms retain full-run preparation. Changing replay chunking does not change the experiment. Omission retains automatic sampling. Base draws remain detached; model/input gradients are kept.
extra (tuple or sequence of tuples, optional) –
Extracellular input specification(s), with the same semantics as
longrun().Each specification is a tuple
(ve_s, time):ve_sis normalized to[*batch, np, n_comp].timeis either aWaveformor a time-last tensor normalized to[*batch, np, n_timesteps].
Both values use ordinary trailing broadcasting first. Only if that fails may low-rank value axes broadcast right-aligned within the explicit batch shape and then be shared over spatial axes. Explicit singleton axes disambiguate equal-size batch and spatial dimensions.
If a single tuple is provided, the method uses a single-contact formulation with
op_sc(). If a sequence of tuples is provided, each tuple is treated as one electrode contact, and the method automatically switches to multi-contact mode usingop_mc():Spatial fields are stacked to shape
[n_contacts, *batch, np, n_comp].Functional (Waveform) inputs are evaluated per time step and expanded/concatenated to shape
[n_contacts, *batch, np, n_timesteps].Non-functional (tensor) inputs are normalized once to that shape.
Mixing
Waveformand tensor time specifications across contacts is not supported and will raise aValueError.If both
veandextraare provided, aValueErroris raised.tstop (float, optional) – Simulation duration in milliseconds to advance from the current model time
self.twhenveis not provided. Only complete fixed timesteps are executed. Any fractional physical duration is retained and combined with the next duration-basedrun,longrun(), orlongrun_checkpointed()call. Ifveis provided, its leading length is authoritative,tstopis ignored, and the retained duration is left unchanged.steps (int, optional) – Exact non-negative step count. Mutually exclusive with
durationandtstop. Leaves retained fractional duration unchanged. Supplied voltage and input tapes must match this count.duration (float, optional) – Non-negative elapsed milliseconds, using the same fractional carry as
tstop. Mutually exclusive withstepsandtstop. Unlike the legacyve/tstopcombination, a supplied voltage tape must match the accepted complete steps.dt (float, optional) – Time step size in milliseconds. If
None, the default valueA.dtfrom the backend is used.callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with
dn.func.make_callbacksfor this Population or a compatible initialized Population. Requesteddtmust honor prepared Recorder cadence and threshold timing. Pure observations read this receiver’s state with fixed prepared selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.progressbar (bool or tqdm, optional) – If
True, displays a progress bar during simulation. Can also be atqdm.tqdminstance for custom progress tracking.callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through
callbacksorfunctional_callbacks. Resumes sampling phase and reducer totals without another initial observation.functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside
callbacks=[...]to combine native hooks and pure observations. Supply the collection through only one argument.functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for
callback_state. Supply carry through only one argument; either collection spelling is accepted.
- Returns:
With pure observations, returns their named results and explicit callback carry. Otherwise returns
None. Model state remains on the Population. Retained observations preserve gradients and are isolated from subsequent native state mutation.- Return type:
Notes
runsupports both precomputedveand the higher-levelextraspecification used bylongrun().When
extrais provided, the underlying construction of extracellular voltage matches the semantics oflongrun(), but the entire simulation is treated as a single chunk.The simulation updates the model’s internal state (e.g.
v,v_prevfor DF methods) and advances the model’s timeself.t.Evaluation mode disables reverse-mode recording with
no_grad; it does not implicitly enabletorch.inference_mode. Entering inference mode around a run can create versionless tensors during lazy solver preparation, which may disable version-checked native topology plans. Prepare the solver outside inference mode when comparing execution-only inference performance, and recreate normal state before subsequently running gradients.
- set_v_init(v_init)[source]#
Set and validate the model’s voltage initial condition.
v_initfollows the same shape rules asexpanded_v_init(). This method does not immediately overwritemodel.v; callinit_v()orinitialize()to apply it.
- slice(include=None, exclude='branchpoint', fuzzy=True, match_case=False, loc=None)[source]#
Finds all indices in the tree structure based on inclusion and exclusion criteria.
- Parameters:
include (str or list of str, optional) – Patterns to include in the search.
exclude (str or list of str, optional) – Patterns to exclude from the search.
fuzzy (bool, optional) – If True, use token-aware glob matching. Punctuation, including underscores, dots, brackets, and parentheses, separates name tokens;
*explicitly matches zero or more characters. Default is True.match_case (bool, optional) – If True, matches case sensitively. Default is False.
loc (float, optional) – If provided, refines the search to the compartment whose ( … )-location is closest to loc (a float in [0, 1]). If None, no refinement is done.
- Returns:
A slice object containing the indices of the matches.
- Return type:
- state_dict_for_checkpoint()[source]#
Get state dictionary for gradient checkpointing.
- Returns:
State dictionary containing model parameters and buffers.
- Return type:
dict
- steady_state(dt=0.2, tstop=200.0, with_ve=True, with_intra=True)[source]#
Relax the model for a fixed duration and cache its resulting state.
- Parameters:
dt (float, default 0.2) – Positive integration timestep in milliseconds.
tstop (float, default 200.0) – Relaxation duration in milliseconds. Executes
int(tstop / dt)steps.with_ve (bool, default True) – Supply an explicit zero extracellular-voltage tensor to the solver. If False, pass no explicit extracellular drive.
with_intra (bool, default True) – Supply an explicit zero intracellular-current tensor to the solver. If False, pass no explicit intracellular drive.
- Returns:
This population, with its clock reset to zero and its state cached for subsequent
initialize()calls.- Return type:
Notes
This is fixed-duration relaxation under
torch.no_grad(), not a convergence test. It clears an earlier steady-state cache and initializes before integrating. The explicit drives above do not evaluate solver-level Slice injections. Mechanism-owned dynamics and injections still run.
- step(dt=None, *, inputs=None, draws=None, ve=None, extra=None, callbacks=None, loop_hooks=False, callback_state=None, functional_callbacks=None, functional_callback_state=None)[source]#
Advance this population by exactly one timestep.
- Parameters:
dt (float, optional) – Timestep in milliseconds. If
None, uses the backend defaultA.dt, matchingrun().ve (Tensor, optional) – Extracellular voltage for this single step, normalized to
[*batch, np, n_comp]. Ordinary trailing PyTorch broadcasting is tried first. If it fails, low-rank data may broadcast right-aligned within the explicit batch shape and be shared spatially. A leading singleton time dimension[1, ...]is also accepted.inputs (dendra.func.Inputs, optional) – One strict Tensor frame of extracellular voltage and/or intracellular current. An explicit
veframe conflicts withve=orextra=; an explicitintraframe conflicts with solver-level Slice injections. Omitted fields retain the existing stimulation sources.draws (dendra.func.RuntimeDraws, optional) – One explicit NOISE/SDE draw frame with authoritative RNG suffixes. Solver-owned intracellular and call-local extracellular Poisson waveform banks, and mechanism-owned waveform injections, consume invocation-indexed draws in native execution order. Omission retains automatic sampling; supplied base draws and schedules remain detached.
extra (extracellular specification, optional) – Higher-level extracellular stimulation specification with the same shape and broadcasting semantics as
run(). It is evaluated at the model’s current time and converted to this step’sve.callbacks (sequence of Callback or dendra.func.FunctionalCallbacks, optional) – Native hook sequence, or a pure collection prepared once with
dn.func.make_callbacksfor this Population or a compatible initialized Population. Requesteddtmust honor prepared Recorder cadence and threshold timing. Pure observations read this receiver’s state with fixed prepared selections. They run after clock advancement and before native post-step hooks. Native hooks retain their loop/chunk/step timing.loop_hooks (bool, optional) – If
True, also callpre_loop_hookbefore the step andpost_loop_hookafter the step. Leave thisFalsewhen manually stepping inside an outer user-controlled loop.callback_state (dendra.func.FunctionalCallbackState, optional) – Carry from the same prepared collection supplied through
callbacksorfunctional_callbacks. Resumes sampling phase and reducer totals without another initial observation.functional_callbacks (dendra.func.FunctionalCallbacks, optional) – Compatibility spelling for the prepared pure collection. Use it alongside
callbacks=[...]to combine native hooks and pure observations. Supply the collection through only one argument.functional_callback_state (dendra.func.FunctionalCallbackState, optional) – Compatibility spelling for
callback_state. Supply carry through only one argument; either collection spelling is accepted.
- Returns:
Returns
selffor chaining when pure observations are omitted. With pure observations, returns their named results and explicit callback carry. Model state remains on the Population. Retained observations preserve gradients and own their sampled tensor values.- Return type:
- terminal_indices()[source]#
Indices of terminal nodes in the morphology tree.
- Returns:
Node indices that have no outgoing edges in
self.graph.- Return type:
list of int
- to(*args, **kwargs)[source]#
Move the population to a new device or dtype.
- Parameters:
*args (Any) – Positional arguments forwarded to
torch.nn.Module.to().**kwargs (Any) – Keyword arguments forwarded to
torch.nn.Module.to().
- Returns:
The population instance after conversion.
- Return type:
Notes
Changing device or dtype after initialization moves mechanism scratch, rebuilds point-process scaling closures, and invalidates derived solver coefficients. Direct Population execution rebuilds the solver workspace lazily. If this population belongs to an already-built Network, reinitialize the Network before execution so all owner state is current.
- unfreeze_group(*groups)[source]#
Unfreeze parameter groups stored as module attributes.
- Parameters:
*groups (str) – Attribute names of iterable parameter collections to unfreeze.
- Returns:
The population instance for chaining.
- Return type:
- property area#
Returns the area of the population.
- property graph#
Returns the graph of the population. This is a placeholder for future graph-related functionality.
- property shape#
Shape tuple of the membrane potential tensor.
- Returns:
Dimensions of
self.vincluding any batch axes.- Return type:
tuple of int
Model families#
Subclasses share the lifecycle above. Their entries describe construction and family-specific geometry. See Morphology and compartment geometry for sections and compartment graphs, and 02a. Native section morphologies for examples.
- class SingleCompartment(N=1, C=1, integrator=None, v_init=-65.0, *, preserve_mechanism_population_axis=None, device=None, dtype=None, **kwargs)[source]#
A Population subclass representing single compartment neuron(s).
This class is a convenience wrapper around the Population class, pre-configured for a single compartment model.
- class Cable(N, C, graph=None, integrator=None, **kwargs)[source]#
Generic unbranched cable using Dendra’s tridiagonal fast path.
Cableis the geometry-general counterpart toAxon. It can represent any material-only native Section morphology whose compiled electrical graph is one simple path, including tapered pt3d Sections and heterogeneous Section membrane properties. Exact compiled membrane areas and axial edge resistances remain the numerical source of truth.Construct native cables with
from_morphology()orfrom_compartment_graph(). The ordinary constructor is primarily the shared implementation base for specialized path models such asAxon.- property compartment_graph#
Immutable path-ordered canonical morphology snapshot, if present.
- property edge_resistance_ohm#
Child-indexed exact axial resistance, including a zero root entry.
- material_volume(domain='intracellular')[source]#
Return an exact native-cable material-domain volume buffer.
- classmethod from_compartment_graph(graph, N=1, integrator=None, **kwargs)[source]#
Construct a fast generic cable from a canonical material path.
The source graph is reordered deterministically from one physical end to the other. Branches and retained zero-area junctions are rejected. Exact edge resistance and membrane area are retained rather than being reconstructed from one representative compartment diameter and length.
- classmethod from_morphology(morphology, N=1, integrator=None, **kwargs)[source]#
Compile a native Section path and construct a generic Cable.
Construction takes an immutable snapshot. Later Section updates on the source Morphology do not affect this Cable; call
from_morphologyagain to build a Cable from the revised declaration.
- class Axon(diameters, n_comp, celsius=37.0, v_init=-80.0, integrator=None, **kwargs)[source]#
Base 1D fiber class.
This is the base class for axon models, implementing common functionality for simulating action potential propagation along 1D fibers.
Notes
{py:class}`~dendra.models.core.Unmyelinated` and {py:class}`~dendra.models.core.Myelinated` extend this class.
The axon is represented as a series of compartments arranged in a line, with each compartment having its own diameter and biophysical properties. All axon classes by defalt are instantiate such that all compartments lie along the x-axis (y=z=0), with the central compartment at x=0 (thereby spanning from -axon_length/2 to axon_length/2).
- register_cid(cid)[source]#
Register compartment names and expose their labelled slices.
This connects a model-definition
CompartmentIDto an axon. Each unique name becomes both an entry in_labelsand an attribute containing the correspondingSlice.- Parameters:
cid (dendra.models.heterogeneous.CompartmentID) – Identifier table whose expanded
namesarray has lengthn_comp.
Examples
from dendra.models.core import Unmyelinated from dendra.models.heterogeneous import CompartmentID from dendra.units import um axon = Unmyelinated(diameters=[8.0], L=60.0 * um, dx=10.0 * um) cid = CompartmentID(["node", "internode * 2"], n_repeats=2) axon.register_cid(cid) axon.node # compartments 0, 3, and 6 axon.internode # compartments 1, 2, 4, and 5
- c(*args)[source]#
Convert relative positions to node indices.
- Parameters:
*args (float) – Variable number of float values between 0 and 1, representing relative positions along the axon.
- Returns:
List of integer node indices corresponding to the input positions.
- Return type:
list
Examples
>>> model.c(0.25, 0.5, 0.75) [25, 50, 75] # For a model with n_comp=101
- class Unmyelinated(diameters, L=1000.0, dx=10.0, celsius=37.0, v_init=-80.0, integrator=None, **kwargs)[source]#
Base unmyelinated axon model class.
This class implements a model of unmyelinated axons (nerve fibers without myelin sheaths) by extending the base Axon class. It uses a uniform spatial discretization with nodes spaced at regular intervals.
- Parameters:
diameters (array_like) – Diameters of the axons in μm. Can be a single value, list, or tensor.
L (float, optional) – Requested axon length in μm. Bare values are interpreted as μm; use
dendra.units.mmwhen specifying millimetres. Default is1.0 * mm(1000 μm).dx (float, optional) – Spatial discretization step in μm. Default is 10.0 μm.
celsius (float, optional) – Temperature in degrees Celsius. Default is 37°C.
v_init (float, optional) – Initial membrane potential in mV. Default is -80 mV.
integrator (Integrator, optional) – The integrator to use for the simulation. If None, a default backward Euler integrator will be used.
Notes
The number of nodes is calculated to ensure it’s odd (for a centered node at position 0).
See also
AxonBase class providing common functionality for axon models.
MyelinatedCompanion class implementing myelinated axon models.
- class Myelinated(diameters, n_node, node_length=2.0, celsius=37.0, v_init=-80.0, integrator=None, **kwargs)[source]#
Myelinated axon model with quadratic geometry scaling.
Nodes of Ranvier are separated by myelinated internodes. Geometric quantities (axon diameter, node diameter, and internodal spacing) are derived from the fiber diameter via simple quadratic fits defined by the class-level
GLOBAL(axon_d, node_d, delta_x)coefficients.- Parameters:
diameters (array_like) – Fiber diameters in µm; scalar or sequence broadcast to the population.
n_node (int) – Number of nodes of Ranvier (compartments) in the model.
node_length (float, optional) – Physical length of each node in µm used to set
dx. Default is 2.0.celsius (float, optional) – Temperature in degrees Celsius. Default is 37.
v_init (float, optional) – Initial membrane potential in mV. Default is -80.
integrator (Integrator, optional) – Integrator instance. If
None, a backward Euler integrator is used.**kwargs (Any) – Additional arguments forwarded to
Axon.
Notes
Geometry
For a fiber diameter \(D\) (µm), the derived quantities are
\[\begin{split}d_\text{axon}(D) &= a_1 D^2 + a_2 D + a_3 \\ d_\text{node}(D) &= n_1 D^2 + n_2 D + n_3 \\ \Delta x(D) &= \delta_1 D^2 + \delta_2 D + \delta_3\end{split}\]Coefficients are taken from
GLOBAL(axon_d=..., node_d=..., delta_x=...). Defaults are:axon_d: \(a_1=0.0\), \(a_2=0.7\), \(a_3=0.0\)node_d: \(n_1=0.0\), \(n_2=0.7\), \(n_3=0.0\)delta_x: \(\delta_1=0.0\), \(\delta_2=100.0\), \(\delta_3=0.0\) (center-to-center internodal spacing)
node_lengthcontrols the physical node extent used for per-nodedx, whiledeltax()evaluates the center-to-center spacing polynomial above.
- class Tree(N, C, graph=None, integrator=None, principal_axis=None, **kwargs)[source]#
Base class for tree-like population models. All neuron morpholgies can be represented as trees of connected compartments. Dendra Axon classes specifically model unbranched axons, while Tree models can represent arbitrary tree-like morphologies with branching structures.
- Parameters:
N (int) – Number of population instances.
C (int) – Number of compartments per population.
graph (networkx.DiGraph, optional) – Morphology graph describing tree structure.
integrator (callable, optional) – Integrator factory used for simulation.
**kwargs – Additional parameters forwarded to
Population.
- property graph#
Mutable morphology interoperability view.
Simulation topology is the immutable compiled
compartment_graph(and its registered topology buffers). Mutating this NetworkX view does not recompile the Tree; construct a new Tree to change morphology.- Type:
networkx.DiGraph
- property compartment_graph#
Canonical immutable morphology snapshot aligned to model storage.
The legacy
graphview remains available for NetworkX-based interoperability.compartment_graphrecords the validated geometry, topology, material domains, and provenance used at construction time.
- property area#
Exact compiled membrane area in square centimetres.
A Tree is a compiled simulation object. Its public NetworkX
graphremains mutable for interoperability, but changing that view must not change the numerical model piecemeal. Read membrane area from the same immutableCompartmentGraphsnapshot that owns electrical topology and axial resistance.
- property edge_resistance_ohm#
Exact child-indexed compiled axial resistance in ohms.
The root entry is zero; every other entry is the complete resistance between that compartment and its parent. Values are shared across the population axis and retain the model’s current dtype and device.
- property material_edge_index: LongTensor#
Return the compact parent-child material edge index.
- Returns:
Tensor with shape
(2, E). Row zero contains parent compartment indices and row one contains the corresponding child compartment indices. A connected Tree withCcompartments hasE = C - 1edges.- Return type:
torch.LongTensor
Notes
Edges are oriented away from the morphology root and ordered by increasing child storage index, with the root omitted. This edge axis is the stable ordering for edge-located material geometry and diffusivity. Topology is shared by every population instance and batch replica, so this tensor has no population or batch axis. It is derived from registered topology buffers, follows model device moves, and does not add duplicate checkpoint state.
- property material_edges: tuple[LongTensor, LongTensor]#
Return compact material edges as
(parent, child)tensors.This is the unpacking-oriented form of
material_edge_index:parent, child = tree.material_edgesBoth tensors have shape
(E,)and use the same stable compact edge ordering documented bymaterial_edge_index.
- material_volume(domain='intracellular')[source]#
Return the volume/mass buffer appropriate for a material domain.
- Parameters:
domain (str, optional) – Domain name or alias.
"i","inside","cytosol", and"intracellular"returnvolume_i."o"and"extracellular"returnvolume_o."total"returnsvolume."membrane"/"surface"return membrane area, which is useful for future surface-density material processes.
- classmethod from_graph(graph, N=1, integrator=None, **kwargs)[source]#
Instantiate a tree population from a morphology graph.
- Parameters:
graph (networkx.DiGraph) – Connected directed tree describing compartment connectivity. Node labels that are not already
0..n-1are deterministically relabelled in graph insertion order on an internal copy.N (int, optional) – Number of population instances. Defaults to
1.integrator (callable, optional) – Integrator factory. Defaults to
dendra.models.integrators.dhs().**kwargs – Additional membrane parameters forwarded to
Tree.
- Returns:
Configured tree population.
- Return type:
- Raises:
ValueError – If the graph is empty, cyclic, disconnected, contains a self-loop, or gives a node more than one parent.
- classmethod from_compartment_graph(graph, N=1, integrator=None, **kwargs)[source]#
Construct a Tree from Dendra’s canonical compartment graph.
- Parameters:
graph (dendra.models.morphology.CompartmentGraph) – Immutable scalar compartment resistor tree.
N (int, optional) – Number of copies of the morphology.
integrator (callable, optional) – Scalar tree integrator factory.
**kwargs – Membrane parameter overrides forwarded to
from_graph().
- classmethod from_morphology(morphology, N=1, integrator=None, **kwargs)[source]#
Discretize a native Section morphology and construct a Tree.
Native and NEURON-authored morphologies converge on the same scalar compartment resistor-graph contract. Compilation is a snapshot: subsequently adding or updating Sections on the source builder cannot mutate the constructed model. Call
from_morphologyagain to build a model from the revised declaration.- Parameters:
morphology (dendra.models.morphology.Morphology) – Connected native Section tree with explicit
nsegvalues.N (int, optional) – Number of population instances.
integrator (callable, optional) – Scalar tree integrator factory.
**kwargs – Membrane parameter overrides forwarded to
from_graph().
- classmethod from_NEURON(root_sec=None, N=1, integrator=None, principal_axis=None, exclude=None, **kwargs)[source]#
Construct a tree population from a NEURON root section.
Geometry and the existing compartment grid are captured without changing
nseg. Configure the NEURON Section tree before capture.- Parameters:
root_sec (neuron.h.Section, optional) – Root section of a NEURON morphology.
N (int, optional) – Number of population instances. Defaults to
1.integrator (callable, optional) – Integrator factory for the population.
**kwargs – Additional keyword arguments forwarded to
from_graph().
- Returns:
Configured tree population.
- Return type:
- classmethod from_swc(file_path, d_lambda=0.1, freq=100.0, N=1, integrator=None, principal_axis=None, **kwargs)[source]#
Load SWC geometry, discretize a native Morphology, and construct a Tree.
SWC parsing uses
from_swc(), including its sample, naming and validation conventions. Compartment counts are selected byapply_d_lambda(). The native pipeline requires no NEURON objects.- Parameters:
file_path (str) – Path to the SWC morphology file.
d_lambda (float, optional) – Dimensionless spatial-discretisation factor for tree reconstruction.
freq (float, optional) – Frequency in hertz used by native d-lambda discretization. Pass a raw hertz value such as
freq=100.0. This morphology-only argument is intentionally an exception to Dendra’s usual kHz (1/ms) frequency convention, so do not multiply it bydendra.units.Hz.N (int, optional) – Number of population instances. Defaults to
1.integrator (callable, optional) – Integrator factory for the population.
**kwargs – Membrane parameters forwarded to
from_morphology().rhoaandcmalso determine spatial discretization; their defaults here are35.4Ω·cm and1µF/cm².
- Returns:
Configured tree population.
- Return type:
- classmethod from_neurolucida(file_path, d_lambda=0.1, freq=100.0, N=1, integrator=None, principal_axis=None, *, root=None, **kwargs)[source]#
Load Neurolucida geometry and discretize it as a native Morphology.
NEURON’s file reader supplies the normalized geometry through
from_asc(). Compartment selection and graph compilation operate on the resulting native snapshot, which holds no NEURON objects.- Parameters:
file_path (str) – Path to the Neurolucida morphology file.
root (str, optional) – Exact imported root Section name, such as
"soma[0]". Required when the file contains several disconnected cable trees.d_lambda (float, optional) – Dimensionless spatial-discretisation factor for tree reconstruction.
freq (float, optional) – Frequency in hertz used by native d-lambda discretization. Pass a raw hertz value such as
freq=100.0. This morphology-only argument is intentionally an exception to Dendra’s usual kHz (1/ms) frequency convention, so do not multiply it bydendra.units.Hz.N (int, optional) – Number of population instances. Defaults to
1.integrator (callable, optional) – Integrator factory for the population.
**kwargs – Membrane parameters forwarded to
from_morphology().rhoaandcmalso determine spatial discretization; their defaults here are35.4Ω·cm and1µF/cm².
- Returns:
Configured tree population.
- Return type:
- classmethod from_asc(file_path, d_lambda=0.1, freq=100.0, N=1, integrator=None, principal_axis=None, *, root=None, **kwargs)#
Load Neurolucida geometry and discretize it as a native Morphology.
NEURON’s file reader supplies the normalized geometry through
from_asc(). Compartment selection and graph compilation operate on the resulting native snapshot, which holds no NEURON objects.- Parameters:
file_path (str) – Path to the Neurolucida morphology file.
root (str, optional) – Exact imported root Section name, such as
"soma[0]". Required when the file contains several disconnected cable trees.d_lambda (float, optional) – Dimensionless spatial-discretisation factor for tree reconstruction.
freq (float, optional) – Frequency in hertz used by native d-lambda discretization. Pass a raw hertz value such as
freq=100.0. This morphology-only argument is intentionally an exception to Dendra’s usual kHz (1/ms) frequency convention, so do not multiply it bydendra.units.Hz.N (int, optional) – Number of population instances. Defaults to
1.integrator (callable, optional) – Integrator factory for the population.
**kwargs – Membrane parameters forwarded to
from_morphology().rhoaandcmalso determine spatial discretization; their defaults here are35.4Ω·cm and1µF/cm².
- Returns:
Configured tree population.
- Return type:
- recentre(x=0.0, y=0.0, z=0.0, origin=None)[source]#
Recentre the morphology so the soma matches
origin.- Parameters:
x (float or torch.Tensor, optional) – Target x-coordinate for the soma.
y (float or torch.Tensor, optional) – Target y-coordinate for the soma.
z (float or torch.Tensor, optional) – Target z-coordinate for the soma.
origin (int or None, optional) – Compartment index of the soma. Defaults to the middle soma node.
- Returns:
Modified instance for chaining.
- Return type:
- shift(dx=0.0, dy=0.0, dz=0.0)[source]#
Translate the morphology by the specified offsets.
- Parameters:
dx (float or torch.Tensor, optional) – Offset along the x-axis.
dy (float or torch.Tensor, optional) – Offset along the y-axis.
dz (float or torch.Tensor, optional) – Offset along the z-axis.
- Returns:
Modified instance for chaining.
- Return type:
- move_to(x=0.0, y=0.0, z=0.0, origin=None)[source]#
Move the morphology so the soma lies at
(x, y, z).- Returns:
Modified instance for chaining.
- Return type:
- rotate_into_direction(target_directions, origin=None)[source]#
Rotates cells to align their current directions with target directions.
- Parameters:
target_directions (torch.Tensor) – A (B, 3) or (1, 3) tensor of target directions.
origin_idx (int) – The index of the compartment to use as the rotation origin.
- rotate_azimuthal(azimuthal_angle, origin=None)[source]#
Rotates cells around their current direction vector by a given angle.
- Parameters:
azimuthal_angle (float or torch.Tensor) – Angle in degrees. Can be a single float or a (B,) tensor for individual angles.
origin_idx (int) – The index of the compartment to use as the rotation origin.
- class ExtCellAxon(diameters=[10.0], n_comp=101, celsius=37.0, v_init=-80.0, n_layers=2, integrator=None, **kwargs)[source]#
Axon model with two-layer extracellular coupling.
- Parameters:
diameters (Sequence[float], optional) – Compartment diameters in micrometers.
n_comp (int, optional) – Number of compartments per axon.
celsius (float, optional) – Simulation temperature in degrees Celsius.
v_init (float, optional) – Initial membrane voltage in millivolts.
n_layers (int, optional) – Number of extracellular layers. Only
2is currently supported.integrator (callable, optional) – Integrator factory used to create the simulation solver.
**kwargs – Additional population parameters such as
dtype,device,rhoa, andcmforwarded toAxon.
- class ExtCellTree(N, C, graph, n_layers=2, integrator=None, **kwargs)[source]#
Tree model supporting extracellular coupling layers.
- Parameters:
N (int) – Number of tree instances (populations).
C (int) – Number of compartments per tree.
graph (networkx.Graph) – Morphology graph describing compartment connections.
n_layers (int, optional) – Number of extracellular layers. Only
2is currently supported.integrator (callable, optional) – Integrator factory used to create the solver.
**kwargs – Additional parameters forwarded to
Tree.
- load_extcell(extcell)[source]#
Load extracellular parameters into buffers.
- Parameters:
extcell (dict[str, torch.Tensor]) – Mapping of extracellular parameter names to tensors shaped
(1, n_comp, n_layers).
- load_morphology(morphology)[source]#
Register morphology tensors as buffers.
- Parameters:
morphology (dict[str, torch.Tensor]) – Mapping of morphology parameter names to tensors shaped
(1, n_comp).
- load_diffusion_edges(diffusion_edges)[source]#
Register child-indexed and compact tree-diffusion metadata.
- classmethod from_graph(graph, N=1, n_layers=2, integrator=None, **kwargs)[source]#
Construct an extracellular tree model from a morphology graph.
- Parameters:
graph (networkx.Graph) – Morphology graph with extracellular attributes.
N (int, optional) – Number of population instances. Defaults to
1.n_layers (int, optional) – Number of extracellular layers. Supports only
2at present.integrator (callable, optional) – Integrator factory. Defaults to backward Euler branching tree.
**kwargs – Additional membrane parameters forwarded to
Tree.
- Returns:
Configured tree population with extracellular coupling.
- Return type:
- classmethod from_NEURON(root_sec=None, N=1, n_layers=2, integrator=None, **kwargs)[source]#
Construct an extracellular tree from a NEURON section.
- Parameters:
root_sec (neuron.h.Section, optional) – Root section from a NEURON model.
N (int, optional) – Number of population instances. Defaults to
1.n_layers (int, optional) – Number of extracellular layers. Supports only
2at present.integrator (callable, optional) – Integrator factory to use for the tree.
**kwargs – Additional keyword arguments forwarded to
from_graph().
- Returns:
Constructed extracellular tree instance.
- Return type:
Tree file constructors select compartment counts through native Morphology
declarations. from_NEURON instead captures the source Section tree’s existing
grid. Spatial methods translate or rotate the constructed model’s coordinates
in place. See 02. Branched morphologies for placement examples.
Morphology graph helpers#
These helpers measure length-weighted paths through a morphology graph in either direction, treating its directed edges as undirected connections.
- distance(cell, origin, targets, *, origin_offset=0.0)[source]#
Return undirected, length-weighted distances between cell compartments.
- Parameters:
cell (object) – An object whose
graphattribute is a NetworkX graph. Edges are weighted by theirLattribute.origin (node label or slice) – Source node. For a canonical Dendra cell, a slice is resolved against compartment storage order. For a generic graph-bearing object, it is resolved against graph node iteration order. The first selected node is used.
targets (node label, iterable of node labels, or slice) – Destination node or nodes. Slice resolution follows the same canonical storage-order or generic graph-order rule as
origin.origin_offset (float or scalar tensor, optional) – Additional path length added to every result. This makes endpoint origins explicit when the graph stores compartment-center distances; for example, a one-segment soma origin at
soma(0)may require half the soma length. Defaults to zero.
- Returns:
One distance per requested target, in target order. Unreachable targets have distance
inf. A scalar target produces a one-element tensor.- Return type:
torch.Tensor
- Raises:
ValueError – If the graph is unavailable or misaligned with canonical storage, or if an origin, target, or offset selector is invalid.
- undirected_weighted_lengths(G, origin, targets, weight_attr='L')[source]#
Return shortest-path distances while ignoring edge direction.
- Parameters:
G (nx.Graph) – Graph whose edges carry the numeric attribute named by
weight_attr. Directed graphs are viewed as undirected.origin (node label) – The single source node.
targets (node label or iterable of node labels) – Node or nodes for which to return distances. A node label that is itself iterable, such as a tuple, is treated as a scalar when it is present in
G.weight_attr (str, optional) – Edge attribute storing length or weight. Defaults to
"L".
- Returns:
A one-dimensional CPU tensor containing one distance per target. Unreachable targets are represented by
inf.- Return type:
torch.Tensor
Packing independent models#
concat_models combines independent scalar models into a MultiPopulation
without adding electrical connections. Components must share device and dtype.
Named components remain selectable as Slice regions for recording and stimulation.
- concat_models(populations, threads=16, write_back=True, celsius=37.0, v_init=None)[source]#
Pack independent populations into one
MultiPopulation.Ordinary
PopulationandSingleCompartmentmodels, branchedTreemodels, and scalarCablemodels (including Axon subclasses) can be combined in one call. Mixed scalar components use the universal packed DHS solver; a collection containing only independent point compartments keeps the optimized single-compartment multi-integrator.Alternatively, two-layer
ExtCellAxonandExtCellTreecomponents can be combined in a block-DHS pack. Scalar and finite-extracellular components cannot be mixed.Concatenation does not create axial edges between component populations. It packs their independent electrical systems into one launch and exposes each component name as a labelled Slice on the composite model.
- Parameters:
populations (dict[str, Population]) – Mapping of unique component names to unbatched populations. All components must share a device and dtype.
threads (int, optional) – DHS lane count for packed Tree/Cable groups. Must divide 32.
write_back (bool, optional) – If
True, write solvedv(and blockvc) views to components after each step. IfFalse, only the composite voltage is updated.celsius (float, optional) – Common simulation temperature.
v_init (scalar, tensor-like, dict[str, tensor-like], optional) – Optional initial voltage override for the combined model. If
None, each component population contributes its own expandedv_init. If a mapping is provided, keys are population names and omitted populations keep their ownv_init.
- Returns:
Combined population. Call
MultiPopulation.batch()on this result when explicit leading batch dimensions are required.- Return type:
Notes
A packed extracellular system retains both membrane voltage
vand absolute circuit potentialsvc. Concatenation still creates no edges between components. NestedMultiPopulationobjects are unsupported.
- class MultiPopulation(integrator=None, celsius=37.0, v_init=None, **populations)[source]#
One packed model composed of independent scalar or extracellular models.
Prefer
concat_models()so Dendra can select the appropriate packed integrator. Component topology, geometry, physical scale factors, mechanisms, injections, initial voltages, and structural labels remain component-specific; temperature is shared by the composite.- Parameters:
integrator (callable, optional) – Integrator factory. Selected automatically when
None.celsius (float, optional) – Shared simulation temperature.
v_init (scalar, tensor-like, dict[str, tensor-like], optional) – Initial voltage for the composite population. If
None, the compositev_initis built by expanding and concatenating each component population’s ownv_init. If a mapping is provided, keys are component population names and omitted populations keep their ownv_init.**populations – Mapping of population names to unbatched instances on one device and dtype. Supported public components are ordinary Population, SingleCompartment, Tree, Cable, Unmyelinated, and Myelinated models, or a collection containing only ExtCellAxon and ExtCellTree models.
Notes
write_back=Trueis an integrator-factory option supplied byconcat_models(), not a constructor argument here. Scalar/block mixtures and nested MultiPopulation components are rejected fail-closed.- property material_edge_index#
Independent chemical edges in stable packed child-storage order.
- property material_edges#
- material_volume(domain='intracellular')[source]#
Return exact component chemical storage volumes, not a packed tube.
- material(name, fields=None, *, initial_values=None, min_values=None, specs=None, domain=None, units=None, conserved=None, **field_initials)[source]#
Declare packed-parent fields globally without changing other fields.
Fields inherited from children retain their independent availability. Explicitly reconfiguring a field on the packed parent makes that field available throughout the parent. Partial updates preserve the other fields and their metadata; they do not discard concatenated specs.
- set_v_init(v_init)[source]#
Set composite initial voltage, with optional per-population mapping.
v_initmay be any form accepted byPopulation.expanded_v_initfor the flattened composite model, or a mapping from component population name to that population’s own scalar/vector/full-shape initial voltage specification.
Axon region identifiers#
- class CompartmentID(names, n_repeats, wrap=True)[source]#
Describe the repeating compartment labels in an axon model.
CompartmentIDis a model-definition helper for axons assembled from a repeated sequence of named regions. Entries such as"internode * 3"are expanded before the sequence is repeated. The resultingnamesarray can be registered withdendra.models.core.Axon.register_cid()to enable name-based slicing and install one labelledSliceper unique compartment name.- Parameters:
names (list of str) – One repeat of the compartment-name pattern. A value of the form
"name * count"contributescountadjacent copies ofname.n_repeats (int) – Number of times to repeat the expanded pattern.
wrap (bool, default=True) – Append the first entry in
namesafter the final repeat. This is useful for models whose repeated units share a boundary node.
- names#
Expanded compartment labels. Its length should equal
axon.n_compbefore the table is passed toregister_cid().- Type:
numpy.ndarray
Examples
A two-unit model with a shared node at the distal boundary has seven compartments:
>>> cid = CompartmentID(["node", "internode * 2"], n_repeats=2) >>> cid.names.tolist() ['node', 'internode', 'internode', 'node', 'internode', 'internode', 'node'] >>> cid.loc("node") [0, 3, 6]
- build(funcs, model)[source]#
Build a per-axon, per-compartment NumPy parameter array.
- Parameters:
funcs (Mapping[str, Callable]) – Mapping from every unique compartment name to a callable. Each callable receives
modeland returns one value per axon.model (Axon) – Model exposing
n_axandn_comp. Its compartment count must match this table.
- Returns:
Array of shape
(model.n_ax, model.n_comp). Values returned for each name are copied into every compartment carrying that label.- Return type:
numpy.ndarray
Intrinsic stimulation and boundary helpers#
- insert_intrinsic_activity(target, onsets, *, tau=0.1, gmax=0.1, e=0.0)[source]#
Insert an excitatory alpha-conductance event train on a Slice.
- Parameters:
target (Slice) – Physical compartments that receive the activity. Empty Slices are a no-op.
onsets (scalar or array_like) – Event times in ms. A scalar creates one event. A one-dimensional
(K,)value is a sharedK-event train and is normalized to(K, 1). Two-dimensional values use explicit(events, locations)layout:(K, 1)shares a train across the Slice, while(K, L)supplies one onset per event and flattened physical location.tau (scalar or array_like, optional) – Alpha time constant in ms. Defaults to
0.1.gmax (scalar or array_like, optional) – Peak point-process conductance in microSiemens. Defaults to
0.1.e (scalar or array_like, optional) – Reversal potential in mV. Defaults to
0.0.
Notes
Repeated calls add independent colocated events. Non-scalar
tau,gmax, andevalues use the copied RANGE contract: provide(K, 1),(1, L),(K, L), or exactlyK * Lvalues rather than an ambiguous short one-dimensional vector. This is a structural model edit; callinitialize()before the next simulation run.
- remove_intrinsic_activity(target)[source]#
Remove helper-created intrinsic activity intersecting a Slice.
Every event/copy created by
insert_intrinsic_activity()at the selected physical compartments is removed. Activity outside the Slice and ordinaryalphasynapseinsertions are preserved. Removing absent activity or targeting an empty Slice is a no-op. This is a structural model edit; callinitialize()before the next simulation run.
- passive_end_nodes_(model, n=1, rhoa=10000000000.0, cm=1.0, *, e=None, diam=None)[source]#
Replace both ends of a cable region with passive membrane mechanisms.
Select the first and last
nentries of the target’s final axis. For a Slice these are its local ends, in its selected order. Overlapping ends and repeated physical compartments are configured only once;n=0and empty targets are no-ops. A scalar Slice selects its single compartment.Every mechanism on the selected support is removed and replaced by
paswithg=1e-4S/cm².e=Noneuses each compartment’s initial voltage; otherwiseeis a reversal in mV broadcastable to the root Cable’s full voltage shape(*batch, N, C). Values always use root coordinates, even for a Slice. Use(N, 1)for per-cell values or(*batch, 1, 1)for per-replica values. Only selected compartments receive the override.rhoa(ohm cm) andcm(µF/cm²) overrides default to1e10and1; passNoneto leave either property unchanged. Native morphology-compiled Cables requirerhoa=Nonebecause their compiled resistivity is immutable.diamoptionally sets a finite positive scalar diameter in µm at the selected ends;Nonepreserves their diameters. For parametrized geometry such as Myelinated, the override applies after the diameter transform, so it specifies the effective node diameter while other nodes retain their original parametrization. Diameters are shared across batch replicas. Native morphology-compiled Cables requirediam=None; edit the source Morphology and construct a new Cable to change their geometry.Mechanism placement is shared by all batch replicas, including when the Slice selects one replica; reversal values may differ across replicas. Call
model.initialize()(orslice.model.initialize()) before running the modified population. The target’s initial voltage and current state are not reset by this helper.
See also Slices and synapse slots, Networks, connections and event sources, Numerical integrators, and Stimulation, input tapes and randomness.