01a. Extracellular stimulation and recording#

In this tutorial, we will explore how to use Dendra to simulate extracellular stimulation and recording in neuronal models. We will cover the following topics:

  • Computing extracellular stimulation potentials

  • Applying extracellular stimulation to neuronal populations

  • Recording extracellular potentials from neuronal populations

General principles#

Dendra treats extracellular stimulation and recording in terms of the extracellular potential experienced by each model compartment. Conceptually, you should think of there being a value \(\phi_e(x_i, t_n)\) for every compartment \(x_i\) and every timestep \(t_n\).

The stimulation machinery in Dendra is essentially about specifying and evaluating this field \(\phi_e(x, t)\) over space and time, then feeding those values into the cable equations.

For ordinary Population, Axon, and Tree models, this supplied field is the extracellular potential immediately outside the membrane. Myelinated is a deliberately simplified node-only model whose internodes are treated as fully insulating; it is not a finite double-cable circuit. Use ExtCellAxon or ExtCellTree when the two extracellular/myelin layers themselves must be solved. These models follow NEURON’s extracellular convention: extra/ve supplies the bath battery outside the outermost layer (e_extracellular), the solved nodes are vc[..., 0] = vi, vc[..., 1] = vext[0], and vc[..., 2] = vext[1], and membrane voltage is v = vi - vext[0]. Layer parameters use NEURON’s units: xraxial in MΩ/cm, xc in µF/cm², and xg in S/cm².

Quasistatic fields and separation of space and time#

In typical neural-interface settings, energy content of electrode currents are relatively low frequency (up to a few kHz) and the spatial scale of interest is small compared to the speed of electromagnetic propagation. Under these conditions, the quasistatic approximation is appropriate: the spatial pattern of the extracellular potential adjusts essentially instantaneously to changes in electrode current, and displacement currents can be neglected.

Practically, this means we can separate the field into:

  • a spatial component (a “lead field”) that depends only on position, and

  • a temporal component that depends only on the stimulation waveform.

For a single stimulating electrode, we can write

\[\phi_e(x, t) \approx I(t)\,\Phi(x),\]

where:

  • \(\Phi(x)\) is the extracellular lead field produced per unit current at that electrode, conventionally in mV/mA, and

  • \(I(t)\) is the time-varying current waveform in mA.

For multiple electrodes, this generalizes to

\[\phi_e(x, t) = \sum_e I_e(t)\,\Phi_e(x),\]

where each \(\Phi_e(x)\) is the unit-current field for electrode \(e\).

In Dendra, this is exactly how field objects are used: you provide a spatial solution (or analytic expression) for unit input, and then drive it with one or more time-varying waveforms. Internally, Dendra evaluates \(\phi_e(x_i, t_n)\) for every compartment and timestep without requiring you to recompute the field solution when you change the waveform.

The unit contract is that every extracellular potential reaching the cable solver is in mV. Direct ve input is already in mV. For extra=(ve_s, waveform), the product ve_s * waveform(t) must be in mV. Dendra’s analytic point and line sources return ve_s numerically in mV/mA, so they pair with waveforms in mA. A precomputed absolute field in mV can instead be paired with a dimensionless relative waveform. Dendra’s unit helpers are scalar conversion factors, so this normalization is explicit rather than inferred at runtime.

Reciprocity and extracellular recording#

The same volume-conductor physics applies to extracellular recording. Under linear, quasistatic conditions, we can use reciprocity: the sensitivity of a recording electrode to a given membrane current source is the same as the extracellular potential that source would experience if we injected unit current at the recording site.

If \(\Phi_{\text{rec}}(x)\) denotes the potential field generated by a unit current at the recording electrode, then the recorded signal can be written schematically as

\[V_{\text{rec}}(t) = \sum_i \Phi_{\text{rec}}(x_i)\, I_m(x_i, t),\]

where \(I_m(x_i, t)\) is the transmembrane current at compartment \(x_i\).

In Dendra, this corresponds to using a “recording lead field” to weight the membrane currents from each compartment and sum them into a simulated local field potential or extracellular trace.

In summary:

  • Stimulation is modeled by imposing \(\phi_e(x_i, t_n)\) per compartment and timestep, using precomputed spatial fields scaled by time-varying waveforms.

  • Recording is modeled by reading out a weighted sum of membrane currents, using reciprocity-based lead fields for the recording electrode.

The rest of this tutorial will show how to construct these fields, attach them to neuronal populations, and use Dendra to simulate both extracellular stimulation and recording.

Example: Extracellular kHz stimulation and recording#

We will simulate a single myelinated axon model receiving extracellular kHz stimulation from a point source electrode, while recording the extracellular potential at another nearby point.

import dendra as dn
from dendra.models.mod import hh
from dendra.units import mm, um

model = dn.Myelinated(
    diameters=[6.0], n_node=201, node_length=1.0, celsius=6.3, v_init=-65.0
)
model.insert(hh)

The default Myelinated class assumes the well established heuristic that nodes of Ranvier are the only excitable compartments, with myelinated segments being fully insulated. This is a simplification, but it allows us to focus on the extracellular stimulation and recording aspects without needing to implement a full myelin model. It also implements the standard heuristic that the internodal length is 100x the fiber diameter, so we can see that the model nodes of Ranvier span from -60 mm to +60 mm for a 6 μm fiber with 201 nodes:

print(model.x)
tensor([[-60000., -59400., -58800., -58200., -57600., -57000., -56400., -55800.,
         -55200., -54600., -54000., -53400., -52800., -52200., -51600., -51000.,
         -50400., -49800., -49200., -48600., -48000., -47400., -46800., -46200.,
         -45600., -45000., -44400., -43800., -43200., -42600., -42000., -41400.,
         -40800., -40200., -39600., -39000., -38400., -37800., -37200., -36600.,
         -36000., -35400., -34800., -34200., -33600., -33000., -32400., -31800.,
         -31200., -30600., -30000., -29400., -28800., -28200., -27600., -27000.,
         -26400., -25800., -25200., -24600., -24000., -23400., -22800., -22200.,
         -21600., -21000., -20400., -19800., -19200., -18600., -18000., -17400.,
         -16800., -16200., -15600., -15000., -14400., -13800., -13200., -12600.,
         -12000., -11400., -10800., -10200.,  -9600.,  -9000.,  -8400.,  -7800.,
          -7200.,  -6600.,  -6000.,  -5400.,  -4800.,  -4200.,  -3600.,  -3000.,
          -2400.,  -1800.,  -1200.,   -600.,      0.,    600.,   1200.,   1800.,
           2400.,   3000.,   3600.,   4200.,   4800.,   5400.,   6000.,   6600.,
           7200.,   7800.,   8400.,   9000.,   9600.,  10200.,  10800.,  11400.,
          12000.,  12600.,  13200.,  13800.,  14400.,  15000.,  15600.,  16200.,
          16800.,  17400.,  18000.,  18600.,  19200.,  19800.,  20400.,  21000.,
          21600.,  22200.,  22800.,  23400.,  24000.,  24600.,  25200.,  25800.,
          26400.,  27000.,  27600.,  28200.,  28800.,  29400.,  30000.,  30600.,
          31200.,  31800.,  32400.,  33000.,  33600.,  34200.,  34800.,  35400.,
          36000.,  36600.,  37200.,  37800.,  38400.,  39000.,  39600.,  40200.,
          40800.,  41400.,  42000.,  42600.,  43200.,  43800.,  44400.,  45000.,
          45600.,  46200.,  46800.,  47400.,  48000.,  48600.,  49200.,  49800.,
          50400.,  51000.,  51600.,  52200.,  52800.,  53400.,  54000.,  54600.,
          55200.,  55800.,  56400.,  57000.,  57600.,  58200.,  58800.,  59400.,
          60000.]])

We need to supply the extracellular potential fields for both stimulation and recording. For simplicity, we will use the analytic solution for a point source in an infinite homogeneous medium. Dendra’s point source field generator makes this easy: it returns a lead field in mV/mA (numerically equal to the potential in mV for a 1 mA source). The default resistivity is 300 Ω·cm, but you can change this with the rhoe argument if desired.

stim_source = dn.isotropic_point(z=100.0 * um, x=-40.0 * mm)
rec_source = dn.isotropic_point(z=150.0 * um, x=40.0 * mm)

For starters, lets just do stimulation:

from dendra.units import mA, kHz

ve_stim = stim_source(model)
i_stim = dn.sin(amp=0.1 * mA, freq=1.0 * kHz)  # 0.1 mA, 1 kHz sine wave
rec = dn.callbacks.Recorder(['v'], node_indices=model.c(0.16, 0.5, 0.75, 1.0))

tstop, dt = 50.0, 0.001

# run as before, but supply extracellular potential for stimulation
rec.reset()
model.initialize()
model.longrun(
    tstop=tstop, dt=dt, chunklength=100, 
    extra=(ve_stim, i_stim), callbacks=[rec],
    progressbar=False
)
import matplotlib.pyplot as plt
import numpy as np

v = rec.numpy('v')
t = np.arange(0, tstop+dt, dt)

plt.figure(figsize=(5, 3), dpi=200)
plt.plot(t, v[:, 0, 0], label="under stimulus")
plt.plot(t, v[:, 0, 1], label="50% node")
plt.plot(t, v[:, 0, 2], label="75% node")
plt.plot(t, v[:, 0, 3], label="end node")
plt.xlabel("Time (ms)")
plt.ylabel("Membrane Potential (mV)")
plt.legend()
plt.show()
../_images/3fd0dda2d57261689fe502ca95e4a15a176c9f5682bf363afda5479089083d4d.png

Ok great! We have the extracellular potential field set up for stimulation. We see that this particular stimulation configuration has an onset response and then not much else (at least not within the first 50 ms). Next, we can record some LFP data using the LFP callback. This, however, requires one small change: for LFP recording, we need to provide the total transmembrane currents as well. To do this, we need to instruct the model to compute and store these currents during the simulation at instantiation, using dn.ctx. Public model.i_membrane is absolute transmembrane current in mA: capacitive plus ionic/mechanism current with Dendra’s outward-positive sign. Applied intracellular stimulus and axial cable currents affect it through the solved voltage but are not added as separate transmembrane-current terms.

LFP takes a non-empty list containing one reciprocal lead-field tensor per recording contact. Each field is in mV/mA and is multiplied by model.i_membrane in mA, so the recorded result is in mV. For a single contact, pass [v_rec] rather than v_rec; the leading output dimension indexes recording contacts:

with dn.ctx(IMEM=1):
    model = dn.Myelinated(
        diameters=[6.0], n_node=201, node_length=1.0, celsius=6.3, v_init=-65.0
    )
    
# then same as before
model.insert(hh)

v_rec = rec_source(model)  # reciprocal lead field [mV/mA]
lfp_rec = dn.callbacks.LFP([v_rec])

lfp_rec.reset()
model.initialize()
model.longrun(
    tstop=tstop, 
    dt=dt, 
    chunklength=100, 
    extra=(ve_stim, i_stim), 
    callbacks=[lfp_rec],
    progressbar=False
)
plt.figure(figsize=(5, 3), dpi=200)
plt.plot(t, lfp_rec.numpy()[:, 0])
plt.xlabel("Time (ms)")
plt.ylabel("LFP (mV)")
plt.show()
../_images/8ffe63322f333e5f32d203038aee589cd636061c7389a8676983c9c1d83bae77.png

Stimulating and recording from a population#

Now that we have the basic extracellular stimulation and recording working for a single axon, we can easily extend this to a population of axons. We will create a population of 100 myelinated axons arranged in a grid, and apply the same extracellular stimulation and recording setup as before.

import torch

diameters = np.random.uniform(5.0, 10.0, size=100)

with dn.ctx(IMEM=1):
    model = dn.Myelinated(
        diameters=diameters, n_node=201, node_length=1.0, celsius=6.3, v_init=-65.0
    )
    
# then same as before
model.insert(hh)

# add some random spatial offsets to each axon
x_offsets = -50.0 + 100.0 * torch.rand(100)
y_offsets = -20.0 + 40.0 * torch.rand(100)
z_offsets = -20.0 + 40.0 * torch.rand(100)
model.x += x_offsets[:, None]
model.y += y_offsets[:, None]
model.z += z_offsets[:, None]

v_stim = stim_source(model)
v_rec = rec_source(model)  # reciprocal lead field [mV/mA]
lfp_rec = dn.callbacks.LFP([v_rec])

lfp_rec.reset()
model.initialize()
model.longrun(
    tstop=tstop, 
    dt=dt, 
    chunklength=100, 
    extra=(v_stim, i_stim), 
    callbacks=[lfp_rec],
    progressbar=False
)
plt.figure(figsize=(5, 3), dpi=200)
plt.plot(t, lfp_rec.numpy()[:, 0])
plt.xlabel("Time (ms)")
plt.ylabel("LFP (mV)")
plt.show()
../_images/10be116e4e1c30f9605a61eca815e858be964d5cc6edafc9b64d8cbcc80580af.png

Great! To summarize, we have successfully set up extracellular stimulation and recording for a population of myelinated axons using Dendra. We created a population of axons with random diameters and spatial offsets, applied point source stimulation, and recorded the resulting extracellular potentials. Next, you can experiment with different stimulation parameters, electrode configurations, and axon properties to explore their effects on the recorded signals. In later tutorials, we will look into branched neuron models and how to apply extracellular stimulation and recording to them.