03. Networks#
In the previous notebooks, we have focused on single neuron models. However, one of the main strengths of Dendra is its ability to efficiently simulate large networks of neurons with complex morphologies. In this notebook, we will explore how to set up and simulate networks of branched morphologies using Dendra.
General overview: event-based networks#
Dendra networks can be event-driven: a pre-synaptic event (e.g., a voltage or gate crossing a threshold, a mechanism-generated spike gate, or a
NetStimevent) triggers a message to its post-synaptic targets.An event-based connection delivers a weighted event to its target synapse after the configured delay.
A connection target can be either:
a physical
Slice, when the synapse mechanism is unique at that location, oran explicit
SynapseSlotsselection, when multiple point-process slots live on the same physical compartment.
The last distinction is important for large networks: colocated point-process synapses can be represented as one vectorized mechanism with many independent local slots rather than many small mechanism objects.
Connection weights inherit their units from the target mechanism. The built-in point-process expsyn and exp2syn mechanisms add weights to conductance state, so their weights are bare numerical values in µS and their current methods return nA before area normalization. For these targets, weight=0.1 means 0.1 µS; do not multiply it by dendra.units.uS.
Example: Ring Network of Branched Neurons#
Build a ring of five branched neurons using the morphology from the previous notebook. Each neuron has two neighbors in the ring. It receives events from one neighbor and sends them to the other, so events travel in one direction.
This example uses L23_PC_cADpyr229_1.asc, a Blue Brain Project L2/3 pyramidal morphology (Copyright © 2015 EPFL-BBP), from the Blue Brain cell package, described by Markram et al. (2015). The morphology is licensed under CC BY-NC-SA 4.0; see License for source and license notices.
import dendra as dn
from dendra.models.mod import hh
model = dn.Tree.from_asc(
"L23_PC_cADpyr229_1.asc",
v_init=-65.0,
celsius=6.3,
rhoa=100.0,
N=5
) # Load morphology from file, set initial voltage and temperature, create 5 instances
model.insert(hh) # Insert Hodgkin-Huxley dynamics into all compartments
Now lets insert synapses and connect the neurons in a ring topology.
from dendra.models.mod import exp2syn
model.soma.insert(exp2syn, tau1=0.2, tau2=1.0) # Insert an exponential synapse at the soma of each neuron
net = dn.Network({"hh": model})
# Create a network with the branched morphology model. The population is named "hh".
Now we connect in a ring topology.
import torch
net.connect_one_to_one(
net.hh.soma,
net.hh.soma[torch.roll(torch.arange(5), shifts=-1)],
net.hh.mech.exp2syn,
threshold=0.0,
weight=0.1, # µS for exp2syn
delay=5.0,
)
Important
A Slice supports PyTorch indexing. Here torch.roll orders the target somas as [1, 2, 3, 4, 0]. The one-to-one rule pairs each source soma with the next target soma and connects the last back to the first.
Note
We use a double exponential synapse model (exp2syn) for the synaptic connections, with rising and falling time constants \(\tau_1\) and \(\tau_2\), respectively, that we have set explicitly (the defaults are 0.1 ms and 10.0 ms). You can explore other synaptic models available in Dendra or follow Writing your own synapse to implement your own event-driven or continuous synapse.
Note
We set the synaptic weight to 0.1 µS and the delay to 5.0 ms. You can adjust these parameters to see how they affect the network dynamics.
We can now stimulate and run. Because the first-neuron index and the somatic compartment label restrict independent axes, Dendra validates that net.hh[0].soma and net.hh.soma[0] are the same retained selection. Label propagation is accepted only when the two restrictions commute exactly; ambiguous cross-axis combinations raise instead of being silently reinterpreted. Use the explicit intersect() method when physical overlap, rather than shape-preserving label propagation, is the intended operation:
from dendra.units import nA, ms
net.hh.delete_injections()
stim = dn.mono_rect(amp=2.0 * nA, pw=0.5 * ms, delay=1.0 * ms)
net.hh[0].soma.inject(stim)
# equivalently: net.hh.soma[0].inject(...)
rec = dn.callbacks.RecorderLambda(
{"somas": lambda net: net.hh.soma.v}
)
tstop, dt = 40.0 * ms, 0.025 * ms
rec.reset()
net.initialize(dt=dt)
net.run(tstop=tstop, callbacks=[rec])
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6), dpi=300)
t = torch.arange(0, tstop+dt, dt)
soma_voltages = rec.numpy('somas')
for i in range(5):
plt.plot(t, soma_voltages[:, i], linewidth=3, label=f'Neuron {i}')
plt.xlabel('Time (ms)')
plt.ylabel('Voltage (mV)')
plt.title('Soma Voltages of Neurons')
plt.legend()
plt.show()
Connection rules#
The ring network above used connect_one_to_one(), which is a convenient wrapper around the more general connect() API. For larger models, it is often clearer to use connect(...) with an explicit conn_spec dictionary. This makes the wiring rule, autapse policy, and multapse policy visible at the call site.
The general form is:
net.connect(
source,
target,
synapse,
conn_spec={"rule": "all_to_all"},
threshold=0.0,
weight=1.0,
delay=0.0,
pre_var=None,
allow_autapses=True,
allow_multapses=True,
)
For source, use a Population, a physical or mechanism slice, a NetStim, or a NetStim slice. For target, choose a Population, a physical slice, or a SynapseSlots selection. Dendra pairs the selected sources and targets using the connection rule, then applies the autapse and multapse options.
Available event-connection rules#
one_to_onePair source and target selections by position. The selections must contain the same number of elements.
net.connect(pre[:N], post[:N], syn, conn_spec={"rule": "one_to_one"}) # equivalent wrapper: net.connect_one_to_one(pre[:N], post[:N], syn)
all_to_allordenseCreate the Cartesian product of the selected sources and targets.
net.connect(pre, post, syn, conn_spec={"rule": "all_to_all"}) # equivalent wrapper: net.connect_dense(pre, post, syn)
pairwise_bernoulliorbernoulliVisit each candidate source-target pair once and keep it independently with probability
p.net.connect(pre, post, syn, conn_spec={"rule": "pairwise_bernoulli", "p": 0.1}) # equivalent wrapper: net.connect_prob(pre, post, syn, prob=0.1, strategy="bernoulli")
pairwise_poissonFor each candidate source-target pair, draw the number of parallel connections from a Poisson distribution with mean
pairwise_avg_num_conns. Because this rule can create multiple edges between the same pair,allow_multapses=Trueis required.net.connect( pre, post, syn, conn_spec={"rule": "pairwise_poisson", "pairwise_avg_num_conns": 0.2}, allow_multapses=True, )
fixed_total_numberorfixed_totalDraw exactly
Nconnections from the candidate edge set. Withallow_multapses=True, edges are sampled with replacement; withallow_multapses=False, sampled source-target pairs are unique.net.connect(pre, post, syn, conn_spec={"rule": "fixed_total_number", "N": 500}) # equivalent wrapper: net.connect_prob_n(pre, post, syn, n=500)
fixed_indegreeFor each selected target, draw exactly
indegreepresynaptic sources.net.connect(pre, post, syn, conn_spec={"rule": "fixed_indegree", "indegree": 20})fixed_outdegreeFor each selected source, draw exactly
outdegreepostsynaptic targets.net.connect(pre, post, syn, conn_spec={"rule": "fixed_outdegree", "outdegree": 20})
Autapses, multapses, and per-edge values#
An autapse is a self-connection. A multapse is a repeated connection between the same source-target pair. For the general connect(...) entry point, allow_autapses and allow_multapses default to True; the legacy convenience wrappers such as connect_one_to_one(...), connect_dense(...), and connect_prob(...) default to False to preserve their older behavior.
This distinction matters when you pass per-edge tensors for threshold, weight, or delay. Those tensors must match the final number of edges after autapse and multapse filtering. If you construct a delay vector from candidate (pre_idx, post_idx) arrays and then call a wrapper that removes duplicate pairs, the delay vector can be longer than the final connection list.
A safe pattern is to either use scalar values:
net.connect(pre, post, syn, conn_spec={"rule": "pairwise_bernoulli", "p": 0.1}, weight=0.05, delay=2.0)
or explicitly keep duplicates when you intentionally created per-edge arrays:
net.connect_one_to_one(
pre[pre_idx],
post[post_idx],
syn,
weight=edge_weight,
delay=edge_delay,
allow_multapses=True,
)
When you want unique pairs, filter pre_idx, post_idx, and every per-edge tensor together before calling connect(...).
Continuous connections use the same rule machinery#
The same conn_spec rules are available for continuous projections through connect_continuous(). Continuous connections do not perform event thresholding; they sample a presynaptic variable every step, apply optional weight/delay/transform logic, and deliver it to a continuous synapse input.
net.connect_continuous(
source=pre,
target=post,
synapse=continuous_syn,
conn_spec={"rule": "fixed_indegree", "indegree": 8},
pre_var="v",
input="exc",
weight=0.1,
delay=1.0,
)
Use event-based connect(...) when presynaptic activity should be converted into discrete deliveries. Use connect_continuous(...) when the postsynaptic mechanism needs a continuously sampled presynaptic state, such as voltage, calcium, or another analog variable. An example of continuous synaptic machinery is implemented in dendra.models.mod.GRADED_SYNAPSE, which dynamically solves a presynaptic gating value and produces a continuous synaptic conductance without discrete events.
Banked point-process synapses and explicit slots#
A regular slice identifies physical compartments. That is sufficient when there is only one target synapse at each selected compartment. For colocated point-process banks, however, several independent synapses can live at the same physical location. In that case, target the mechanism’s local slots explicitly.
from dendra.models.mod import exp2syn
# Allocate 30 independent synaptic slots at soma compartments.
# The physical target may contain repeated compartment indices, but each slot
# has its own local synaptic state and scatters current back to the same cell.
post.soma.insert(exp2syn, alias="exc", tau1=0.2, tau2=2.0, copies=30)
slots = post.soma.slots(post.mech.exc)
print(slots.local_index.shape) # 30 local point-process slots
print(slots.flat_index.shape) # physical compartment index for each slot
The usual insertion path collapses duplicate physical compartments, which is what you want for distributed channels. Use copies=... or preserve_duplicate_indices=True only when repeated local state is intentional, such as independent AMPA/NMDA/GABA receptor contacts.
Connecting to slots#
Once you have a slot selection, use either the explicit slot API:
net.connect_one_to_one_slots(
pre_selection,
post.soma.slots(post.mech.exc, local_index=torch.arange(30)),
threshold=0.0,
weight=0.05,
delay=1.0,
)
or pass the SynapseSlots object as the target to the generic connection methods:
net.connect_one_to_one(
pre_selection,
post.soma.slots(post.mech.exc, local_index=[0, 1, 2]),
threshold=0.0,
weight=[0.05, 0.05, 0.05],
delay=1.0,
)
If a mechanism has several local slots on the same physical compartment, connecting to the physical slice is ambiguous and Dendra will ask you to select slots explicitly. This avoids silently choosing the wrong point-process target.
Attaching a NetStim after network construction#
You can construct a purely cellular network first and attach artificial sources later:
net = dn.Network({"cells": cells})
# Later, when you want prescribed events:
ns = dn.NetStim(N=100)
net.attach_netstim(ns)
net.connect_one_to_one(
net.netstim[:],
cells.soma.slots(cells.mech.exc, local_index=torch.arange(100)),
threshold=None,
weight=0.05,
delay=1.0,
)
Adding a NetStim, replacing a NetStim, or adding new connections invalidates materialized NetCons. Call net.initialize(dt) again before the next run(...) so the connection queues are rebuilt.
Awesome! We have successfully set up and simulated a ring network of branched neurons using Dendra. We can see that with a single initial pulse delivered to the first neuron, the activity propagates through the network in a ring topology, eventually returning to the first neuron and continuing the cycle. We encourage you to further explore different network topologies (perhaps try connecting axonal compartments to dendritic compartments?), synaptic models, and stimulation protocols to study various aspects of neural network dynamics. The same ideas scale to richer graph topologies using the connection rules described above, while still preserving Dendra’s explicit source/target indexing model.