Mechanisms, Ions, and Materials#
This guide explains how to define local ion-channel dynamics, choose the right lifetime for each tensor, and compose mechanisms with shared Ion and Material fields and spatial material processes. For a complete event-driven synapse, including insertion, event delivery, and functional execution, see Writing your own synapse.
Mechanism, State, Material, and MaterialProcess#
Dendra separates local biophysics from shared population-wide fields.
Mechanism (
Mechanism): user-facing local biophysics. A mechanism declares parameters, state bundles, currents, ion/material dependencies, and lifecycle hooks.State (
State): helper class for private per-mechanism state variables and their ODEs/kinetics. RegisterStatesubclasses withMechanism.STATE_BUNDLE(...).Material: population-wide shared fields that exist in every compartment and can be read/written/sourced by multiple mechanisms. Ions are specialized materials with valence, current, and Nernst/reversal-potential semantics.
MaterialProcess: process-level dynamics over full material fields. Examples include
DiffusionProcess,ClearanceProcess,ClampProcess, andExchangeProcess. These are inserted like mechanisms but are scheduled in material phases rather than treated as ordinary local channel mechanisms.
A useful rule of thumb is: use State for variables private to one mechanism; use Material when the variable represents shared biochemical, chemical, or ionic state that several mechanisms may need to read, write, source, or spatially process.
Membrane-mechanism unit contract#
Dendra uses plain numeric tensors rather than unit-carrying quantities, so mechanism authors are responsible for following the public unit contract:
An ordinary
Mechanism, including aContinuousSynapsethat does not also inheritPointProcess, is distributed over membrane area. Voltage and reversal potentials are in mV; current methods return outward-positive current density in mA/cm²; conductance parameters anddI/dVare in S/cm². The identity S × mV = mA makesg * (v - e)a current density without an extra factor of 1000.A
PointProcessis lumped at a finite-area compartment. Its current methods return nA and its conductances use µS; Dendra divides the raw values by1e6 * area_cm2to obtain mA/cm² and S/cm² for the density-based cable equation. The corresponding identity is µS × mV = nA. A point process therefore cannot be attached to a zero-area branchpoint.
Do not mix these contracts: a distributed channel parameter such as HH gnabar=0.12 means 0.12 S/cm² (120 mS/cm²), whereas a point-synapse conductance of 0.001 means 0.001 µS (1 nS). Built-in point-synapse weights are bare values in this local µS coordinate and must not be multiplied by dendra.units.uS. See Units used in Dendra for the complete convention.
Declaring state variables and dynamics#
Use a State subclass to name solver variables and define their dynamics with DERIVATIVE or KINETIC. Register it on the owning mechanism with Mechanism.STATE_BUNDLE(...). The declarations distinguish three kinds of runtime values:
Declaration |
Lifetime and update rule |
Typical use |
|---|---|---|
|
Persistent solver state, advanced by the declared equations or a custom |
Gates, synaptic conductance, reaction intermediates |
|
Persistent, checkpointed state updated through a returned initialization, accepted-step, or supported event mapping |
Counters, latches, timers, histories |
|
Ephemeral algebra returned by |
Steady states, time constants, conductance algebra |
assigned_values can run several times within one timestep, at different stage voltages. Keep it deterministic and read-only. A counter or a once-per-step recovery belongs in advance, or in a declared State equation when it describes continuous dynamics. Event-triggered jumps belong in Synapse.net_receive_values; see Writing your own synapse.
Simulation time and dt are in ms. Consequently, if a state variable x has units U, the right-hand side of x' = ... must evaluate in U/ms; a first-order rate constant is in ms⁻¹ and a time constant is in ms. Dendra does not infer or validate these dimensions. For an SDE, the diffusion coefficient multiplying dW has units U/√ms.
from dendra.models.mechanisms import Mechanism as M
from dendra.models.mechanisms import State as S
from dendra.models.mechanisms import (
DiffusionProcess,
ClearanceProcess,
ClampProcess,
ExchangeProcess,
register_material,
register_ion,
)
from dendra.models.mechanisms.ops import exp, vtrap
class mhn(S):
S.STATE("m", "h", "n")
S.METHOD("cnexp")
S.DERIVATIVE(
"m' = (minf - m) / mtau",
"h' = (hinf - h) / htau",
"n' = (ninf - n) / ntau",
)
S.ASSIGNED("minf", "mtau", "hinf", "htau", "ninf", "ntau")
S.DERIVED_BUFFER("q10")
def derive_buffers(self):
return {"q10": 3.0 ** ((self.celsius - 6.3) / 10.0)}
def assigned_values(self, v, values):
del values
alpha_m = 0.1 * vtrap(-(v + 40), 10)
beta_m = 4 * exp(-(v + 65) / 18)
tot = alpha_m + beta_m
mtau = 1 / (self.q10 * tot)
minf = alpha_m / tot
alpha_h = 0.07 * exp(-(v + 65) / 20)
beta_h = 1 / (exp(-(v + 35) / 10) + 1)
tot = alpha_h + beta_h
htau = 1 / (self.q10 * tot)
hinf = alpha_h / tot
alpha_n = 0.01 * vtrap(-(v + 55), 10)
beta_n = 0.125 * exp(-(v + 65) / 80)
tot = alpha_n + beta_n
ntau = 1 / (self.q10 * tot)
ninf = alpha_n / tot
# return dict whose keys match ASSIGNED names
return {"mtau": mtau, "minf": minf, "htau": htau, "hinf": hinf, "ntau": ntau, "ninf": ninf}
def state_defaults(self, v, values):
assigned = self.assigned_values(v, values)
return {"m": assigned["minf"], "h": assigned["hinf"], "n": assigned["ninf"]}
class hh(M):
"""
Classic Hodgkin-Huxley mechanism with m/h/n gates and leak.
"""
M.STATE_BUNDLE(mhn)
# Conductance densities are in S/cm²; reversal potentials are in mV.
M.GLOBAL(gnabar=0.12, gkbar=0.036, gl=0.0003, ena=50.0, ek=-77.0, el=-54.3)
M.NONSPECIFIC_CURRENT("il", "ina", "ik")
# Example for ions: M.USEION("na", read=("nai", "nao", "ena"), write=("ina",))
def il(self, v):
return self.gl * (v - self.el)
def ina(self, v):
gna = self.gnabar * self.m**3 * self.h
return gna * (v - self.ena)
def ik(self, v):
gk = self.gkbar * self.n**4
return gk * (v - self.ek)
Methods of integration#
Dendra supports multiple methods for integrating State dynamics. The preferred way to select an integration method is with the State.METHOD(...) declaration inside a State subclass:
from dendra.models.mechanisms._state import State as S
class MyState(S):
S.STATE("x", "y")
S.METHOD("rosenbrock", fallback="derivimplicit")
S.DERIVATIVE(
"x' = -a*x + y*y",
"y' = -b*y + x",
)
S.METHOD(method, **kwargs) selects the integration method and passes method-specific options to the solver builder. It is the only supported declaration form; direct class assignments to method or method_kwargs are rejected so inherited solver policy remains unambiguous. See Upgrading Dendra when migrating an older custom State.
"cnexp"#
Exact exponential integration for independent scalar affine ODEs.
Use this for equations of the form:
x' = a + b*x
or, equivalently, common gating equations such as:
x' = (x_inf - x) / tau_x
where coefficients are treated as fixed over the timestep.
Example:
class Gate(S):
S.STATE("m")
S.METHOD("cnexp")
S.DERIVATIVE(
"m' = (minf - m) / mtau",
)
"cnexp" is the default method. It is usually the fastest and most accurate method for Hodgkin-Huxley-style independent gates. It should be preferred whenever the state equation is independent and affine in its own state.
cnexp can also be applied to systems where each scalar equation is affine in its own state but depends on other state variables. In that case, the other states are treated as constants over the timestep, using their values at the beginning of the step. This is a frozen-coupling approximation: it is fast and often useful, but it is not an exact coupled solve.
Supported aliases include:
"cnexp"
"rush_larsen"
"rl"
"bufferimplicit"#
Specialized implicit integration for two-state free/bound buffer systems.
Use this for systems like calcium buffering:
bound' = ku * free * (1 - bound) - kr * bound
free' = source - gamma * bound'
For example:
class oc_cai(S):
S.STATE("oc", "cai")
S.METHOD("bufferimplicit", bound="oc", free="cai")
S.DERIVATIVE(
"oc' = ku * cai * (1 - oc) - kr * oc",
"cai' = -ica * SA / Vol / (2*FARADAY) - nb * Bi * (ku * cai * (1 - oc) - kr * oc)",
)
This method performs a closed-form backward-Euler update by reducing the implicit system to a scalar quadratic solve. It avoids Newton iteration, preserves the buffer/free-concentration conservation relation under the backward-Euler discretization, and is much faster than derivimplicit for this motif.
This is the preferred method for oc/cai-style intracellular calcium buffering systems.
Common options:
S.METHOD(
"bufferimplicit",
bound="oc",
free="cai",
clamp_discriminant=True,
eps=1e-30,
clamp_bound=False,
bound_min=0.0,
bound_max=1.0,
free_min=None,
strict=True,
fallback=None,
)
Supported aliases include:
"bufferimplicit"
"buffer"
"implicit_buffer"
"ca_buffer"
"calcium_buffer"
"calciumbuffer"
"linearimplicit" / "sparse"#
Implicit backward-Euler integration for coupled affine-linear systems.
Use this for systems of the form:
x' = A*x + b
where the state variables may be coupled, but the right-hand side is affine-linear in the state vector.
Example:
class Markov2(S):
S.STATE("C", "O")
S.METHOD("sparse")
S.DERIVATIVE(
"C' = -alpha*C + beta*O",
"O' = alpha*C - beta*O",
)
The method generates the backward-Euler update:
(I - dt*A) * x_next = x + dt*b
This is the correct choice for coupled linear Markov models, linear kinetic schemes, linear exchange systems, and other affine-coupled state systems.
Although "sparse" is provided as an alias for NMODL familiarity, the current implementation is best thought of as a generated batched small-system linear implicit solver. It does not require the user to manually assemble a sparse matrix.
This method is not valid for nonlinear state coupling such as:
x' = x*y
x' = sin(x) - y
oc' = ku*cai*(1 - oc) - kr*oc
For the last case, use "bufferimplicit" if the equations match the calcium-buffer motif, or "rosenbrock" / "derivimplicit" otherwise.
Common options:
S.METHOD(
"sparse",
solver="auto",
jacobian_regularization=0.0,
strict=True,
fallback=None,
)
Fallback examples:
S.METHOD("sparse", fallback="rosenbrock")
S.METHOD("sparse", fallback="derivimplicit")
Supported aliases include:
"linearimplicit"
"linear_implicit"
"implicitlinear"
"implicit_linear"
"affineimplicit"
"affine_implicit"
"sparse"
"be_linear"
"backward_euler_linear"
"linear_be"
"rosenbrock"#
A general linearly implicit method for nonlinear ODE systems.
Given:
x' = f(x)
Rosenbrock-Euler evaluates the RHS and Jacobian at the beginning of the timestep, then solves:
(I - gamma*dt*J) * k = dt*f(x)
x_next = x + damping*k
Example:
class NonlinearState(S):
S.STATE("x", "y")
S.METHOD("rosenbrock", fallback="derivimplicit")
S.DERIVATIVE(
"x' = -a*x + y*y",
"y' = -b*y + x",
)
This is a good general-purpose method for nonlinear systems when cnexp, bufferimplicit, and linearimplicit do not apply. It is usually much faster than derivimplicit because it uses one RHS evaluation, one Jacobian evaluation, and one linear solve, without Newton iterations or line search.
For affine-linear systems, "rosenbrock" with gamma=1.0 gives the same update as backward Euler. For nonlinear systems, it is an approximation to fully implicit backward Euler based on a local linearization.
Common options:
S.METHOD(
"rosenbrock",
gamma=1.0,
damping=1.0,
jacobian_regularization=0.0,
strict=True,
fallback=None,
)
Supported aliases include:
"rosenbrock"
"rosenbrock1"
"rosenbrock_euler"
"linearlyimplicit"
"linearly_implicit"
"linearized_implicit"
"linearly_implicit_euler"
"linimplicit"
"semiimplicit"
"semi_implicit"
"derivimplicit"#
Fully implicit backward-Euler integration for general ODE systems using Newton-Raphson iteration.
Use this for nonlinear and coupled ODE systems when a more specialized method is not available or when a fully converged implicit solve is desired.
Example:
class GeneralImplicitState(S):
S.STATE("x", "y")
S.METHOD(
"derivimplicit",
newton_iters=4,
damping=1.0,
line_search=False,
)
S.DERIVATIVE(
"x' = -a*x + y*y",
"y' = -b*y + sin(x)",
)
derivimplicit constructs the backward-Euler residual:
R(x_next) = x_next - x - dt*f(x_next)
and approximately solves:
R(x_next) = 0
using Newton iterations.
This is the most general method, but it is also the most expensive. It may require multiple RHS evaluations, Jacobian evaluations, and linear solves per timestep. It can also have convergence issues for very stiff systems, poor initial guesses, or large timesteps.
Dendra attempts to generate analytic Jacobians when possible. If analytic Jacobian generation fails, the method may fall back to a slower Jacobian path, depending on solver options.
Common options:
S.METHOD(
"derivimplicit",
max_iter=8,
tol=1e-8,
damping=1.0,
line_search=True,
max_ls_steps=8,
ls_decay=0.5,
jacobian_regularization=0.0,
detach_newton=None,
create_graph=None,
)
Aliases for max_iter include:
"newton_iters"
"iterations"
For compiled training workloads, a fixed small number of Newton iterations with line search disabled is often more compiler-friendly:
S.METHOD(
"derivimplicit",
newton_iters=3,
damping=1.0,
line_search=False,
)
Supported aliases include:
"derivimplicit"
"deriv_implicit"
"implicit"
"backward_euler"
"be"
Choosing a method#
A useful rule of thumb is:
Use “cnexp” when each state equation is independent and affine in its own state.
Use “bufferimplicit” for free/bound buffer systems such as oc/cai calcium buffering.
Use “linearimplicit” or “sparse” for coupled affine-linear systems, such as Markov state models.
Use “rosenbrock” for nonlinear systems when you want a fast, stable, fixed-work method.
Use “derivimplicit” when you need the most general fully implicit solver or as a reference/fallback.
For example:
# Independent HH-style gate
S.METHOD("cnexp")
# Calcium buffer motif
S.METHOD("bufferimplicit", bound="oc", free="cai")
# Coupled linear Markov model
S.METHOD("sparse")
# General nonlinear fast fallback
S.METHOD("rosenbrock", fallback="derivimplicit")
# Fully implicit Newton solve
S.METHOD("derivimplicit", newton_iters=4, line_search=False)
A recommended fallback pattern for nonlinear mechanisms is:
S.METHOD("rosenbrock", fallback="derivimplicit")
A recommended fallback pattern for systems expected to be linear is:
S.METHOD("sparse", fallback="rosenbrock")
This lets Dendra use the fastest valid solver when the symbolic structure matches, while retaining a more general method when it does not.
Runtime noise and State SDEs#
Dendra distinguishes noise variables in mechanisms from stochastic differential equations in state variables.
Detached runtime noise for mechanisms#
Mechanism.GLOBALNOISE, Mechanism.BATCHNOISE, and Mechanism.RANGENOISE declare buffers that are resampled during simulation. These are useful for stochastic currents or other exogenous drives:
from dendra.models.mechanisms import Mechanism
class NoisyCurrent(Mechanism):
Mechanism.NONSPECIFIC_CURRENT("i")
Mechanism.RANGENOISE("eta", distribution="normal", mu=0.0, sigma=1.0)
Mechanism.RANGE(sigma_i=0.01)
def i(self, v):
return self.sigma_i * self.eta
Runtime NOISE values are detached from their distribution parameters, base draws and timestep scaling. Gradients can still flow through ordinary coefficients such as sigma_i, which multiplies the detached noise in the current calculation. These semantics apply in native and functional execution; see inputs and randomness for explicit draws and replay.
Stochastic State dynamics#
For stochastic dynamics of state variables, use State.DIFFUSION(...) with an SDE-aware State.METHOD(...). Dendra currently provides two explicit State SDE methods:
State.METHOD("euler_maruyama")for Itô SDEs.State.METHOD("euler_heun")for Stratonovich SDEs.
Both represent equations with drift and diffusion terms:
dx = f(x, t) dt + g(x, t) dW
For euler_heun, the stochastic term is interpreted in Stratonovich form, often written with a circle:
dx = f(x, t) dt + g(x, t) ∘ dW
Example:
from dendra.models.mechanisms import State
class OU(State):
State.STATE("x")
State.RANGE(mu=0.0, tau=10.0, sigma=1.0)
State.ASSIGNED("drift_mu", "drift_tau", "diff_sigma")
State.DERIVATIVE("x' = (drift_mu - x) / drift_tau")
State.DIFFUSION("x = diff_sigma")
State.METHOD("euler_maruyama")
def assigned_values(self, v, values):
del v, values
return {
"drift_mu": self.mu,
"drift_tau": self.tau,
"diff_sigma": self.sigma,
}
The generated Euler-Maruyama update is:
x_next = x + f(x) dt + g(x) sqrt(dt) eps
where eps is a detached standard-normal increment. Drift and diffusion coefficients retain their parameter gradients through the state update.
For Stratonovich multiplicative noise, use Euler-Heun:
class MultiplicativeNoise(State):
State.STATE("x")
State.RANGE(sigma=0.2)
State.ASSIGNED("diff_sigma")
State.DERIVATIVE("x' = 0.0")
State.DIFFUSION("x = diff_sigma * x")
State.METHOD("euler_heun")
def assigned_values(self, v, values):
del v, values
return {"diff_sigma": self.sigma}
Euler-Heun evaluates a predictor state and averages the old/predicted diffusion coefficients:
x_pred = x + f(x) dt + g(x) dW
x_next = x + f(x) dt + 0.5 * (g(x) + g(x_pred)) * dW
Pass average_drift=True to also average the deterministic drift term:
State.METHOD("euler_heun", average_drift=True)
These SDE methods evolve declared State variables. For a stochastic drive to the voltage equation, use a noise-dependent current such as NoisyCurrent above.
Q10 scaling#
Declare DERIVED_BUFFER("q10") for a temperature factor that remains fixed during a run. Return the factor from pure derive_buffers(self). In the HH gates above:
S.DERIVED_BUFFER("q10")
def derive_buffers(self):
return {"q10": 3.0 ** ((self.celsius - 6.3) / 10.0)}
Use self.q10 in assigned_values or kinetic rate calculations to scale time constants and rates. Ordinary Population.initialize() rebuilds it from the freshly populated parameters and temperature. If those inputs change, initialize again before continuing with refreshed coefficients. In functional execution, rebuild preparation from the new explicit parameters/constants with prepare, or use a combined prepare_and_* operation.
State defaults and initialization#
Initialization is a state-construction phase; it does not take a timestep. The ordered precedence is:
shared Ion/Material seed,
State.state_defaults(v, values),insertion-time
icoverrides,Mechanism.initial_values(v, values),each registered State’s
initial_values(v, values), in bundle order.
state_defaults supplies fallback solver values for names without an explicit ic. An initial_values hook returns a partial overlay: a State can return its own STATE and CARRY names; a Mechanism can return flattened solver-state names, direct Mechanism CARRY, and its owned writable Ion/Material locals. A later overlay can intentionally replace an ic value. Ordinary carry starts from zero on fresh initialization; initialize any other desired value explicitly.
Initialization overlays return Tensors with the declared dtype and device. Their shapes may broadcast to the declared local or structural storage shape; Dendra materializes independent storage. Read the ordered inputs from values and parameters/prepared workspaces through self; do not mutate either. The frame includes available initialized values, local shared fields, celsius and diam. State INPUT declarations use their defaults during initialization, even when a runtime binding exists.
Supply every solver variable through a seed, default, ic, or overlay when using fresh functional initialization. See Model initialization for the complete initialization lifecycle and Population-level setup hooks/transforms.
Multiple State bundles per Mechanism#
A mechanism can register multiple State subclasses with separate M.STATE_BUNDLE(...) calls or one call containing several classes. Each bundle class name and every flattened State.STATE tensor name must be unique within that Mechanism.
All bundles and the owning Mechanism.advance read one snapshot of the mechanism’s state before the accepted-step transition. Dendra computes their returned updates first, then commits them together. A later bundle or the Mechanism hook therefore does not see another bundle’s newly solved state during that transition. Use a coupled State system when equations need to be solved together; registering separate bundles does not make the solver jointly integrate their equations.
Prepared workspaces and persistent carry#
Use
DERIVED_BUFFER(name, ...)for a workspace determined entirely by populated parameters, temperature, and local geometry. Purederive_buffers(self)must return exactly the declared names. Ordinary initialization builds these before State defaults and initialization overlays; functional preparation rebuilds them from explicit inputs.Use
TIMESTEP_BUFFER(name, ...)when the workspace also depends ondt, and return exactly its names fromderive_timestep_buffers(self, dt). The framework configures these after initialization when the integrator starts or its timestep changes. Fresh initialization exposes literal zero timestep buffers; it does not call the timestep builder, even atdt=0.Neither builder may read voltage, evolving state/shared fields, implicit randomness, or mutate module tensors. A timestep builder may read static derived workspaces, but must not read another installed timestep workspace. Keep related timestep calculations in one builder’s local variables.
Workspace outputs must be Tensors on the declared dtype/device and broadcast to the declared storage shape. A default timestep workspace uses the owner’s parameter-local shape;
shape=()or an explicit tuple declares structural storage that does not acquire Population batch axes.Prepared values are reused, rather than tracked reactively after arbitrary parameter edits. Reinitialize to refresh effective parameters/static workspaces; reconfigure the integrator timestep for timestep workspaces. Functional callers must call
prepareagain after changing parameters/constants, or useprepare_and_*.Use
CARRY(name, ...)for persistent, checkpointed values that change during simulation. A pureinitial_values(self, v, values)method initializes it, andadvanceor a supported event hook returns later updates. Workspaces participate instate_dictserialization but are read-only prepared values, rather than mutable functional carry.Example (extracellular Ca accumulation in
caextscale):class cao(S): S.STATE("cao") S.GLOBAL(lseg=1.0, txfer=4511.0, FARADAY=96500.0, cabath=2.0, fhspace=1.0) S.DERIVED_BUFFER("SA", "Vol_peri") S.DERIVATIVE("cao' = (ica*SA/(2*Vol_peri*FARADAY) + (cabath - cao)/txfer)") def derive_buffers(self): SA = math.pi * (1e-4) * self.diam * self.lseg Vol = math.pi * ((1e-4) * (self.diam / 2)) ** 2 * self.lseg Vol_peri = ( math.pi * ((1e-4) * ((self.diam + self.fhspace) / 2)) ** 2 * self.lseg ) - Vol return {"SA": SA, "Vol_peri": Vol_peri}
SAandVol_periare reproducible preparation workspaces rather than evolving state. For voltage- or state-dependent initialization, use purestate_defaultsorinitial_values.
API overview#
State classmethods (at State definition)#
STATE(name, ...): declare solver-evolved tensor variables. This is distinct fromMechanism.STATE_BUNDLE(...), which registers a State class.METHOD(method, **kwargs): select the integration method and pass method-specific options. Examples include"cnexp","bufferimplicit","linearimplicit"/"sparse","rosenbrock", and"derivimplicit".DERIVATIVE("x' = expr", ...): symbolic ODEs for states.KINETIC("~ a <-> b (alpha, beta)", ...): Markov/kinetic schemes between states.ASSIGNED(name, ...): ephemeral per-compartment algebra returned by pureassigned_values(v, values).INPUT(name, ..., default=0.0): ephemeral read-only tensors supplied to this State by explicitPopulation.bind_input(...)bindings; no buffer or checkpointed state is allocated.GLOBAL/RANGE: shared vs per-compartment parameters scoped to the State.CARRY(name, ..., dtype=None, shape="local"): persistent, checkpointed non-ODE state.DERIVED_BUFFER(name, ...): declare a preparation-time workspace returned by purederive_buffers.TIMESTEP_BUFFER(name, ...): declare adt-dependent workspace returned by purederive_timestep_buffers.
State dynamics are local to one mechanism. Use a Material for a shared biochemical field or population-wide spatial processing. For a read-only tensor dependency on another mechanism in the same Population, use a declared State INPUT and Population.bind_input(...); see Run models with explicit state. These bindings do not deliver Network events.
State.INPUT and ContinuousSynapse.INPUT serve different APIs. A State input is a read-only value resolved from a same-Population binding when its consumer advances. A continuous synapse input is a persistent delivery buffer reset and filled by Network continuous connections, with optional previous-input storage. Use the declaring class name explicitly; see Writing your own synapse for a continuous synapse example.
State lifecycle hooks#
derive_buffers(self): return exactly the declaredDERIVED_BUFFERnames from parameters, temperature and local geometry.derive_timestep_buffers(self, dt): return exactly the declaredTIMESTEP_BUFFERnames from prepared inputs and the scalar timestep in ms.state_defaults(self, v, values): supply fallback values for otherwise unresolved solver state.initial_values(self, v, values): return a partial initialization overlay for this State’sSTATEandCARRY.assigned_values(self, v, values): return exactly the declared ephemeralASSIGNEDnames. It may run several times per step.advance(self, v, dt, values): return every declared solver tensor and optionally this State’sCARRY. The default advances the declared equations. Override it only to implement a custom complete transition; the declared ODE solver does not also run automatically when you replace this method.
advance runs once per accepted timestep from the shared mechanism snapshot described above. Its values also includes this State’s carry and any declared INPUT tensors resolved at the consumer’s advance phase. assigned_values sees that same input frame, including during generated solver stage evaluations. Runtime assigned_values and advance outputs must exactly match their declared shape, dtype and device; initialization-only broadcasting does not apply here. Treat all inputs and self state as read-only and return new tensors instead of assigning buffers.
Mechanism classmethods (at mechanism definition)#
STATE_BUNDLE(StateSubclass, ...): register State bundles used by the mechanism; it does not itself declare a tensor. Bundle class names and their flattenedState.STATEtensor names must be unique within the Mechanism.GLOBAL,RANGE: shared vs per-compartment parameters on the mechanism.CARRY(name, ..., dtype=None, shape="local"): declare persistent, checkpointed non-ODE state.ASSIGNED(name, ...): declare ephemeral algebra returned byassigned_values.DERIVED_BUFFER(name, ...): declare a preparation-time workspace returned by purederive_buffers.TIMESTEP_BUFFER(name, ...): declare adt-dependent workspace returned by purederive_timestep_buffers.USEION(ion, read=(), write=()): declare ionic dependencies.read/writemust be in{ion}i,{ion}o,e{ion},i{ion}. For example, read("ena", "nai", "nao")and write("ina",)to contribute Na current.USEMATERIAL(material, read=(), write=(), source=()): declare generic shared-material dependencies. Use this for non-ion shared fields such asip3i,campi,atpi,pip2, mobile buffers, or for ion-backed fields when you want material-style access rather than current assembly.NONSPECIFIC_CURRENT(name, ...): register membrane currents not tied to an ion.SAVE_CURRENT(name, ...): retain Dendra’s latest assembled raw support-local current in the checkpointed<name>_mirror. A direct call to the current method does not refresh the mirror.EXPLICIT(name, ...): select explicit treatment of a declared current rather than an implicit conductance contribution. It does not assert that the current is voltage-independent.
For full-field material dynamics, use a MaterialProcess subclass instead of an ordinary Mechanism. Process subclasses also support declaration helpers such as PHASE(...), METHOD(...), and process-specific declarations like DIFFUSE(...), CLEAR(...), CLAMP(...), or EXCHANGE(...).
Mechanism lifecycle hooks#
derive_buffers(self): purely construct exactly theDERIVED_BUFFERoutputs from populated parameters, temperature and local geometry.derive_timestep_buffers(self, dt): purely construct exactly theTIMESTEP_BUFFERoutputs from prepared inputs and the timestep.initial_values(self, v, values): return a partial initialization overlay for flattened solver state, directCARRY, and owned writable shared-field locals.assigned_values(self, v, values): purely return exactly the ephemeral values declared withASSIGNED. Current methods can then read that algebra throughself.advance(self, v, dt, values): return a partial mapping of once-per-accepted-step updates for directCARRYand owned writable or additive shared-field locals. It cannot replace private bundle solver state or nested State carry. A solver-state name also declared as an owned writable Ion/Material local is still an allowed shared-field output; Mechanism updates commit after bundle results, so prefer one owner for a field’s transition. The hook reads the same pre-transition snapshot as all State bundles; omitted fields remain unchanged.Current methods (
ina,ik,il, etc.): implement currents declared viaNONSPECIFIC_CURRENTor ion writes inUSEION. For an ordinary distributedMechanism, they return outward-positive mA/cm² and their voltage derivative is S/cm². APointProcessinstead returns lumped nA and uses µS conductances; Dendra performs area normalization.
All returned runtime replacements must preserve the declared shape, dtype and device. Current methods and assigned_values are repeatable read-only algebra. Persistent changes belong in a declared State transition, an accepted-step mapping, or the appropriate event hook. Do not override internal initialization/solver adapters or ordinary-Mechanism set_dt; see Upgrading Dendra for replacements for older hooks.
Voltage and event hooks#
A VoltageProcess implements pure voltage_values(v, dt, values) -> (new_v, updates). new_v must preserve the local voltage schema. Its flat updates mapping may replace declared bundle STATE tensors and direct Mechanism CARRY; it cannot update nested State carry, shared fields, ASSIGNED, or prepared workspaces. The framework’s update_v adapter runs voltage processes in their ordered phase before State advancement/current assembly, and does not run them during initialization. See Run models with explicit state.
An event-driven Synapse implements pure net_receive_values(weights, dt, values). Its partial result separates "states", "carry", and nested "state_carry" namespaces. The canonical net_receive adapter applies it once per existing connection invocation, including zero payloads and repeated calls within one timestep. Keep continuous decay/recovery in State equations or advance, rather than applying it once per received call. The hook sees Tensor weights broadcast to actual target-local storage (including explicit batch axes), and a one-element dt Tensor of shape (1,). Both inputs use the target dtype/device. See Writing your own synapse for a complete implementation, payload units, and imperative/functional usage.
Legacy overrides of update_v or net_receive remain available imperatively; functional execution requires the pure hook and canonical adapter. Event hooks can read explicit state, prepared workspaces, shared fields and nested State carry. Ephemeral ASSIGNED values are excluded from the event frame: derive event algebra in the hook, or declare CARRY when it must persist.
Runnable lifecycle example#
This mechanism stores elapsed time (ms) and a dimensionless decaying memory in direct CARRY. The static rate depends on parameters and temperature; the prepared decay additionally depends on the timestep. At 32 °C, the chosen parameters give rate = 1 ms⁻¹.
Initialization sets memory to one and elapsed time to zero; it takes no timestep. The timestep workspace remains zero until the first step configures it. Each accepted-step hook computes replacements from the old values snapshot, then Dendra commits them together. Reinitialization resets the carry and returns the timestep workspace to its unconfigured zero value. The assertions check two steps against the independent exponential solution.
import torch
import dendra as dn
from dendra.models.mechanisms import Mechanism
class PreparedMemory(Mechanism):
Mechanism.GLOBAL(tau=2.0, q10=2.0) # tau in ms; reference at 22 degrees C.
Mechanism.CARRY("elapsed", "memory")
Mechanism.DERIVED_BUFFER("rate")
Mechanism.TIMESTEP_BUFFER("decay")
def derive_buffers(self):
return {"rate": self.q10 ** ((self.celsius - 22.0) / 10.0) / self.tau}
def derive_timestep_buffers(self, dt):
return {"decay": torch.exp(-dt * self.rate)}
def initial_values(self, v, values):
return {"elapsed": torch.zeros_like(v), "memory": torch.ones_like(v)}
def advance(self, v, dt, values):
return {
"elapsed": values["elapsed"] + dt,
"memory": values["memory"] * values["decay"],
}
with dn.ctx(DEVICE="cpu", DTYPE=torch.float64, JIT=0, REQUIRE_GRAD=0):
cells = dn.SingleCompartment(N=1, C=1, celsius=32.0, dtype=torch.float64)
cells.insert(PreparedMemory.rename("memory_demo"))
cells.eval()
cells.initialize()
memory = cells.mech.memory_demo
torch.testing.assert_close(memory.rate, torch.ones_like(memory.rate))
torch.testing.assert_close(memory.decay, torch.zeros_like(memory.decay))
torch.testing.assert_close(memory.elapsed, torch.zeros_like(cells.v))
torch.testing.assert_close(memory.memory, torch.ones_like(cells.v))
for step in (1, 2):
cells.step(dt=0.1)
torch.testing.assert_close(memory.elapsed, torch.full_like(cells.v, step * 0.1))
expected = torch.full_like(cells.v, -step * 0.1).exp()
torch.testing.assert_close(memory.memory, expected)
cells.initialize()
torch.testing.assert_close(memory.elapsed, torch.zeros_like(cells.v))
torch.testing.assert_close(memory.memory, torch.ones_like(cells.v))
torch.testing.assert_close(memory.decay, torch.zeros_like(memory.decay))
Example (h-channel with mechanism-level assigned algebra):
class h(M):
M.STATE_BUNDLE(s, f)
M.GLOBAL(gbar=0.0001) # S/cm² (distributed conductance density)
M.USEION("k", read=["ek"], write=["ik"])
M.USEION("na", read=["ena"], write=["ina"])
M.ASSIGNED("g")
def assigned_values(self, v, values):
del v
return {"g": self.gbar * (0.5 * values["s"] + 0.5 * values["f"])}
def ina(self, v):
return 0.5 * self.g * (v - self.ena)
def ik(self, v):
return 0.5 * self.g * (v - self.ek)
Here ASSIGNED("g") declares ephemeral conductance algebra. Dendra evaluates the pure assigned_values mapping whenever the integrator needs current inputs; g is not checkpointed carry. Because h derives from ordinary Mechanism, gbar and g are conductance densities in S/cm², v/ena/ek are in mV, and ina/ik return mA/cm².
Ions#
Dendra has built-in support for ionic concentrations and currents via the USEION mechanism classmethod. USEION is the right interface when a mechanism contributes an ionic current, reads an ionic reversal potential, or updates an ionic concentration.
Built-in ions and their standard fields are:
Sodium (
"na"):nai,nao,ena,inaPotassium (
"k"):ki,ko,ek,ikCalcium (
"ca"):cai,cao,eca,ica
The ion-field convention is fixed: <ion>i and <ion>o concentrations are in mM, e<ion> is in mV, and the assembled i<ion> field is outward-positive current density in mA/cm². A distributed mechanism that writes an ionic current therefore returns mA/cm²; a point process authors its lumped current in nA and Dendra normalizes that contribution before ion-current assembly.
Ions are also specialized Material objects. This means ion concentration fields such as cai can participate in generic material processes such as diffusion, while still retaining ion-specific behavior such as valence, ionic current bookkeeping, and Nernst/reversal-potential updates.
You can define custom ions with register_ion:
from dendra.models.mechanisms import register_ion
register_ion(
"cl",
valence=-1,
e=-65.0, # reversal potential [mV]
i0=10.0, # intracellular concentration [mM]
o0=110.0, # extracellular concentration [mM]
)
This makes "cl" available in USEION declarations with fields cli, clo, ecl, and icl.
USEION read/write semantics#
USEION declares that a mechanism interacts with ion-specific variables. For example:
M.USEION("na", read=["ena", "nai", "nao"], write=["ina"])
means the mechanism reads sodium reversal potential and concentrations and contributes sodium current. Dendra then makes ena, nai, and nao available to the mechanism and its State bundles, and expects the mechanism to define an ina(self, v) current method.
Concentration variables <ion>i and <ion>o can also be written by mechanisms when implementing local ion dynamics. For example:
M.USEION("ca", read=["ica"], write=["cai"])
makes ica available to the state dynamics and commits the local updated cai back to the population-wide calcium material/ion field. Dendra does not automatically turn membrane current into a concentration derivative: the model must supply the Faraday, valence, area, and volume conversion explicitly, as in the following example.
Example: intracellular Ca²⁺ accumulation with buffering#
import math
import torch
from dendra.models.mechanisms import Mechanism as M
from dendra.models.mechanisms import State as S
from dendra.models.mechanisms.ops import *
class oc_cai(S):
S.STATE("oc", "cai")
S.METHOD("bufferimplicit", bound="oc", free="cai")
S.GLOBAL_SIGNED(lseg=1e-3, ku=100.0, kr=0.238, nb=4.0, Bi=0.001, FARADAY=96500.0)
S.DERIVED_BUFFER("SA", "Vol")
S.DERIVATIVE(
"oc' = ku * cai * (1-oc) - kr * oc",
"cai' = (-ica * SA / Vol / (2*FARADAY) - nb * Bi * (ku * cai * (1 - oc) - kr * oc))",
)
def derive_buffers(self):
return {
"SA": math.pi * (1e-4) * self.diam * self.lseg,
"Vol": math.pi * ((1e-4) * (self.diam / 2)) ** 2 * self.lseg,
}
def state_defaults(self, v, values):
return {"oc": torch.full_like(v, 0.05)}
class caintscale(M):
M.STATE_BUNDLE(oc_cai)
M.USEION("ca", read=["ica"], write=["cai"])
How this works:
oc_caideclares private local state variablesocandcai.S.METHOD("bufferimplicit", bound="oc", free="cai")uses the specialized implicit calcium-buffer update, avoiding a generic Newton solve while preserving the free/bound conservation relation under the backward-Euler discretization.M.USEION("ca", read=["ica"], write=["cai"])tells Dendra that the mechanism uses the local calcium current to update intracellular calcium.The updated
caiis committed back to the shared population-wide calcium field, so other mechanisms and material processes can read it later in the timestep schedule.
Use USEION for ion-specific electrophysiology. Use USEMATERIAL when the shared variable is not an ion, or when you want generic material-style access to an ion-backed field.
MaterialProcess: population-field dynamics#
MaterialProcess is the process-level analogue of Mechanism for population-wide material fields. It is inserted like a mechanism, binds the shared material tensors, and is scheduled in the material phase. Processes may be global; spatial processes such as diffusion may also be restricted to selected compartments. This is the right place for spatial/global dynamics such as diffusion, clearance, bath clamping, or conservative exchange between stores.
Material processes use a strict full-field authoring contract:
GLOBAL(...),RANGE(...), andBATCH(...): declare process parameters.MaterialProcess.PHASE(...): choose where the process runs in the material scheduler.MaterialProcess.METHOD(method, **kwargs): choose process-specific numerical behavior.Family declarations such as
DIFFUSE(...),CLEAR(...),CLAMP(...), andEXCHANGE(...): name the Material fields the process operates on.
Dendra binds the shared fields and calls configure_process(population) after insertion, calls set_dt(dt) when timestep configuration changes, and calls advance_materials(dt) once per accepted step. Ordinary local-Mechanism state, current, USEION, USEMATERIAL, and workspace declarations are not part of this process lifecycle.
Current material phases are:
post_local local pointwise material processes; good for clearance/exchange
transport spatial transport; good for diffusion
post_transport clamps, bath conditions, bounds, and boundary constraints
The scheduler first commits local mechanism material writes/sources, then runs material processes by phase, and finally advances materials/ions to apply guarding and derived-field updates such as Nernst reversal potentials.
DiffusionProcess#
DiffusionProcess implements finite-volume material diffusion. The current implementation supports intracellular/cytosolic fields on unbranched 1D axons with analytic geometry, branched Tree morphologies with native material geometry, and explicit named chemical geometries on both unbranched and Tree populations (including intracellular, extracellular, or periaxonal domains).
Regional support and topology#
A process can be inserted globally or on any compartment subset. A restricted insertion uses the induced morphology graph: an edge transports material only when both endpoints belong to the process region. Edges crossing out of the region are sealed, disconnected selected components evolve as independent matrix blocks, and excluded field values remain exactly unchanged. The selected subset does not need to be connected.
Generic intracellular tracer diffusion:
from dendra.models.mechanisms import DiffusionProcess
class tracer_diffusion(DiffusionProcess):
DiffusionProcess.PHASE("transport")
DiffusionProcess.RANGE(Dtracer=0.5) # µm²/ms
DiffusionProcess.DIFFUSE("tracer", field="traceri", D="Dtracer")
DiffusionProcess.METHOD("implicit", solver="auto", boundary="sealed")
Then register the material and insert the process:
self.material(
"tracer",
fields={"traceri": 0.0},
min_values={"traceri": 0.0},
domain={"traceri": "intracellular"},
units={"traceri": "mM"},
conserved={"traceri": True},
)
self.insert(tracer_diffusion, Dtracer=0.5)
To constrain transport to a region, insert on a slice instead:
self.dendrites.insert(tracer_diffusion, Dtracer=0.5)
Repeated insertions of the same process class form one union domain. Adjacent selections therefore communicate even when they came from separate insertion calls, while disjoint selections remain independent. Overlapping diffusivity assignments must agree. Distinct diffusion-process classes may target disjoint regions, but cannot overlap when they write the same material field in the same phase because sequential implicit solves would be order-dependent.
Named chemical geometry and edge diffusivity#
For a chemical domain that does not use the model’s native geometry, register explicit finite-volume storage and edge geometry. This registry is independent of electrical extracellular layers: ExtCellAxon.xraxial, xc, and xg do not define a chemical extracellular volume or diffusion area. Quantities may be scalar or broadcastable tensors. Node quantities normally end in C. Unbranched edge quantities end in C - 1; Tree edge quantities end in compact dimension E and use tree.material_edge_index order.
The example assumes that k.ko already exists in the Material/Ion registry with extracellular domain metadata (normally because the model uses the k Ion), and that a Slice named periaxonal_region identifies the desired transport support. Every field’s effective domain must match the named geometry’s domain.
# This unbranched example uses (N, C) nodes and (N, C - 1) edges.
self.register_buffer("periaxonal_volume", volume_um3)
self.register_buffer("periaxonal_interface_area", area_um2)
self.register_buffer("periaxonal_interface_distance", distance_um)
self.register_buffer("edge_D", edge_diffusivity_um2_per_ms)
self.register_material_geometry(
"periaxonal",
domain="extracellular",
volume="periaxonal_volume",
edge_area="periaxonal_interface_area",
edge_distance="periaxonal_interface_distance",
)
class periaxonal_k_transport(DiffusionProcess):
DiffusionProcess.RANGE(bath_rate=0.0)
DiffusionProcess.GLOBAL(bath_target=5.0)
DiffusionProcess.DIFFUSE(
"k", field="ko", D="edge_D", domain="extracellular",
geometry="periaxonal", D_location="edge",
)
DiffusionProcess.RELAX(
"k", field="ko", rate="bath_rate", target="bath_target",
where="all",
)
DiffusionProcess.METHOD("implicit")
# bath_rate_on_region is node-aligned on this Slice and is nonzero only
# where exchange with the fixed bath should occur.
self.periaxonal_region.insert(
periaxonal_k_transport, bath_rate=bath_rate_on_region,
)
For a Tree, the morphology still owns adjacency while named geometry supplies chemical storage and weights. Tree edge tensors use a compact, stable E axis rather than a root-padded C axis:
parent, child = tree.material_edges
edge_index = tree.material_edge_index # shape (2, E)
# edge_factor[e] and edge_D[e] describe parent[e] -> child[e].
tree.register_buffer("ecs_volume", volume_um3) # (..., C)
tree.register_buffer("ecs_edge_factor", factor_um) # (..., E)
tree.register_buffer("ecs_edge_D", edge_D) # (..., E)
tree.register_material_geometry(
"ecs_tree", domain="extracellular",
volume="ecs_volume", edge_factor="ecs_edge_factor",
)
class tree_ecs_transport(DiffusionProcess):
DiffusionProcess.DIFFUSE(
"k", field="ko", D="ecs_edge_D",
domain="extracellular", geometry="ecs_tree",
D_location="edge",
)
DiffusionProcess.METHOD("implicit")
Tree edge order is increasing child storage index with the morphology root omitted. Named geometry can set an existing edge factor or diffusivity to zero to seal that edge, but it cannot add an edge. Regional selection remains exact: omitting an intervening junction seals its incident crossing edges rather than silently adding the junction to the process region.
volume is in µm³, edge_area in µm², edge_distance in µm, and the equivalent precomputed edge_factor = edge_area / edge_distance in µm. Edge conductance is D_edge * edge_factor in µm³/ms. With named geometry and the default D_location="node", D is scalar or node-aligned and the interface value is the arithmetic endpoint mean 0.5 * (D_i + D_j). Named geometry rejects interface_scheme="series" because its area/distance edge factor does not contain the two half-compartment resistances.
With D_location="edge", D is scalar or interface-aligned; a string such as "edge_D" can name a registered Population edge buffer or parameter. Edge-located D requires named explicit geometry and is available on unbranched and Tree populations, but not with analytic cylindrical 1D or native Tree geometry. A node-aligned RANGE parameter is not an edge array. Process-local parameter/buffer names take precedence over Population names.
String geometry components and Population coefficient names must refer to registered buffers or parameters. They therefore follow dtype/device moves and state dictionaries. Differentiable sources preserve autograd. Direct ordinary tensor-like geometry arguments are registered as Population buffers automatically, while a direct nn.Parameter is registered as a Population parameter and is discoverable through model.parameters().
Geometry, D, and RELAX rate/target/where values are sampled when the spatial operator is configured—normally on the first step after initialization or after explicit timestep reconfiguration—not read anew on every timestep. Mutating one during a run requires reconfiguring before it takes effect; this declaration API does not represent a continuously time-varying bath coefficient.
On active process support, unbranched volumes must be finite and positive. Implicit Tree diffusion permits finite zero-volume algebraic junctions when every conductive component reaches at least one positive-volume node; explicit Tree diffusion requires all active volumes to be positive. Interface area/factor and D must be finite and non-negative, and explicit edge distance finite and positive. A zero edge factor or zero edge D seals that interface. Validation that depends on the selected region occurs when the process binds or its operator is configured.
A process class can diffuse several fields through one named geometry. If any DIFFUSE declaration names a geometry, every DIFFUSE declaration in that class must name that same geometry; named and unnamed declarations cannot be mixed. On a Tree, named geometry replaces chemical volumes and edge weights but retains morphology adjacency. It may seal existing edges, but cannot add connections or define a chemically distinct graph.
Fused reservoir or bath coupling#
RELAX (alias BATH) contributes -rate * (c - target) directly to the same backward-Euler system as diffusion. If M is finite-volume storage, L is the diffusion Laplacian, Lambda is the effective relaxation rate, and c_source is the field after committed local Mechanism writes/sources, Dendra solves
(M + dt*L + dt*M*Lambda) c_new
= M*c_source + dt*M*Lambda*c_bath
Diffusion and bath exchange are therefore not split from one another, and stiff non-negative bath rates remain stable. RELAX is implicit-only and must target a field declared by DIFFUSE in the same class. To model bath coupling without longitudinal diffusion, declare DIFFUSE(..., D=0) and add RELAX(...). Multiple RELAX declarations for one field add their matrix contributions.
The effective relaxation support is
process insertion region ∩ where mask ∩ compartments with nonzero rate
where="all" (the default) or where=None means no additional mask. It never bypasses 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 can further restrict coupling. Process-local names take precedence. No other string is special: ClampProcess selectors such as "terminal", "root", or "soma" are treated as quantity names here, not topology selectors.
Setting a node-aligned rate to zero is often the simplest independent bath mask. In the example above, a regional process with where="all" still excludes every compartment outside that region, and only nodes with bath_rate != 0 exchange with the bath. rate is in ms⁻¹ and must be finite and non-negative on effective support; target has the field’s units and must be finite wherever the rate is nonzero.
RELAX couples the modeled field to a fixed/infinite reservoir and therefore does not conserve mass inside the modeled domain. Use ExchangeProcess instead when the second reservoir is finite, explicitly modeled, and total mass must be conserved.
Material scheduling is: accepted local current/material sources → transport processes such as this fused solve → Material/Ion guards and derived-field refresh (including enabled Nernst updates).
Intracellular Ca²⁺ diffusion through the ion-as-material bridge:
class cai_diffusion(DiffusionProcess):
DiffusionProcess.PHASE("transport")
DiffusionProcess.RANGE(Dca=0.6) # µm²/ms
DiffusionProcess.DIFFUSE("ca", field="cai", D="Dca")
DiffusionProcess.METHOD("implicit", solver="auto", boundary="sealed")
This updates the same population-wide cai field used by USEION("ca", ...) mechanisms. Local calcium mechanisms can update cai, diffusion spreads the committed field, and then the calcium ion object can update/guard cai and recompute eca if appropriate.
Solver and geometry notes:
METHOD("implicit")uses finite-volume backward Euler and is the recommended default for diffusion.solver="auto"selects the appropriate spatial backend when available.For Dendra’s unbranched 1D
Axonclasses, diffusion uses analytic compartment volume and 1D tridiagonal/Thomas-style solves.Named unbranched and Tree chemical geometries use explicit control volumes and either
edge_factororedge_area / edge_distance. They accept the arithmetic interface scheme; useD_location="edge"when the desired interface coefficient is already known.RELAX(...)is implicit-only. Explicit diffusion remains available when no RELAX declaration is present. Tree RELAX uses the volume selected by the diffusion operator—native for unnamed diffusion and custom for named geometry.Analytic 1D diffusion uses the legacy arithmetic endpoint interface by default. Pass
interface_scheme="series"toMETHOD(...)to combine the two half-compartment diffusion resistances in series. The latter is useful for NEURON RxD parity across sharp diameter or length changes. Tree diffusion already consumes precomputed edge geometry and does not accept this 1D-only option.For
Treemorphologies imported through NEURON, diffusion uses tree/DHS-style topology when material geometry buffers such asvolume_ianddiff_geom_umare available.Diffusion coefficients
Dare finite, non-negative effective diffusivities in µm²/ms on active interfaces; they are not automatically temperature-scaled unless a process explicitly implements such scaling.Axon and Tree finite-volume geometry uses compartment volumes in µm³. Diffusion preserves the volume-weighted field total under sealed boundaries (up to solver/floating-point error); the field’s
conserved=Truemetadata documents this intent but does not activate a different algorithm.
ClearanceProcess#
ClearanceProcess applies pointwise first-order relaxation/degradation:
c' = -rate * (c - target)
The default method is the exact exponential update for fixed rate and target over the timestep. rate is in ms⁻¹, while target has the same units as c.
from dendra.models.mechanisms import ClearanceProcess
class ip3_clearance(ClearanceProcess):
ClearanceProcess.PHASE("post_local")
ClearanceProcess.RANGE(kclear=0.01) # ms⁻¹
ClearanceProcess.CLEAR("ip3", field="ip3i", rate="kclear", target=0.0)
ClearanceProcess.METHOD("exact")
Useful aliases include:
ClearanceProcess.CLEAR(...)
ClearanceProcess.DECAY(...)
ClearanceProcess.RELAX(...)
Use clearance for IP3/cAMP degradation, extracellular uptake, recovery to baseline, bath relaxation, or slow homeostatic removal.
ClampProcess#
ClampProcess imposes algebraic constraints on full material fields. It is useful for bath conditions, boundary conditions, fixed experimental fields, and safety bounds. It defaults to the post_transport phase, so by default it runs after diffusion/transport.
Hard clamp all extracellular potassium to a bath value:
from dendra.models.mechanisms import ClampProcess
class ko_bath_clamp(ClampProcess):
ClampProcess.RANGE(ko_bath=5.4)
ClampProcess.CLAMP("k", field="ko", value="ko_bath", where="all")
Clamp only terminal/boundary compartments:
class terminal_ko_bath(ClampProcess):
ClampProcess.RANGE(ko_bath=5.4)
ClampProcess.CLAMP("k", field="ko", value="ko_bath", where="terminal")
Bounds and positivity constraints:
class ip3_nonnegative(ClampProcess):
ClampProcess.MIN("ip3", field="ip3i", value=0.0)
class ip3_bounds(ClampProcess):
ClampProcess.RANGE(ip3_max=10.0)
ClampProcess.BOUNDS("ip3", field="ip3i", lower=0.0, upper="ip3_max")
Supported MVP locations include "all", "terminal" / "boundary", "root" / "soma", boolean masks, and explicit index/slice-like selectors.
ExchangeProcess#
ExchangeProcess implements conservative pointwise exchange between two material fields:
V_a * a' = -g * (a - b)
V_b * b' = g * (a - b)
It preserves V_a*a + V_b*b up to floating-point roundoff when both pools have positive volume/mass. The two fields must use the same units because the process evaluates a - b. The default method is the exact closed-form update for fixed exchange coefficient and volumes over the timestep.
Example: cytosol ↔ ER-like calcium store exchange:
from dendra.models.mechanisms import ExchangeProcess
class ca_er_exchange(ExchangeProcess):
ExchangeProcess.RANGE(k_er=1e-3, Ver=0.1) # k_er: ms⁻¹; Ver: µm³
ExchangeProcess.EXCHANGE(
("ca", "cai"),
("er_ca", "caer"),
rate="k_er",
volume_a="intracellular",
volume_b="Ver",
)
ExchangeProcess.METHOD("exact")
Register the store material before insertion:
self.material(
"er_ca",
fields={"caer": 0.2},
min_values={"caer": 0.0},
domain={"caer": "intracellular"},
units={"caer": "mM"},
conserved={"caer": True},
)
self.insert(ca_er_exchange, k_er=1e-3, Ver=0.1)
You can specify either rate=... or conductance=...:
ratehas units ms⁻¹; Dendra converts it to an exchange conductance withg = rate * volume_a.conductanceis used directly and must have units of the chosen volume/mass weight per ms (µm³/ms when using inferred volumetric geometry).Inferred intracellular/extracellular volume weights are in µm³; inferred membrane/surface weights are in µm². Explicit scalar/tensor weights must follow one compatible convention for both pools. Setting material metadata
conserved=Truerecords intent but does not alter these equations.
Useful aliases include:
ExchangeProcess.EXCHANGE(...)
ExchangeProcess.COUPLE(...)
ExchangeProcess.TRANSFER(...)
Choosing between State, Ion, Material, and MaterialProcess#
Use State variables when one mechanism owns the local dynamics. Examples: HH gates, Markov states, private kinetic intermediates. A consumer in the same Population can read a declared tensor through an explicit State.INPUT binding; this does not turn that tensor into a shared writable field.
Use USEION when the mechanism participates in electrophysiological ion handling: reading ena/ek/eca, reading ion concentrations, writing ionic currents such as ina, or locally updating ion concentrations such as cai.
Use USEMATERIAL when the mechanism needs to share a generic chemical/biochemical field with other mechanisms. Examples: IP3, ATP, cAMP, PIP2, pH/protons, mobile buffers, ligand concentration, extracellular transmitter, or ion-backed concentration fields used as generic shared state.
Use MaterialProcess when the dynamics are naturally full-field or spatial/global rather than private to one local mechanism.
Current concrete process families:
DiffusionProcess: finite-volume spatial diffusion of material fields. Use for intracellular Ca²⁺ diffusion, IP3 diffusion, mobile-buffer diffusion, etc.ClearanceProcess: first-order degradation, uptake, or relaxation to a target. Use for IP3/cAMP degradation, extracellular clearance, or recovery to baseline.ClampProcess: algebraic bath conditions, boundary clamps, or safety bounds. Use for fixed extracellular bath values, terminal boundary conditions, or nonnegative concentration constraints.ExchangeProcess: conservative exchange between two full material fields. Use for cytosol ↔ store exchange, mobile ↔ immobile pools, or finite reservoir exchange.
A compact mental model is:
Mechanisms are local operators.
States are private local memory.
Materials are shared population-wide fields.
MaterialProcesses are spatial/global operators on shared fields.
Ions are specialized Materials with electrophysiological semantics.
For coupled material models, compose local mechanisms and material processes through explicit shared fields rather than by directly reaching into another mechanism’s private buffers.
Example material-process composition#
The material interface is most useful when several mechanisms and processes share one field. For example, a calcium model might combine:
class caintscale(M):
M.STATE_BUNDLE(oc_cai) # local buffer/reaction dynamics
M.USEION("ca", read=["ica"], write=["cai"])
class cai_diffusion(DiffusionProcess):
DiffusionProcess.PHASE("transport")
DiffusionProcess.RANGE(Dca=0.6) # µm²/ms
DiffusionProcess.DIFFUSE("ca", field="cai", D="Dca")
DiffusionProcess.METHOD("implicit")
class cai_minimum(ClampProcess):
ClampProcess.MIN("ca", field="cai", value=1e-12)
The local mechanism updates cai from calcium current and buffering, diffusion spreads the committed cai field, and the clamp enforces a final lower bound. Other mechanisms can read the same cai field with either USEION("ca", read=["cai"]) or USEMATERIAL("ca", read=["cai"]), depending on whether they need ion-specific electrophysiology or generic material-style access.