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.Parameterized to 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 the mechanism.DE ModuleDict.

  • 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 Mechanism is 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 as g * (v - e) because S/cm² * mV = mA/cm². Dendra keeps these values as densities during mechanism assembly and applies compartment area in the voltage solver.

Inherit from PointProcess when a mechanism instead returns a lumped current in nA and uses conductance in µS. The conversion factors in dendra.units are plain scalars for documented public base units; do not form density units with expressions such as S / cm**2.

Subclasses declare nested state, persistent CARRY(), ephemeral ASSIGNED(), and ionic/material dependencies during class definition. initial_values and advance define persistent initialization and one accepted-timestep transition; assigned_values defines 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 key represents 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 key storage 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 USEION declarations 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 / ions blocks 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 USEION declarations alongside generic USEMATERIAL declarations. Ion entries use read for concentration/reversal/current reads, write_current for ionic current writes such as ica, and write_concentration for concentration writes such as cai.

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 suffix is None.

  • suffix (str, optional) – Suffix appended to the original class name when new_name is omitted.

Returns:

Mechanism subclass identical to cls but with a new __name__.

Return type:

type

Raises:
  • ValueError – If both new_name and suffix are None.

  • TypeError – If suffix is 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, where G and J do not depend on v with 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 ASSIGNED(*args)[source]#

Declare repeatable ephemeral algebra returned by assigned_values.

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 through advance(); current- stage algebra belongs in ASSIGNED() instead.

Parameters:
  • *args (str) – Names of persistent carry tensors.

  • dtype (torch.dtype, optional) – Fixed carry dtype. None follows 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_dict registration. The framework refreshes it after effective parameters, temperature, and local geometry have been populated, before State defaults and authored initial_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. None follows 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_conductance method 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_conductance method 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 through USEION(). Dendra owns the checkpointed <current>_ mirror, initializes it to zero, and updates it whenever that current is evaluated. Authored initial_values and advance hooks 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 dt argument instead of mutating module state. Do not repeat the same name in a CARRY(), DERIVED_BUFFER(), or ASSIGNED() 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}, or i{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 read and write because 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.

clear_injections()[source]#

Remove all waveform injections registered on this mechanism.

delayed_state(name, value, *, delay_steps=None, mode=None)[source]#

Return a delayed copy of value and 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 values frame and return their replacements for advance(), initial_values() or voltage_values(). Neither inputs nor module state are mutated. Registration and capacity are fixed; use the native delayed_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(). values must have the same shape as the like tensor 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 dt in 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. v defaults to the first injection mask, an existing named current, or diam. t defaults to the mechanism’s clock, or zero when it has no clock. Pure hooks use injection_values() with explicit v and t instead.

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 ic run 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.

values includes initialized STATE/CARRY values, support-visible celsius and diam, 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 call register_waveform_injection() to get padded I(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 index to 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:

True only if the mechanism accepts complete ownership of the injection. Returning False leaves 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.

v supplies the local output shape, device and dtype. t is 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 from assigned_values or 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 circular when the mechanism is in eval mode and gradients are disabled; otherwise use shift.

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 k appears after delay_steps subsequent 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, use NetCon / ContinuousCon or 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 mechanism CARRY storage 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) and stream_axis=-2 is 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. auto uses 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 like containing 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 before stream_axis for backwards compatibility. Use delay_axis=0 for 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_states supports heterogeneous per-stream integer delays, but all streams in a group share one circular pointer and one buffer depth equal to max(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 False without storing state so the solver can deliver the full injection exactly once.

resample_random_parameters(*names, force=True)[source]#

Resample mechanism-level and nested-State random parameters.

resample_runtime_noise(*names, dt=None, phase=None)[source]#
reset_delayed_states(*names)[source]#

Zero registered delayed-state buffers and reset circular pointers.

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 Mechanism and register them with Mechanism.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 ephemeral ASSIGNED values 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 x therefore has units unit(x)/ms; an SDE diffusion coefficient has units unit(x)/sqrt(ms). Voltage arguments are in mV, self.celsius is 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, use CARRY().

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 custom advance() implementation.

Parameters:
  • *args (str) – Persistent carry names to allocate.

  • dtype (torch.dtype, optional) – Fixed carry dtype. None follows 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_dict registration, 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 authored initial_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. None follows 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. Passing None leaves 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_dict registration, but are rebuilt whenever an integrator configures its timestep. The builder must be pure and may depend on the explicit scalar dt argument as well as populated parameters, temperature, local geometry, and initialization-static derived buffers. Do not repeat the same name in a separate CARRY() 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’s shape_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, draws supplies 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. Omitting draws samples 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 v and values as read-only and do not update persistent carry here.

derive_buffers()[source]#

Return initialization-static buffers declared by DERIVED_BUFFER.

derive_timestep_buffers(dt)[source]#

Return timestep workspaces declared by TIMESTEP_BUFFER.

initial_values(v, values)[source]#

Return a pure initialization overlay for this State.

The optional mapping may contain this State’s declared STATE and CARRY names. values exposes their current initialized values, support-visible celsius and local diam inputs, 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 ic value. Return a mapping from every such state name to a Tensor (or a value broadcastable to the support-local voltage shape).

values explicitly exposes available shared seeds/overrides plus support-visible celsius and local diam. 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 nested State variable and CARRY() replacements. The hook is pure: its voltage, timestep, and values inputs 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 key represents 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 key storage 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 or self.

values follows the ordinary Mechanism runtime frame: declared persistent/assigned values, prepared workspaces, local shared fields, celsius, and diam. Parameters may be read through self. updates may 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 match v in 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-in expsyn and exp2syn event weights are consequently numerical values in µS (for example, weight=0.05 means 0.05 µS).

Dendra divides point-process currents and conductances by 1e6 * area_cm2 before 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, use 50 * 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 key represents 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 key storage 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 standard net_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.

NetCon weights inherit their units from the target synapse. For the built-in point-process expsyn and exp2syn mechanisms, weights are numerical values in µS. A custom density-style Synapse may 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 key represents 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 key storage 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.

weights is a Tensor broadcast to this mechanism’s local runtime shape. dt is 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. values contains the Mechanism state, prepared workspace, and shared-field frame plus a state_carry mapping 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 through self.

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.

net_receive(weights, netcon)[source]#

Apply a pure receive hook once at the existing NetCon boundary.

class ContinuousSynapse(*args, **kwargs)[source]#

A mechanism that receives continuously valued presynaptic variables.

ContinuousSynapse is the analog counterpart to Synapse. 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 calling continuous_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>_old when the input was declared with the default keep_old=True.

A ContinuousSynapse follows the ordinary distributed Mechanism unit contract unless it also inherits PointProcess: 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>_old buffers 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.

value and Boolean mask have the named input’s local shape. received marks elements delivered earlier in this timestep, including actual zero deliveries. dt has shape (1,). values uses the event-receive frame, including input/old-input CARRY and nested State CARRY. Return event-style states, carry and state_carry mappings 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_receive overrides remain native-only.

continuous_receive(value, con=None, input=None, reduce=None, mask=None)[source]#

Apply the shared pure receive hook at the native connection boundary.

Ions and shared materials#

register_ion(ion, valence, e, i0, o0, min_concentration=None)[source]#

Register a new ion species with its properties.

Parameters:
  • ion (str) – The name of the ion (e.g., ‘na’, ‘k’, ‘ca’).

  • valence (float) – The valence of the ion (e.g., 1.0 for Na+, 2.0 for Ca2+).

  • e (float) – The reversal potential (in mV) for the ion.

  • i0 (float) – The initial intracellular concentration of the ion (in mM).

  • o0 (float) – The initial extracellular concentration of the ion (in mM).

  • min_concentration (float, optional) – The minimum concentration of the ion (in mM). If None, a default value is used.

concentrations(use_last=False, **kwargs)[source]#
equilibria(use_last=False, **kwargs)[source]#
register_material(name, fields=None, *, initial_values=None, min_values=None, conserved=True, domain='i', units=None, aliases=None)[source]#

Register a named material type and its default field declarations.

Registration is optional: callers may instantiate Material directly with explicit fields. Registering is useful when a Population convenience API wants to construct the material by name.

material_defaults(material, use_last=False, **field_updates)[source]#

Temporarily update registered material initial values.

This mirrors the existing ion concentration/equilibrium context managers but is intentionally generic. Only fields that already exist in the registered material spec may be updated.

class Material(name, shape, fields=None, *, initial_values=None, min_values=None, specs=None)[source]#

Population-wide material field container.

A Material is present over the full compartmental shape of a population. Mechanisms read/write local views using Mechanism.USEMATERIAL(…), while MaterialProcess subclasses can operate on full fields directly.

Each field has two distinct roles: field is mutable runtime state, while initial_source() returns its registered initial-value parameter or parametric module. initialize() resolves that source afresh. This preserves gradients to trainable initial values in training mode; evaluation initialization produces detached runtime fields. Canonical bounded sources are evaluated from their current raw parameters without reusing or changing their inference caches.

initial_source(field)[source]#

Return the registered parameter/module used to reset field.

The returned object is the source itself, not its resolved tensor value. It therefore remains visible to named_parameters(), follows device/dtype moves, and is serialized by state_dict().

initialize(*args, **kwargs)[source]#

Reset material fields from current registered initial-value sources.

advance(*args, **kwargs)[source]#

Apply generic field guards/derived updates.

Generic materials only enforce minimum values. Subclasses such as Ion override this to update derived fields like reversal potentials.

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 expose material_fields, prepare operator data with prepare_materials(), and return replacement fields from material_updates(). The native advance_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. Use configure_process() for persistent configuration and set_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 key represents 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 key storage 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 METHOD(method='none', **kwargs)[source]#

Declare the process-level numerical method.

static PHASE(phase='post_local')[source]#

Declare one of post_local, transport, or post_transport.

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.

set_dt(dt)[source]#

Apply this MaterialProcess family’s timestep configuration.

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. prepared lets 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(), and advance_materials().

prepare_materials(fields, dt)[source]#

Return tensor-only operator data without changing fields or self.

fields is 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.

material_updates(fields, prepared)[source]#

Return full-field replacements without mutating inputs or self.

Returned keys use the same canonical identifiers as fields. The adapter owns publication of this transaction, including later shared field guards and derived updates such as Nernst reversals.

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 by Population.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() (alias BATH()) optionally fuses linear reservoir coupling into the implicit diffusion solve. With storage matrix M, diffusion Laplacian L, non-negative rate Lambda, reservoir value c_bath, and the field c_source after 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. RELAX is currently implicit-only.

Analytic 1-D models support interface_scheme="arithmetic" (the legacy default) and interface_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 key represents 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 key storage 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 to f"{material}i".

  • D – Diffusivity in um^2 / ms. It may be a scalar, tensor, or the name of a process parameter/buffer. With D_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) means D is scalar or node-aligned. The spatial backend derives interface coefficients from endpoint values. "edge" means D is scalar or interface-aligned (final dimension C - 1 for an unbranched population, or compact Tree edge dimension E in material_edge_index order). 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 mean 0.5 * (D_i + D_j). Named geometry rejects interface_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 e describes parent[e] -> child[e] as exposed by material_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) and None mean 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 with rate == 0 contribute no relaxation. Thus where="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 requires METHOD("implicit"). For bath-only dynamics, declare the field with DIFFUSE(..., D=0) and then RELAX it.

Only "all" and None are 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.

BATH is an exact declaration alias for RELAX.

property graph#

Graph proxy used by SpatialOperatorTree during set_dt(…) precompute.

material_volume(domain='intracellular')[source]#

Return the process-local volume/mass buffer for a material domain.

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 key represents 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 key storage 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 to f"{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.

static DECAY(material, *, field=None, rate=None, target=0.0, domain=None)[source]#

Alias for CLEAR().

static RELAX(material, *, field=None, rate=None, target=0.0, domain=None)[source]#

Alias for CLEAR().

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_transport so 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 with ClampProcess.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 key represents 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 key storage 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 to f"{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 to value. "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.

lower and upper may be scalars/tensors or parameter names. If upper is omitted, only the lower bound is applied through MIN.

This helper is intentionally named BOUNDS rather than RANGE so it does not shadow Mechanism.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 a and b are concentration-like material fields, V_a and V_b are their local mass/volume weights, and g is an exchange conductance. If rate is supplied instead of conductance, Dendra uses g = rate * V_a; thus rate has units 1/ms and describes the first-order relaxation rate of pool a toward pool b when volumes are fixed.

The default method is the exact closed-form update for fixed rate/g and fixed volumes over the timestep. It preserves V_a*a + V_b*b up 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 key represents 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 key storage 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 plus field_a=... / field_b=....

  • b – Material field references. Accepted forms are ("ca", "cai"), "ca.cai", or a material name plus field_a=... / field_b=....

  • rate – First-order rate in 1/ms. Dendra converts this to an exchange conductance via g = rate * volume_a. If omitted and conductance is 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 rate or conductance, 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 unless METHOD(..., 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 unless METHOD(..., 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 / ms by 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 in configure_diffusion(...); the per-step diffuse_*_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_mask selects 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.

prepared_buffers()[source]#

Export an independent, differentiable numerical workspace.

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.

diffuse_explicit_configured(c)[source]#

Explicit sealed-boundary finite-volume update using precomputed geometry.

diffuse_explicit_prepared(c, workspace)[source]#

Advance explicit diffusion without reading bound numerical buffers.

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#

validate(mechanism)[source]#
exception NumericalCurrentContractError[source]#

Raised when a runtime probe disproves a NUMERICAL declaration.

Mechanism.NUMERICAL is 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.