Mechanisms, state equations and materials#
Subclass Mechanism to define membrane currents, State to define state equations,
and the process classes below to interact with shared ions/materials. See
Custom models and explicit functional execution and Writing your own synapse for examples.
Parameter declarations such as RANGE and GLOBALRAND are inherited from
Parameterized; their reference is
Parameters and random distributions.
Current units and conductance#
Distributed Mechanism currents are outward-positive densities in mA/cm² with conductance in S/cm². PointProcess currents are in nA with conductance in µS; Dendra performs the area conversion. Voltages and reversal potentials are in mV. See Units used in Dendra before mixing distributed and point-process parameters.
An affine current may provide i_affine_terms(v) -> (G, J) for I=G*v-J
and declare Mechanism.AFFINE("i"). An exact i_with_conductance pair is
also supported. Mechanism.NUMERICAL opts into numerical conductance for
local deterministic currents. These declarations do not make a nonlocal or
state-mutating current valid. dn.ctx(MEMBRANE_ASSEMBLY="validate") enables
additional affine-contract diagnostics.
Mechanism and State hooks#
- class Mechanism(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Base class for Dendra mechanisms.
Mechanisms encapsulate state variables, ionic currents, and parameter declarations that can be attached to neuronal morphologies. They extend
dendra.models.parametric.Parameterizedto leverage the shared parameter declaration and population infrastructure.Use uppercase classmethods (
STATE_BUNDLE,GLOBAL,RANGE,CARRY,USEION,NONSPECIFIC_CURRENT, etc.) at class definition time to declare structure. Override pure lowercase hooks (initial_values,assigned_values,advance, current methods) to implement behavior.STATE_BUNDLE(StateSubclass, ...): register one or more State bundles. Each State subclass manages its own state variables and derivatives. These are accessible via themechanism.DEModuleDict.GLOBAL/RANGE: shared vs per-compartment parameters.CARRY: persistent non-ODE simulation state.ASSIGNED: repeatable ephemeral algebra.USEION: ionic read/write dependencies.NONSPECIFIC_CURRENT/ current methods: contribute to membrane balance.initial_values(self, v, values): pure initialization overlay.assigned_values(self, v, values): pure repeatable algebra.advance(self, v, dt, values): accepted-timestep transition.
Notes
An ordinary
Mechanismis a distributed membrane mechanism. Its voltage and reversal potentials are in mV, each declared current method returns outward-positive current density in mA/cm², and the corresponding voltage derivative/conductance is in S/cm². Thus a density-style Ohmic current is written directly asg * (v - e)becauseS/cm² * mV = mA/cm². Dendra keeps these values as densities during mechanism assembly and applies compartment area in the voltage solver.Inherit from
PointProcesswhen a mechanism instead returns a lumped current in nA and uses conductance in µS. The conversion factors indendra.unitsare plain scalars for documented public base units; do not form density units with expressions such asS / cm**2.Subclasses declare nested state, persistent
CARRY(), ephemeralASSIGNED(), and ionic/material dependencies during class definition.initial_valuesandadvancedefine persistent initialization and one accepted-timestep transition;assigned_valuesdefines repeatable current-stage algebra. All hook inputs are read-only. Dendra may reuse one gathered voltage tensor across mechanisms that occupy the same ordered support, and may evaluate assigned/current algebra more than once per step.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- classmethod material_summary(*, include_ions=True, include_empty=False)[source]#
Return a printable summary of Material and Ion usage.
- Parameters:
include_ions (bool, default True) – Include
USEIONdeclarations in the summary. Ions are treated as specialized materials for the purpose of this report.include_empty (bool, default False) – If True, include empty
materials/ionsblocks even when the mechanism declares none.
- Returns:
Human-readable multi-line summary.
- Return type:
str
Examples
>>> print(MyMechanism.material_summary()) MyMechanism material usage: ions: ca: read=ica, write_concentration=cai materials: ip3: read=ip3i, source=ip3i→j_ip3
- classmethod material_usage(*, include_ions=True)[source]#
Return structured material/ion dependency metadata for this class.
- Parameters:
include_ions (bool, default True) – If True, include
USEIONdeclarations alongside genericUSEMATERIALdeclarations. Ion entries usereadfor concentration/reversal/current reads,write_currentfor ionic current writes such asica, andwrite_concentrationfor concentration writes such ascai.- Returns:
A dictionary with
"materials"and, when requested,"ions"entries. The result is intended for debugging, documentation, and population-build diagnostics; it does not require mechanism instantiation.- Return type:
dict
- classmethod rename(new_name=None, suffix=None)[source]#
Create a renamed clone of the current mechanism class.
- Parameters:
new_name (str, optional) – Explicit name for the cloned class. Required when
suffixisNone.suffix (str, optional) – Suffix appended to the original class name when
new_nameis omitted.
- Returns:
Mechanism subclass identical to
clsbut with a new__name__.- Return type:
type
- Raises:
ValueError – If both
new_nameandsuffixareNone.TypeError – If
suffixis provided but not a string.
- classmethod state_names()[source]#
Collect state variable names declared by the mechanism class.
- Returns:
Names of state variables registered in
cls._state.- Return type:
list of str
- static AFFINE(*args)[source]#
Assert that currents are exactly affine functions of voltage.
- Parameters:
*args (str) – Current names satisfying
I(v) = G * v - J, whereGandJdo not depend onvwith gates and assigned values held fixed during the solver stage.
Notes
This declaration authorizes coefficient assembly and exact affine centering in Dufort–Frankel. Existing currents and analytic/numerical conductance pairs remain sufficient. Optionally define
<current>_affine_terms(self, v) -> (G, J)to calculate coefficients directly; an ordinary current is synthesized when it is omitted. Automatically recognized symbolic affine currents need no declaration.dn.ctx(MEMBRANE_ASSEMBLY="off")selects original current assembly;"validate"diagnoses coefficient mismatches and nonlinear voltage dependence using frozen-state probes. These probes do not prove arbitrary code globally affine. Incorrect assertions can produce incorrect trajectories. Inherited assertions and coefficient hooks do not silently carry across an overridden current definition.
- static CARRY(*args, dtype=None, shape='local')[source]#
Declare persistent mutable mechanism carry.
Carry crosses accepted timesteps and is therefore part of imperative checkpoints and functional state. Authors initialize it through
initial_values()and update it throughadvance(); current- stage algebra belongs inASSIGNED()instead.- Parameters:
*args (str) – Names of persistent carry tensors.
dtype (torch.dtype, optional) – Fixed carry dtype.
Nonefollows the mechanism dtype.shape ({"local", "deferred", tuple of int}, optional) –
"local"follows the mechanism runtime shape, including explicit Population batch axes."deferred"lets the first pure initialization output establish a custom shape, which is then frozen for this mechanism instance. A tuple declares structural storage independent of Population batching.
- static DERIVED_BUFFER(*args, dtype=None, shape='local')[source]#
Declare initialization-static buffers built by
derive_buffers.A derived buffer retains registered-buffer and
state_dictregistration. The framework refreshes it after effective parameters, temperature, and local geometry have been populated, before State defaults and authoredinitial_values()hooks.derive_buffers()must return a mapping containing exactly the declared names. It must not mutate module tensors and must not depend on voltage, dynamic state, ions/materials, randomness, or timestep.- Parameters:
*args (str) – Names of derived buffers to allocate and materialize.
dtype (torch.dtype, optional) – Fixed workspace dtype.
Nonefollows the mechanism dtype.shape ({"local", "deferred", tuple of int}, optional) –
"local"follows the mechanism runtime shape, including explicit Population batch axes."deferred"lets the first pure builder result establish a custom shape, which is then frozen for this instance. A tuple is a fixed structural shape.
- static EXPLICIT(*args)[source]#
Select explicit treatment of currents when assembling the RHS.
These currents do not contribute an implicit conductance term. This declaration does not assert that the current is voltage independent.
- Parameters:
*args (str) – Current names that should not contribute to conductance terms.
- static NONSPECIFIC_CURRENT(*args)[source]#
Declare non-specific (leak) currents produced by the mechanism.
Current methods and any properties they read must be deterministic during one solver evaluation. Symbolic conductance assembly may evaluate a coefficient separately from the authored current method; stateful or stochastic property access can therefore make an
(i, g)pair internally inconsistent. Such currents should provide an exact<current>_with_conductancemethod instead.- Parameters:
*args (str) – Current names to register as non-specific.
- static NUMERICAL(*args)[source]#
Assert that currents are safe for numerical differentiation.
- Parameters:
*args (str) – Current names that should be numerically differentiated. Each current must be deterministic, side-effect free, and pointwise in voltage.
Notes
Numerical currents use centered finite differences and support float32 and float64 voltage tensors. The declaration is an explicit assertion of the pointwise/purity contract: Dendra perturbs every voltage element simultaneously, which is correct for local currents but is a directional derivative for currents that couple compartments or batch elements. Stateful, nondeterministic, or voltage-mutating current methods are also invalid because centered differences evaluate them repeatedly. Like any same-precision finite difference, this path can lose accuracy when the current is dominated by a very large voltage-independent offset. Prefer a symbolically factorable current or an exact
<current>_with_conductancemethod when available.
- static SAVE_CURRENT(*args)[source]#
Declare currents whose latest evaluated values should be retained.
Every name must also be declared by
NONSPECIFIC_CURRENT()or as an ionic-current write throughUSEION(). Dendra owns the checkpointed<current>_mirror, initializes it to zero, and updates it whenever that current is evaluated. Authoredinitial_valuesandadvancehooks must not write the mirror directly.- Parameters:
*args (str) – Declared current names to mirror with a trailing underscore.
- static STATE_BUNDLE(*args)[source]#
Register State bundle classes for the mechanism class body.
- Parameters:
*args (type) – State subclasses whose solver tensors are owned by the mechanism.
- static TIMESTEP_BUFFER(*args, shape='local')[source]#
Declare buffers built by
derive_timestep_buffers(dt).Dendra rebuilds a timestep buffer whenever the owning integrator configures a timestep, after effective parameters and initialization-static derived buffers are available. The builder must be pure and use its explicit scalar
dtargument instead of mutating module state. Do not repeat the same name in aCARRY(),DERIVED_BUFFER(), orASSIGNED()declaration.- Parameters:
*args (str) – Names of timestep-derived buffers to materialize.
shape ({"local", tuple of int}, optional) – Canonical registered-buffer shape.
"local"(the default) follows the owning mechanism’s runtime shape. An explicit tuple, including()for a scalar, is structural and remains independent of Population batching.
- static USEION(ion, read=None, write=None)[source]#
Declare ionic read/write dependencies for the mechanism class body.
- Parameters:
ion (str) – Ion species identifier (e.g.,
'na').read (Sequence[str], optional) – Ion variables to be read; must be among
{ion}i,{ion}o,e{ion}, ori{ion}(e.g.,['nai', 'nao', 'ena']).write (Sequence[str], optional) – Ion variables to be written; same allowed set (e.g.,
['ina']for current contribution, or['nai']to update concentration).
- Raises:
AssertionError – If the ion name is unknown or a read/write symbol is invalid.
ValueError – If reversal potentials are written or a variable is both read and written.
- static USEMATERIAL(material, read=None, write=None, source=None)[source]#
Declare generic material read/write dependencies.
- Parameters:
material (str) – Material name, e.g.
"ip3"or"ca".read (Sequence[str], optional) – Material fields to expose as local read buffers on this mechanism and its nested State modules.
write (Sequence[str], optional) – Material fields that this mechanism locally replaces. The handler commits these local buffers back to the full population Material after the local mechanism phase.
source (Sequence[str] or Mapping[str, str], optional) – Additive material increments. A sequence such as
["ip3i"]creates local source buffers named"ip3i_source". A mapping such as{"ip3i": "j_ip3"}uses explicit local buffer names.
Notes
Unlike USEION, USEMATERIAL allows a field to appear in both
readandwritebecause local reaction mechanisms commonly need to read a material and then write its updated value.
- advance(v, dt, values)[source]#
Return a partial accepted-step CARRY/shared-field update mapping.
Runs once per accepted timestep. Update direct Mechanism CARRY and owned writable/additive Ion/Material locals; omitted carry is retained. This hook reads the same incoming snapshot as the State bundles, not their newly solved values, and does not replace their solver. Return new Tensors with each output’s exact shape, dtype, and device instead of mutating the value frame or module state.
- assigned_values(v, values)[source]#
Return exactly the ephemeral values declared with
ASSIGNED().This pure algebra may be evaluated repeatedly at different solver stages. Outputs must preserve their exact shape, dtype, and device. Persistent timers, counters, and history belong in CARRY and advance.
- delayed_state(name, value, *, delay_steps=None, mode=None)[source]#
Return a delayed copy of
valueand update the named delay line.The delay line must first be created with
register_delayed_state().mode="auto"uses the in-place circular buffer only in eval/no-grad mode; otherwise it uses a graph-safe functional shift update.
- delayed_state_values(name, value, values, *, mode=None)[source]#
Return
(delayed, updates)for one registered fixed-step history.Read the queue and pointer from the explicit
valuesframe and return their replacements foradvance(),initial_values()orvoltage_values(). Neither inputs nor module state are mutated. Registration and capacity are fixed; use the nativedelayed_state()adapter for runtime capacity changes.
- delayed_states(name, values, *, delay_steps=None, mode=None)[source]#
Return delayed copies of a multi-stream value tensor.
The delay group must first be created with
register_delayed_states().valuesmust have the same shape as theliketensor used at registration time. The stream axis can have distinct integer delays supplied during registration.
- delayed_states_values(name, payload, values, *, mode=None)[source]#
Return
(delayed, updates)for a registered multi-stream history.Each stream uses its registered integer delay. Shift mode preserves gradients through history; circular mode detaches queued writes while zero-delay streams retain the current payload’s gradient.
- derive_buffers()[source]#
Return exactly the workspaces declared by DERIVED_BUFFER.
Build from populated parameters, temperature, and local geometry. Do not read evolving state, voltage, timestep, or implicit randomness, or mutate the module. Ordinary initialization refreshes these values; functional preparation builds them from its explicit inputs.
- derive_timestep_buffers(dt)[source]#
Return exactly the workspaces declared by TIMESTEP_BUFFER.
Build from parameters, static derived workspaces, and scalar Tensor
dtin ms when the integrator configures its timestep. Fresh initialization leaves these buffers zero and does not call this hook. Do not read evolving state or another installed timestep workspace, use implicit randomness, or mutate module tensors.
- evaluate_injections(v=None, *, t=None, current_name='i_inj')[source]#
Evaluate registered waveform currents and assign
current_name.This native compatibility adapter uses
injection_values()for numerical evaluation.vdefaults to the first injection mask, an existing named current, ordiam.tdefaults to the mechanism’s clock, or zero when it has no clock. Pure hooks useinjection_values()with explicitvandtinstead.
- initial_delay_values(values, *names)[source]#
Return a pure zero-history overlay for registered delay lines.
Use this from
initial_values()to clear registered histories on initialization. Histories declared as CARRY already receive ordinary zero defaults. Undeclared registered histories retain their values unless an initialization hook returns an explicit replacement.
- initial_values(v, values)[source]#
Return a pure partial overlay for declared initial values.
Return flattened bundle STATE names, direct Mechanism CARRY, or owned writable Ion/Material locals. Omitted fields keep their earlier value. State defaults and insertion-time
icrun before this overlay; nested State overlays run afterward. This hook does not advance time. Tensor outputs must use the declared dtype/device and have shapes broadcastable to each declared output’s storage shape.valuesincludes initialized STATE/CARRY values, support-visiblecelsiusanddiam, and the support-local Ion/Material/current aliases installed for this ordered initialization phase. Treat inputs and module state as read-only; read parameters/workspaces through self.
- inject(waveform, *, index=None, shape=None, model_shape=None, model=None, **kwargs)[source]#
Optionally attach a waveform stimulus to this mechanism.
The default implementation is deliberately a no-op and returns
False. Mechanisms that own their own voltage/current dynamics can override this method and either consume the arguments directly or callregister_waveform_injection()to get paddedI(t)tensors.- Parameters:
waveform (Waveform) – Waveform object supplied through
model[idx].inject(waveform).index (tuple, optional) – Population-level index tuple identifying the targeted compartments.
shape (tuple, optional) – Shape produced by applying
indexto the population.model_shape (tuple, optional) – Full population voltage shape at registration time.
model (Population, optional) – Owning population. Used for device/dtype/shape information.
**kwargs – Reserved for future extension.
- Returns:
Trueonly if the mechanism accepts complete ownership of the injection. ReturningFalseleaves delivery to the solver path.- Return type:
bool
- injection_values(v, *, t, current_name='i_inj')[source]#
Return registered waveform currents without changing mechanism state.
vsupplies the local output shape, device and dtype.tis an explicit scalar evaluation time in ms. The returned tensor sums matching registrations, with zeros outside their masks. Waveform outputs may be scalar, broadcast over the local shape, or contain one value per selected compartment, optionally preceded by batch axes. Scales multiply waveform outputs before the singleton time axis is removed, so tensor scales must broadcast with that time-last output.Waveforms must evaluate without mutating their module or inputs when this helper is used from a pure hook. Parameters and tensor-valued times remain differentiable. This helper does not assign
current_name; return the result fromassigned_valuesor use it in current algebra.
- register_delayed_state(name, like, delay_steps, *, mode='auto', buffer_name=None, pointer_name=None, insert_axis=-1, clear=True)[source]#
Register a fixed-step delayed state buffer on this mechanism.
This helper is for fused mechanisms that need NetCon-like fixed delays while bypassing
NetCon. The delayed state has two update backends:mode="shift"Graph-safe functional update. Each call constructs a new queue with
torch.cat. This is appropriate for training / BPTT because the delayed value remains connected to the computation graph.mode="circular"Fast in-place circular buffer. This avoids shifting/copying the whole queue each step, but it intentionally writes under
torch.no_grad()and is therefore intended for evaluation only.mode="auto"Use
circularwhen the mechanism is in eval mode and gradients are disabled; otherwise useshift.
- Parameters:
name (str) – User-facing delay name used with
delayed_state().like (torch.Tensor) – Tensor whose shape/device/dtype define the payload shape.
delay_steps (int) – Integer delay in simulation steps. A value emitted at call
kappears afterdelay_stepssubsequent calls, matching the queue convention used by Dendra’s event delay buffers. The current delayed-state helper assumes one uniform delay per registered delayed state. For heterogeneous per-connection delays, useNetCon/ContinuousConor register separate delayed states for each distinct delay.mode ({"auto", "shift", "circular"}, default "auto") – Backend selection policy.
buffer_name (str, optional) – Name of the registered buffer. Defaults to
f"{name}_delay_buffer". Existing mechanismCARRYstorage can be reused by passing its declared name here.pointer_name (str, optional) – Name of the circular-buffer write pointer.
insert_axis (int, default -1) – Axis before which the delay dimension is inserted. The default inserts the delay axis before the final payload dimension, so a payload of shape
(..., n)becomes(..., depth, n).clear (bool, default True) – If true, reset the delay buffer and pointer.
- Returns:
The registered delay buffer.
- Return type:
torch.Tensor
- register_delayed_states(name, like, delay_steps, *, mode='auto', buffer_name=None, pointer_name=None, steps_name=None, stream_axis=-2, delay_axis=None, clear=True)[source]#
Register a batched fixed-step delay line for several streams.
This is the multi-stream counterpart of
register_delayed_state(). It is intended for fused mechanisms that need many pathway-level delays over tensors with the same payload shape. For example, a value tensor with shape(batch, n_streams, n)andstream_axis=-2is stored in one delay buffer with shape(batch, depth, n_streams, n).- Parameters:
name (str) – User-facing delay group name used with
delayed_states().like (torch.Tensor) – Example value tensor. One dimension is interpreted as the stream / pathway axis; all other dimensions are payload dimensions.
delay_steps (int or sequence[int] or torch.Tensor) – Integer delays in simulation steps. A scalar applies the same delay to every stream. A vector must have length
like.shape[stream_axis].mode ({"auto", "shift", "circular"}, default "auto") – Backend selection policy.
autouses circular buffers in eval / no-grad mode and graph-safe shifted queues during training/grad mode.buffer_name (str, optional) – Name of the registered delay buffer. Defaults to
f"{name}_delay_buffer".pointer_name (str, optional) – Name of the circular-buffer write pointer. Defaults to
f"{name}_delay_ptr".steps_name (str, optional) – Name of the registered integer delay vector. Defaults to
f"{name}_delay_steps".stream_axis (int, default -2) – Axis of
likecontaining independent delay streams.delay_axis (int or None, default None) – Axis of the delay buffer where the delay dimension is inserted. If
None, the delay dimension is inserted immediately beforestream_axisfor backwards compatibility. Usedelay_axis=0for a time-major buffer layout(depth, *like.shape), which is often preferable for GPU execution.clear (bool, default True) – If true, reset the delay buffer and circular pointer.
- Returns:
The registered delay buffer.
- Return type:
torch.Tensor
Notes
delayed_statessupports heterogeneous per-stream integer delays, but all streams in a group share one circular pointer and one buffer depth equal tomax(delay_steps) + 1. This is useful for fused models with several fixed pathway delays and avoids one delayed-state helper call per pathway.
- register_waveform_injection(waveform, *, index=None, model_shape=None, current_name='i_inj', scale=1.0, model=None)[source]#
Register a waveform and build a local padding mask for this mechanism.
This helper is intended for mechanism subclasses that override
inject(). It computes the overlap between a population-level injection index and the compartments occupied by this mechanism, stores the waveform as a submodule, and records a boolean local mask. Later,injection_values()evaluates registered waveforms at an explicit time and returns a tensor shaped like the local voltage argument, with zeros outside the targeted compartments.evaluate_injections()additionally assigns the named current for native compatibility.Registration succeeds only when this mechanism covers every targeted population location. Partial overlap returns
Falsewithout storing state so the solver can deliver the full injection exactly once.
- class State(celsius, diameters, key, shape, shape_f, additional_parameters=None, **kwargs)[source]#
Helper mixin for declaring per-compartment state variables and their dynamics.
Define subclasses inside a
Mechanismand register them withMechanism.STATE_BUNDLE(). Use uppercase classmethods (STATE,DERIVATIVE,KINETIC,ASSIGNED,CARRY,GLOBAL,RANGE) at class definition time to declare state variables, ODEs/kinetics, per-compartment parameters, and auxiliary buffers. Override lowercase hooks to implement behavior:state_defaults(self, v, values): return lower-priority defaults for declared solver state.initial_values(self, v, values): return a pure initialization overlay for declared state and persistent carry.assigned_values(self, v, values): compute ephemeralASSIGNEDvalues needed by the generated solver.advance(self, v, dt, values): return the next declared state/carry.
Notes
State equations advance on Dendra’s millisecond time coordinate. A derivative of a state
xtherefore has unitsunit(x)/ms; an SDE diffusion coefficient has unitsunit(x)/sqrt(ms). Voltage arguments are in mV,self.celsiusis in °C, and compartment diameters are in µm.- static ASSIGNED(*args)[source]#
Declare computed per-compartment variables used in derivatives.
State ASSIGNED variables form an explicit contract with
assigned_values(): each declared name must be computed there and returned in its mapping. For persistent auxiliary storage that does not participate in this return contract, useCARRY().- Parameters:
*args (str) – Names of values returned by
assigned_values().
- static CARRY(*args, dtype=None, shape='local')[source]#
Declare persistent per-compartment non-ODE state.
Carry is checkpointed and exposed by functional execution, but is not advanced automatically by the declared ODE/SDE solver. Initialize or update it through returned values from
initial_values()or a customadvance()implementation.- Parameters:
*args (str) – Persistent carry names to allocate.
dtype (torch.dtype, optional) – Fixed carry dtype.
Nonefollows the State dtype.shape ({"local", "deferred", tuple of int}, optional) –
"local"follows the State runtime shape, including explicit Population batch axes."deferred"lets the first pure initialization output establish a custom shape, which is then frozen for the lifetime of that State instance. A tuple declares structural storage independent of Population batching.
- static DERIVATIVE(*args)[source]#
Declare ODEs for state variables using symbolic strings.
- Parameters:
*args (str) – Derivative expressions like
"m' = (minf - m) / tau".
- static DERIVED_BUFFER(*args, dtype=None, shape='local')[source]#
Declare initialization-static buffers built by
derive_buffers.Derived buffers retain registered-buffer and
state_dictregistration, but additionally declare that their accepted value is a pure function of populated parameters, temperature, and local geometry. They are refreshed before State defaults and authoredinitial_values()hooks.derive_buffers()must return a mapping containing exactly the declared names. It must not mutate module tensors and must not depend on voltage, dynamic state, ions/materials, randomness, or timestep.- Parameters:
*args (str) – Names of derived buffers to allocate and materialize.
dtype (torch.dtype, optional) – Fixed workspace dtype.
Nonefollows the State dtype.shape ({"local", "deferred", tuple of int}, optional) –
"local"follows the State runtime shape, including explicit Population batch axes."deferred"lets the first pure builder result establish a custom shape, which is then frozen for this instance. A tuple is a fixed structural shape.
- static DIFFUSION(*args)[source]#
Declare diffusion coefficients for State SDEs.
Each declaration has the form
"x = sigma"and represents the multiplicative noise coefficient.State.METHOD("euler_maruyama")interprets this as an Itô SDE.State.METHOD("euler_heun")interprets it as a Stratonovich SDE. Stochastic voltage/cable equations are currently unsupported.
- static INPUT(*names, default=0.0)[source]#
Declare read-only tensor inputs supplied by Population bindings.
Inputs are ephemeral values in State hook frames; they allocate no buffers and cannot be returned as state updates. Unbound inputs use a finite scalar default, broadcast to the local voltage shape. During initialization inputs use these defaults; bindings are evaluated only when the consumer State advances.
- static KINETIC(*args)[source]#
Declare kinetic/Markov schemes between states.
- Parameters:
*args (str) – Kinetic expressions like
"~ a <-> b (alpha, beta)".
- static METHOD(method=None, **kwargs)[source]#
Declare the integration method for this State subclass.
- Parameters:
method (str, optional) – Integration method name. Currently registered methods include
"cnexp","derivimplicit","bufferimplicit","linearimplicit"/"sparse","rosenbrock","euler_maruyama"for Itô State SDEs, and"euler_heun"for Stratonovich State SDEs. PassingNoneleaves the inherited method unchanged and only updates method kwargs.**kwargs –
Method-specific options captured at class-definition time and passed to the generated solver builder. For example:
State.METHOD("derivimplicit", max_iter=4, line_search=False)or:
State.METHOD("cnexp", pade=True)
- static STATE(*args)[source]#
Declare state variables for the State subclass.
- Parameters:
*args (str) – Names of state variables advanced by the integrator.
- static TIMESTEP_BUFFER(*args, shape='local')[source]#
Declare buffers built by
derive_timestep_buffers(dt).Timestep buffers retain registered-buffer and
state_dictregistration, but are rebuilt whenever an integrator configures its timestep. The builder must be pure and may depend on the explicit scalardtargument as well as populated parameters, temperature, local geometry, and initialization-static derived buffers. Do not repeat the same name in a separateCARRY()declaration.- Parameters:
*args (str) – Names of timestep-derived buffers to materialize.
shape ({"local", tuple of int}, optional) – Canonical registered-buffer shape.
"local"(the default) follows the owning State’sshape_p. An explicit tuple, including()for a scalar, is structural and remains independent of Population batching.
- advance(v, dt, values, *, draws=None)[source]#
Return the next declared state from a read-only current-value frame.
The default implementation runs the generated solver for this State’s equations. An override replaces that transition and must return every declared STATE tensor, plus any optional replacements for this State’s CARRY. Runtime outputs preserve their exact shape, dtype, and device. Other bundles and the owning Mechanism advance from the same incoming snapshot; their new values are not visible during this calculation.
For Euler-Maruyama and Euler-Heun,
drawssupplies a mapping from non-eliminated state names to standard-normal tensors with the exact shape, dtype, and device of the corresponding current state. Base draws are detached; drift, diffusion coefficients, and timestep retain their gradients. Omittingdrawssamples the State’s Native RNG streams.
- assigned_values(v, values)[source]#
Return ephemeral values declared with
ASSIGNED().The mapping is evaluated immediately before the generated state solver needs it and may be evaluated more than once by a multi-stage method. Treat
vandvaluesas read-only and do not update persistent carry here.
- initial_values(v, values)[source]#
Return a pure initialization overlay for this State.
The optional mapping may contain this State’s declared
STATEandCARRYnames.valuesexposes their current initialized values, support-visiblecelsiusand localdiaminputs, and any support-local Ion/Material/current aliases installed by the owning Mechanism for this ordered initialization phase. Returned values must be Tensors with the declared dtype/device and shapes broadcastable to each output’s local or structural storage shape. The hook must not mutate module state or consume implicit RNG.
- state_defaults(v, values)[source]#
Return lower-priority defaults for declared solver state.
Used once per State during initialization when at least one declared state lacks an insertion-time
icvalue. Return a mapping from every such state name to a Tensor (or a value broadcastable to the support-local voltage shape).valuesexplicitly exposes available shared seeds/overrides plus support-visiblecelsiusand localdiam. The hook must be pure, deterministic, and complete for every otherwise unresolved State name.
Voltage and synaptic processes#
VoltageProcess.voltage_values supplies imposed voltage. Event synapses
implement net_receive_values; continuous synapses implement
continuous_receive_values. Their native adapters publish the returned
values. The pure hooks are shared by native and functional execution.
- class VoltageProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Mechanism subtype that updates the membrane potential
v.Implement
voltage_values()to return a new voltage and a mapping of declared nestedStatevariable andCARRY()replacements. The hook is pure: its voltage, timestep, andvaluesinputs are read-only, and it must not mutate the module. Dendra uses the same hook in imperative and functional execution.Voltage processes run in their existing ordered, support-local phase before gating and membrane-current assembly. They do not run during initialization. Both input and returned voltage are in mV.
Legacy subclasses overriding
update_v()continue to work imperatively, but need the pure hook to participate in functional execution.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- voltage_values(v, dt, values)[source]#
Return
(voltage, updates)without modifying inputs orself.valuesfollows the ordinary Mechanism runtime frame: declared persistent/assigned values, prepared workspaces, local shared fields,celsius, anddiam. Parameters may be read throughself.updatesmay replace any subset of this process’s declared nested State variables and direct CARRY values, preserving each value’s shape, dtype, and device. Nested State CARRY, ASSIGNED values, workspaces, and shared fields cannot be replaced here. The returned voltage must matchvin shape, dtype, and device.
- update_v(v)[source]#
Imperative adapter committing the pure hook’s declared state outputs.
Functional execution lifts these same buffer replacements into explicit state. User-authored voltage algebra belongs in
voltage_values(), not in this adapter.
- class PointProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Base class for a mechanism that delivers lumped current at one location.
A point-process current method returns a numerical value in nA and its conductance or voltage derivative is in µS. Voltage remains in mV, so an Ohmic method can use
g * (v - e)directly becauseµS * mV = nA. Built-inexpsynandexp2synevent weights are consequently numerical values in µS (for example,weight=0.05means 0.05 µS).Dendra divides point-process currents and conductances by
1e6 * area_cm2before adding them to distributed membrane densities. This conversion makes nA into mA/cm² and µS into S/cm². It also means a point process cannot be inserted at a zero-area branchpoint.Notes
Point-process nA/µS values are a local mechanism coordinate convention. Do not multiply a built-in point-process weight or conductance parameter by
dendra.units.uS, which converts a value to the absolute-S convention used elsewhere. To convert, for example, 50 nS into the required µS coordinate, use50 * dendra.units.nS / dendra.units.uS.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- class Synapse(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
A Mechanism that receives weighted events and delivers synaptic current.
Implement the pure
net_receive_values()hook to return declared state/carry replacements. The standardnet_receive()adapter commits those replacements in existing NetCon delivery order, including calls with a zero payload. Multiple connections may call it during one timestep.Legacy subclasses overriding
net_receive()retain their imperative behavior; they must adopt the pure hook for functional event delivery.NetConweights inherit their units from the target synapse. For the built-in point-processexpsynandexp2synmechanisms, weights are numerical values in µS. A custom density-styleSynapsemay define a different weight contract and should document it explicitly.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- net_receive_values(weights, dt, values)[source]#
Return event updates without modifying inputs or the module.
weightsis a Tensor broadcast to this mechanism’s local runtime shape.dtis the configured timestep as a broadcastable one-element Tensor of shape(1,). Scalar structural CARRY updates should reshape their result to the declared scalar shape after arithmetic.valuescontains the Mechanism state, prepared workspace, and shared-field frame plus astate_carrymapping from State bundle names to their declared CARRY tensors. Ephemeral ASSIGNED values are excluded: derive event algebra in this hook, or declare CARRY when a value must persist. Parameters may be read throughself.Return any subset of
{"states": {...}, "carry": {...}, "state_carry": {StateName: {...}}}. These sections update flat STATE variables, direct Mechanism CARRY, and nested State CARRY respectively. Omitted fields remain unchanged. Every replacement must preserve its declared shape, dtype, and device. Shared fields, ASSIGNED values, prepared workspaces, and INPUT values cannot be updated here.
- class ContinuousSynapse(*args, **kwargs)[source]#
A mechanism that receives continuously valued presynaptic variables.
ContinuousSynapseis the analog counterpart toSynapse. It is intended for graded transmitter gates, rate-coded projections, neuromodulatory drives, and other connections where the presynaptic mechanism emits a continuous variable rather than discrete events.Subclasses declare continuous input buffers with
ContinuousSynapse.INPUT. The network’s continuous-connection machinery resets those buffers once per timestep, then delivers weighted presynaptic values by callingcontinuous_receive(). By default, deliveries are summed into the named input, which is the natural behavior for convergent synaptic currents. The previous timestep’s input is also available as<input>_oldwhen the input was declared with the defaultkeep_old=True.A
ContinuousSynapsefollows the ordinary distributedMechanismunit contract unless it also inheritsPointProcess: current in mA/cm² and conductance in S/cm². The product of a connection weight and its transformed presynaptic value must have the units declared for the target input buffer. For a dimensionless presynaptic gate delivered to a conductance-density input, the weight is in S/cm².Example
class graded_gaba(ContinuousSynapse): ContinuousSynapse.INPUT("g_pre") ContinuousSynapse.RANGE(e=-80.0) ContinuousSynapse.NONSPECIFIC_CURRENT("i") def i(self, v): return self.g_pre * (v - self.e)
- static INPUT(*names, keep_old=True)[source]#
Declare one or more per-step continuous input buffers.
- Parameters:
*names (str) – Input buffer names to declare.
keep_old (bool, optional) – If True (default), also declare
<name>_oldbuffers and populate them with the previous timestep’s input during reset.
- continuous_receive_values(value, dt, values, *, input, reduce, mask, received)[source]#
Return declared state/carry updates for one ordered analog delivery.
valueand Booleanmaskhave the named input’s local shape.receivedmarks elements delivered earlier in this timestep, including actual zero deliveries.dthas shape(1,).valuesuses the event-receive frame, including input/old-input CARRY and nested State CARRY. Return event-stylestates,carryandstate_carrymappings without modifying any input or module state.The default hook implements sum/add, set/replace/last, min and max. Override this pure hook to add synaptic dynamics at delivery time; legacy imperative
continuous_receiveoverrides remain native-only.
Material processes#
MaterialProcess uses full-field material_fields, prepare_materials and
material_updates hooks. It does not use ordinary Mechanism initialization,
assigned-value or advance hooks. Its default native adapter publishes the pure
material replacements. Built-in transport processes implement this protocol.
- class MaterialProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Full-field operator over shared Material objects.
Insert a process like a Mechanism and select its execution phase with
PHASE(). Pure implementations exposematerial_fields, prepare operator data withprepare_materials(), and return replacement fields frommaterial_updates(). The nativeadvance_materials()adapter publishes those replacements; functional execution uses the same pure hooks.Notes
The voltage-local Mechanism lifecycle does not apply: State bundles, CARRY,
initial_values,advance, and Mechanism workspace declarations are unsupported. Useconfigure_process()for persistent configuration andset_dt()for native timestep setup. Parameter declarations and explicit RAND/NOISE inputs remain available.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- configure_process(population=None)[source]#
Configure this process after Material/Population binding.
Dendra may invoke this hook again when it rebuilds execution maps or rebinds the process. Implementations must therefore be idempotent: replace derived configuration instead of accumulating it.
- advance_materials(dt, *, prepared=None)[source]#
Prepare a pure operator and atomically publish its replacements.
Pure process families inherit this adapter; legacy families may retain their own imperative implementation.
preparedlets an execution adapter supply explicit operator tensors prepared outside a time loop.
- property material_fields: tuple[tuple[str, str], ...]#
Canonical full-field inputs to a pure material-process operator.
This optional protocol is separate from ordinary Mechanism workspace declarations. Legacy processes may continue implementing only
configure_process(),set_dt(), andadvance_materials().
- prepare_materials(fields, dt)[source]#
Return tensor-only operator data without changing fields or self.
fieldsis keyed by canonical(material_name, field_name)pairs. Implementations resolve current parameters and geometry into an explicit tensor PyTree; they must not retain this preparation on the process.
- class DiffusionProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Finite-volume diffusion over all or a selected subset of compartments.
Declare transported fields with
DIFFUSE(). Intracellular fields can use an Axon’s analytic cylindrical geometry or a Tree’s native material geometry. Intracellular, extracellular, periaxonal, and other chemical domains on unbranched or Tree populations may instead use finite-volume geometry registered byPopulation.register_material_geometry(). Boundaries are sealed.Inserting on a Slice restricts transport to the induced morphology subgraph. An edge is active only when both endpoints are selected; crossing edges are sealed, disconnected selected components evolve as independent matrix blocks, and excluded field values remain exactly unchanged. Repeated insertions of the same process class form one union support, so separately inserted regions communicate if they touch.
Concatenation retains each component’s transport geometry and process placement. A packed MultiPopulation uses a disconnected parent-index forest: different cells never acquire chemical interfaces merely because their storage is adjacent. Fields absent from a component are excluded from that field’s induced transport forest and remain unchanged.
RELAX()(aliasBATH()) optionally fuses linear reservoir coupling into the implicit diffusion solve. With storage matrixM, diffusion LaplacianL, non-negative rateLambda, reservoir valuec_bath, and the fieldc_sourceafter committed local material sources, one step solves(M + dt*L + dt*M*Lambda) c_new = M*c_source + dt*M*Lambda*c_bath.Consequently diffusion and bath coupling are not operator-split from one another. Local Mechanism material writes/sources run first; material transport runs next; Ion/Material guards and derived values such as Nernst reversals refresh afterward.
RELAXis currently implicit-only.Analytic 1-D models support
interface_scheme="arithmetic"(the legacy default) andinterface_scheme="series"(two half-compartment diffusion resistances in series). Tree models use their precomputed edge geometry and do not accept the 1-D-only series option. Named geometries already provide an interface factor and currently use the arithmetic scheme; use edge-located diffusivity for an explicitly computed interface coefficient.Geometry/topology and timestep-scaled coefficients are configured before stepping (or explicitly by
set_dt(dt)), so the per-timestep material phase only calls a preconfigured spatial operator. Registered named-geometry and Population coefficient buffers/parameters are sampled during this configuration and remain differentiable; they are not read anew on every timestep.Notes
One process class may declare multiple fields. If any DIFFUSE declaration names geometry, every DIFFUSE declaration in that class must name that same geometry; named and unnamed declarations cannot be mixed. Overlapping assignments from repeated insertions must be unambiguous. Distinct DiffusionProcess classes may be disjoint, but overlapping writers to the same material field in the same phase are rejected because sequential implicit solves are order-dependent.
Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- static DIFFUSE(material, *, field=None, D=None, domain=None, geometry=None, D_location='node')[source]#
Declare a material field to diffuse.
- Parameters:
material – Material name, e.g.
"ca"or"ip3".field – Field name, e.g.
"cai"or"ip3i". If omitted, defaults tof"{material}i".D – Diffusivity in
um^2 / ms. It may be a scalar, tensor, or the name of a process parameter/buffer. WithD_location="edge", a string may also name a registered Population edge buffer.domain – Optional domain override. If omitted, the material field spec’s domain metadata is used.
geometry – Optional named material geometry registered on the Population with
Population.register_material_geometry(). It is currently required for extracellular diffusion. Every DIFFUSE declaration in one process class must use the same named geometry (or none).D_location –
"node"(default) meansDis scalar or node-aligned. The spatial backend derives interface coefficients from endpoint values."edge"meansDis scalar or interface-aligned (final dimensionC - 1for an unbranched population, or compact Tree edge dimensionEinmaterial_edge_indexorder). It requires named geometry and is useful for barriers or junctions that cannot be represented by endpoint averaging.
Notes
With named geometry and
D_location="node", interface diffusivity is the arithmetic endpoint mean0.5 * (D_i + D_j). Named geometry rejectsinterface_scheme="series"because an area/distance edge factor does not contain both half-compartment resistances.Edge location is supported with explicit named geometry on unbranched and Tree populations; it is not available for analytic cylindrical 1-D or native Tree geometry. A node-aligned RANGE declaration is not an edge array. For spatially varying edge diffusivity, use a literal edge tensor or a registered Population edge buffer/parameter. Process-local names take precedence over Population names.
Named Tree geometry retains morphology adjacency. Compact edge entry
edescribesparent[e] -> child[e]as exposed bymaterial_edges; zero geometry or diffusivity may seal that edge, but named geometry cannot add a new one.Coefficients are finite and non-negative on active interfaces. A zero diffusivity seals an interface. Registered Population values are sampled whenever the process spatial operator is configured, not on every timestep; reconfigure after mutating one.
- static RELAX(material, *, field=None, rate=None, target=0.0, where='all')[source]#
Fuse linear reservoir relaxation into a diffused field’s solve.
The implicit update contributes
-rate * (c - target)to the same linear system as diffusion. This is useful for bulk-bath exchange, clearance into a fixed reservoir, or other stiff linear coupling.- Parameters:
material – Material containing the field. It must match a
DIFFUSE()declaration in the same process class.field – Field to relax. If omitted, defaults to
f"{material}i".rate – Non-negative relaxation rate in
1 / ms. It may be a scalar, node-aligned tensor, or process parameter/buffer name. A spatially varying zero rate is often the simplest coupling mask.target – Reservoir concentration/value in the same units as
field. It may be scalar, node-aligned, or a parameter/buffer name.where – An additional node mask.
"all"(the default) andNonemean no additional mask: they do not override the region where the DiffusionProcess was inserted. A boolean scalar/tensor, a node-aligned process parameter/buffer name, or a registered Population buffer/parameter name further restricts reservoir coupling.
Notes
Effective coupling support is the intersection of the process insertion region and
where; compartments withrate == 0contribute no relaxation. Thuswhere="all"on a regional process still excludes every compartment outside that process region. Multiple RELAX declarations for one field add their diagonal and right-hand-side contributions. RELAX requiresMETHOD("implicit"). For bath-only dynamics, declare the field withDIFFUSE(..., D=0)and then RELAX it.Only
"all"andNoneare special mask values. Any other string is resolved as a process-local or registered Population quantity name; ClampProcess selector words such as"terminal","root", and"soma"have no special meaning here. Process-local names take precedence over Population names.Rate, target, and where values are sampled into the configured implicit operator and are not hot-read every timestep. Reconfigure the spatial operator after changing them. RELAX represents coupling to a fixed or infinite reservoir and therefore does not conserve mass inside the modeled field. Use ExchangeProcess for conservative exchange with a finite modeled reservoir.
BATHis an exact declaration alias forRELAX.
- property graph#
Graph proxy used by SpatialOperatorTree during set_dt(…) precompute.
- class ClearanceProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Pointwise first-order clearance/relaxation of full Material fields.
A ClearanceProcess applies
c’ = -rate * (c - target)
to one or more population-wide material fields. It is intended for generic decay, degradation, uptake, bath relaxation, and recovery-to-baseline dynamics that do not require spatial coupling. The default method is the exact exponential update, which is stable for non-negative rates and fixed targets over the timestep.
Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- static CLEAR(material, *, field=None, rate=None, target=0.0, domain=None)[source]#
Declare a first-order clearance/relaxation for a material field.
- Parameters:
material – Material name, e.g.
"ip3"or"k".field – Field name, e.g.
"ip3i"or"ko". If omitted, defaults tof"{material}i".rate – First-order rate in
1/ms. May be a scalar/tensor or the name of a process parameter, e.g.rate="kclear". If omitted, defaults to the parameter name"rate".target – Relaxation target. May be a scalar/tensor or the name of a process parameter, e.g.
target="ko_bath".domain – Optional domain metadata override. Clearance is pointwise, so the domain is currently validation metadata rather than geometry input.
- class ClampProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Pointwise hard or bound clamp of full Material fields.
A ClampProcess imposes an externally prescribed value or bound on one or more population-wide material fields. It is intended for bath conditions, boundary conditions after transport, fixed experimental fields, and safety bounds that should be applied as a well-defined material-process phase.
The default phase is
post_transportso a clamp inserted with diffusion behaves like a boundary/bath condition: local reactions run first, transport runs second, and the clamp is imposed last. Override withClampProcess.PHASE(...)if a different ordering is desired.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- static CLAMP(material, *, field=None, value=0.0, where='all', mode=None, domain=None)[source]#
Declare a clamp for a material field.
- Parameters:
material – Material name, e.g.
"ip3","k", or"ca".field – Field name, e.g.
"ip3i","ko", or"cai". If omitted, defaults tof"{material}i".value – Clamp value or bound. May be a scalar/tensor or the name of a process parameter/buffer. For
mode="range", pass a two-element tuple/list(lower, upper)whose entries may also be parameter names.where – Region where the clamp applies. Supported MVP values include
"all","terminal"/"boundary","root"/"proximal", a boolean mask tensor, or an index/slice into the material field.mode –
"set"/"hard"sets the field tovalue."min"imposes a lower bound."max"imposes an upper bound."range"imposes lower and upper bounds.domain – Optional domain metadata override. Clamp is pointwise, so this is currently validation/semantic metadata rather than geometry input.
- static SET(material, *, field=None, value=0.0, where='all', domain=None)[source]#
Alias for a hard set clamp.
- static MIN(material, *, field=None, value=0.0, where='all', domain=None)[source]#
Declare a lower-bound clamp:
field = max(field, value).
- static LOWER(material, *, field=None, value=0.0, where='all', domain=None)[source]#
Alias for
MIN().
- static MAX(material, *, field=None, value=0.0, where='all', domain=None)[source]#
Declare an upper-bound clamp:
field = min(field, value).
- static UPPER(material, *, field=None, value=0.0, where='all', domain=None)[source]#
Alias for
MAX().
- static BOUNDS(material, *, field=None, lower=0.0, upper=None, where='all', domain=None)[source]#
Declare a lower/upper bound clamp.
loweranduppermay be scalars/tensors or parameter names. Ifupperis omitted, only the lower bound is applied throughMIN.This helper is intentionally named
BOUNDSrather thanRANGEso it does not shadowMechanism.RANGE(), which is still used to declare process parameters such as bath values.
- class ExchangeProcess(name, celsius, diameters, shape, shape_f, key=None, is_composable=False, support_spec=None, preserves_multiplicity=False, force_packed_support=False, additional_parameters=None, ic=None, **kwargs)[source]#
Conservative pointwise exchange between two full Material fields.
An ExchangeProcess applies a local two-pool exchange at every compartment:
V_a * a' = -g * (a - b) V_b * b' = g * (a - b)
where
aandbare concentration-like material fields,V_aandV_bare their local mass/volume weights, andgis an exchange conductance. Ifrateis supplied instead ofconductance, Dendra usesg = rate * V_a; thusratehas units1/msand describes the first-order relaxation rate of poolatoward poolbwhen volumes are fixed.The default method is the exact closed-form update for fixed
rate/gand fixed volumes over the timestep. It preservesV_a*a + V_b*bup to floating-point roundoff on compartments with positive volumes.Initialize a mechanism instance and register declared buffers.
- Parameters:
name (str) – Mechanism alias. If
None, falls back to the class name.celsius (Tensor or float) – Temperature in °C, broadcastable to the mechanism shape.
diameters (Tensor) – Compartment diameters in µm, shared with sub-components.
shape (tuple of int) – Base shape for parameter tensors (without batch dimensions).
shape_f (tuple of int) – Full shape including batch dimensions.
key (Any, optional) – Index selector identifying the attached compartments.
is_composable (bool, optional) – Whether
keyrepresents a tuple of slices instead of flat indices.support_spec (SupportSpec, optional) – Precomputed structural support metadata. Population compilation supplies this so support identity remains available after device moves without changing the legacy
keystorage ABI.preserves_multiplicity (bool, optional) – Whether local slots deliberately preserve repeated physical locations, as for copied point processes.
force_packed_support (bool, optional) – Keep an otherwise classifiable support in its packed one-axis ABI.
additional_parameters (dict, optional) – Additional parameter declarations injected by the parent population.
ic (dict, optional) – Initial condition overrides for state buffers.
**kwargs – Extra keyword arguments forwarded to
dendra.models.parametric.Parameterized.
- static EXCHANGE(a, b, *, field_a=None, field_b=None, rate=None, conductance=None, volume_a=None, volume_b=None, domain_a=None, domain_b=None)[source]#
Declare conservative exchange between two material fields.
- Parameters:
a – Material field references. Accepted forms are
("ca", "cai"),"ca.cai", or a material name plusfield_a=.../field_b=....b – Material field references. Accepted forms are
("ca", "cai"),"ca.cai", or a material name plusfield_a=.../field_b=....rate – First-order rate in
1/ms. Dendra converts this to an exchange conductance viag = rate * volume_a. If omitted andconductanceis also omitted, defaults to the process parameter name"rate".conductance – Direct exchange conductance in the chosen geometry/mass-weight units per ms (for example µm³/ms for volumetric fields or µm²/ms for membrane-domain fields). This is useful when the coupling itself is a geometric/permeability term. Specify either
rateorconductance, not both.volume_a – Optional mass/volume weights. May be scalars, tensors, parameter names, or domain names such as
"intracellular". If omitted, Dendra tries to infer volumes from the material field domain and population geometry; if no compatible geometry is available, unit volumes are used unlessMETHOD(..., require_volumes=True)is set.volume_b – Optional mass/volume weights. May be scalars, tensors, parameter names, or domain names such as
"intracellular". If omitted, Dendra tries to infer volumes from the material field domain and population geometry; if no compatible geometry is available, unit volumes are used unlessMETHOD(..., require_volumes=True)is set.domain_a – Optional domain metadata overrides.
domain_b – Optional domain metadata overrides.
- static COUPLE(*args, **kwargs)[source]#
Alias for
EXCHANGE().
- static TRANSFER(*args, **kwargs)[source]#
Alias for
EXCHANGE().
- class SpatialOperator1D(*, solver='auto', boundary='sealed', interface_scheme='arithmetic')[source]#
Finite-volume helper for 1D compartment chains.
The operator assumes the final tensor dimension is the compartment axis; all leading dimensions are independent batches/fibers. Geometry is expected in micrometers. Diffusivities are therefore expected in
um^2 / msby default, and the implicit solve advances concentration-like fields in ms.Unlike the convenience
solve_tridiagonal_1d(), this module follows the same split used by Dendra’s voltage integrators: solver selection and static geometry/band construction happen inconfigure_diffusion(...); the per-stepdiffuse_*_configured(...)methods only assemble the RHS and call the preselected solver.- finite_volume_geometry(diam_um, dx_um, *, volume_fraction=1.0, area_fraction=1.0)[source]#
Return compartment volumes and interface areas for a 1D cable.
- edge_conductance(D_um2_per_ms, diam_um, dx_um, *, volume_fraction=1.0, area_fraction=1.0, interface_scheme=None)[source]#
Return
(volume, g_edge)for finite-volume diffusion.
- configure_diffusion(c_like, dt, D_um2_per_ms, diam_um, dx_um, *, volume_fraction=1.0, area_fraction=1.0, interface_scheme=None, node_mask=None, solver=None, volume=None, edge_factor=None, edge_area=None, edge_distance=None, D_location='node')[source]#
Precompute geometry, solver choice, and timestep-scaled bands.
node_maskselects the induced diffusion subgraph. An interface is active only when both of its endpoint compartments are selected, so omitted compartments impose exact sealed boundaries. The full field shape is retained: disconnected selected regions therefore form independent diagonal blocks in the same solve.
- configure_relaxation(rate, target=0.0, *, where=None)[source]#
Add
-rate * (c - target)to the configured implicit system.Multiple calls accumulate, allowing independent linear reservoirs to couple to the same transported field without an additional split step.
- prepare_diffusion(c_like, dt, D_um2_per_ms, diam_um, dx_um, **kwargs)[source]#
Build explicit tensor workspace without changing this operator.
Structural checks remain active. Numerical inputs must satisfy the same physical-domain contract checked by
configure_diffusion(); no tensor-value reads or solver selection occur in this transformable builder. Configure and validate the owning plan before lowering it.
- prepare_relaxation(workspace, rate, target=0.0, *, where=None)[source]#
Return updated implicit coefficients for a validated reservoir.
- diffuse_implicit_configured(c)[source]#
Backward-Euler sealed-boundary update using precomputed bands.
- diffuse_implicit_prepared(c, workspace, *, solve)[source]#
Advance from explicit coefficients using the configured solver plan.
- solve_tridiagonal_1d(a, b, c, rhs, *, solver='auto')[source]#
Solve a batched tridiagonal system along the final dimension.
This function remains as a public/debug helper. Hot material-process paths should prefer
SpatialOperator1D, which selects the solver and precomputes static bands outside the timestep loop.
Validation and contract errors#
- exception NumericalCurrentContractError[source]#
Raised when a runtime probe disproves a
NUMERICALdeclaration.Mechanism.NUMERICALis valid only for currents returning a tensor with the voltage’s shape, dtype, and device that are pointwise in voltage, deterministic, non-mutating with respect to the voltage input, and free of registered-state side effects. Dendra checks those properties with bounded probes on the first eager evaluation for each input signature. Passing the probes is useful evidence, not a proof for unprobed or state-dependent behavior.
- exception UnsafeAutomaticNumericalFallbackError[source]#
Raised when exact current conductance analysis cannot be completed.
Numerical differentiation is sound for Dendra’s local conductance term only when the authored current is deterministic, side-effect free, and pointwise in voltage. A failed symbolic analysis does not establish those properties, so silently switching to simultaneous finite differences is unsafe.