00. Dendra Overview#
In this tutorial, we provide a brief overview of Dendra. We will cover the following topics:
Setting up a neuronal model
Accessing and viewing model properties
Running simulations
Advancing simulations one timestep at a time
Analyzing simulation results
What is Dendra?#
Dendra is a Python library designed for simulating and analyzing neuronal models. It provides a flexible framework for building complex neuronal populations and networks, allowing researchers to explore the dynamics of neural systems.
What are “neuronal models”, conceptually?#
Neuronal models are mathematical representations of neurons, their responses to intra- and extracellular stimulation, and their interactions within a network. They can range from simple point neuron models to complex multi-compartmental models that capture the detailed morphology and biophysics of real neurons. Neuronal models are used to study various aspects of neural function, including the behavior of cellular substrates in neural interfaces, signal propagation, synaptic integration, and network dynamics.
In Dendra, the core abstraction is the Population, which represents a group of neurons with shared properties. Each Population can contain multiple compartments, each with its own biophysical properties and dynamics.
Fundamentally, a Population in Dendra is an array of compartments. These compartments may be connected topologically to form neurons, but the Population itself is agnostic to this structure. Each compartment can have its own set of properties, such as membrane potential, ion channel densities, and synaptic inputs. When the compartments of a Population are connected (there exist finite-impedance current paths between them), a row of the Population corresponds to a single neuron, and a column corresponds to a compartment within that neuron. When compartments are not connected, each compartment can be treated as an independent point neuron.
Dendra implements a number of abstractions on top of Population to facilitate working with neuronal models:
Population– generic multicompartment neuron population (Nneurons ×Ccompartments)SingleCompartment(Population) – single‑compartment (point‑neuron) population (N×Ctotal neurons)Cable(Population) – generic unbranched native morphologies with exact compiled geometry and the 1D solver fast pathAxon(Cable) – diameter‑parameterized axonal fiber familyUnmyelinated(Axon) – unmyelinated axons with uniform spatial discretizationMyelinated(Axon) – myelinated axons with nodes of Ranvier and diameter‑scaled internodesExtCellAxon(Axon) – axons with two‑layer extracellular coupling (e.g., realistic myelin)
Tree(Population) – branched, tree‑shaped neuron morphologies (soma, axon, dendrites, apical dendrites)ExtCellTree(Tree) – tree‑shaped neurons with two‑layer extracellular coupling
Cable is the geometry-general unbranched model: it consumes a native Morphology or CompartmentGraph, including tapered pt3d geometry, while retaining the tridiagonal cable solver. Axon specializes that path representation for the established diameter-parameterized axon constructors; branched native morphologies use Tree.
Each of these abstractions builds upon the Population class, adding specific features and behaviors relevant to the type of neuronal model being represented. This hierarchical structure allows users to easily create and manipulate different types of neuronal models while leveraging the common functionality provided by the Population base class. Users can create their own custom models by using and subclassing these core abstractions, in particular SingleCompartment, Cable, Unmyelinated, Myelinated, ExtCellAxon, Tree, and ExtCellTree, which are designed to be flexible and extensible (highlighted in blue below).
from dendra_hierarchy_utils import render
render()
Setting Up a Neuronal Model#
To set up a neuronal model in Dendra, you typically start by creating an instance of a Population or one of its subclasses. You then define its biophysical properties. Let’s look at an example of creating a simple unmyelinated axon model:
import dendra as dn
from dendra.units import um, mm
axon = dn.Unmyelinated(diameters=[1.0 * um], dx=10.0 * um, L=2.0 * mm, v_init=-65.0, celsius=6.3)
This defines an unmyelinated axon with a uniform diameter of 1 micrometer (note how diameters is a list length 1, if we had supplied multiple diameters we have multiple axons), compartment length of 10 micrometers, total length 2.0 millimeters, an initial membrane potential of -65 mV, and a temperature of 6.3 degrees Celsius. For unmyelinated axon models, Dendra will round up the number of compartments to ensure an odd number, which ensures an unambiguous central compartment for stimulation. By default, axons lie along the x-axis, with the central compartment at x=0.
print(axon.L, axon.nc, axon.x[0, int(axon.nc // 2)], axon.x[0, 0], axon.x[0, -1])
2010.0 201 tensor(0.) tensor(-1000.) tensor(1000.)
This model doesn’t do much yet, as we haven’t defined any channel biophysics. Let’s make it a simple Hodgkin-Huxley axon by adding the standard sodium, potassium, and leak channels:
from dendra.models.mod import hh
axon.insert(hh)
This inserts the Hodgkin-Huxley channel model into all compartments of the axon, enabling it to exhibit action potential dynamics when stimulated. At this point, we haven’t yet built the model, only defined its structure and biophysics.
Important
Before initializing the model, you can move it to a CPU with .to("cpu"), a GPU with .to("cuda"), or Apple Silicon with .to(device="mps", dtype=torch.float32). See Hardware support for tested configurations and solver requirements.
In the next sections, we will explore how to run simulations and analyze the results. First, we initialize the model to prepare it for simulation:
axon = axon.initialize()
The model is now initialized and ready for simulation. All state variables have been set to their initial conditions based on the defined biophysics. To help us verify that our model is set up correctly, let’s inspect some of its properties. For this, it is helpful to introduce the concept of a Slice, which is a central abstraction in Dendra for accessing and manipulating subsets of a Population.
Slices#
A Slice in Dendra is a retained logical selection of a Population. It allows you to select particular neurons and compartments while the population continues to own the numerical state. Reading through a Slice returns a snapshot; explicit Slice assignment updates the selected model state. Slices can be created using standard PyTorch indexing syntax:
The complete indexing, mutation, labeling, batching, and rebuild semantics are specified in the The Slice contract contract.
# view the membrane potential of compartments 2 to 4 in the first (and only) axon
print(axon[0, 2:5].v)
# view the sodium channel activation variable 'm' in the central compartment of the first axon
print(axon[0, axon.nc // 2].mech.hh.m)
tensor([-65., -65., -65.])
tensor(0.0529)
Slices can also be labeled and accessed by name, which can make code more readable when working with complex models. For example, you might label the central compartment of an axon as “node” and access it using that label:
axon[0, axon.nc // 2].label("node")
print(axon.node.mech.hh.m)
tensor(0.0529)
For more complex morphologies (such as Tree populations), Dendra implements various quality-of-life features to facilitate working with compartments by name, such as automatic labeling of standard structures (e.g., “soma”, “axon”, “dendrite”, “apical”) and convenient access to commonly used subsets (e.g., all dendritic compartments), which we will explore in later tutorials.
Running a simulation#
This model is ready to be simulated, but it is not very interesting yet since we have not applied any stimulation. Dendra allows us to apply intracellular current injetion to specific compartments using the same Slice abstraction we used to access model properties. For example, we can inject a 1 nA current pulse into the terminal compartment of the first axon for 0.1 ms starting at t=0.1 ms:
from dendra.units import nA, ms
stim = dn.mono_rect(amp=1.0 * nA, pw=0.1 * ms, delay=0.1 * ms)
axon[0, 0].inject(stim)
In the above, dn.mono_rect is an example of a Waveform object that defines a simple rectangular current pulse. Dendra provides various built-in waveform types, and users can also define custom waveforms as needed (see the “dendra.models.stim” API documentation for more details). Ok, now we are ready to run the simulation! First though, we need to set up some recording to capture the results. Let’s record the membrane potential at the center, 75% along, and terminal compartments of the axon:
from dendra.models.callbacks import Recorder
rec = Recorder(['v'], node_indices=axon.c(0.5, 0.75, 1.0))
Now lets run and record!
rec.reset()
axon.initialize(force_rebuild=True)
axon.run(tstop=25.0 * ms, dt=0.01 * ms, callbacks=[rec])
vm_rec = rec.numpy('v')
print(vm_rec.shape) # (num_timepoints, num_neurons, num_recorded_compartments)
(2501, 1, 3)
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0, 25.0+0.01, 0.01)
plt.plot(t, vm_rec[:, 0, 0], label='Center')
plt.plot(t, vm_rec[:, 0, 1], label='75% along')
plt.plot(t, vm_rec[:, 0, 2], label='Terminal')
plt.xlabel('Time (ms)')
plt.ylabel('Membrane potential (mV)')
plt.legend()
plt.show()
Advancing one timestep at a time#
For most simulations, run(...) is the simplest and fastest interface because Dendra owns the entire time loop. Sometimes an application needs to inspect the model, change an input, exchange data with another simulator, or stop conditionally after every timestep. The dn.step helper supports these user-controlled loops by advancing either a population or a network exactly once.
A population must be initialized before stepping. Pass its timestep through dt; after each call, the model state and axon.t have both advanced by that amount:
axon.initialize(force_rebuild=True)
dt = 0.01 * ms
for _ in range(10):
dn.step(axon, dt=dt)
print(f'Simulation time: {axon.t.item():.2f} ms')
Simulation time: 0.10 ms
The injected waveform configured above is applied automatically at the model’s current time. Extracellular input can likewise be supplied in either of the forms accepted by run(...): use ve= for a precomputed voltage for this one step, or extra= for a spatial field and waveform that Dendra evaluates at the current time. Do not pass both ve and extra.
Native Cable models safely validate compiled geometry and cached solver inputs by default. Advanced users tuning a trusted stepping loop can review the available policies and lifecycle rules in Diagnose model and performance problems.
Callbacks passed to dn.step(...) run their pre_step_hook and post_step_hook on every call. Loop-level hooks are omitted by default so they are not repeatedly initialized and finalized inside a manual loop. If a callback needs them, call its pre_loop_hook once before the loop and its post_loop_hook once afterward. For a single standalone step, loop_hooks=True runs both loop-level hooks around that call.
Networks use the same helper, but their timestep is fixed when the network is initialized. Initialize with net.initialize(dt), then call dn.step(net) without a new dt. Dendra advances all populations, connections, event queues, and the network clock in the same phase order as net.run(...). The equivalent instance methods, axon.step(...) and net.step(...), are also available.
Tip
Use run(...) or longrun(...) when Dendra can own the time loop. Use dn.step(...) when your application needs control between timesteps.
Awesome! We have successfully run a simulation of our unmyelinated axon model with intracellular current injection and recorded the membrane potential at specified compartments. In the next tutorial, we will look at extracellular stimulation and recording.