Extracellular fields#

Python module dendra.models.fields.

Field normalization and units#

Field modules return a spatial tensor; they do not attach physical-unit metadata. When the result is used as ve_s in extra=(ve_s, waveform), the product ve_s * waveform(t) must be an extracellular potential in mV. This supports two common representations:

  • an absolute spatial potential in mV driven by a dimensionless relative waveform; or

  • a normalized lead field in mV per input unit driven by a waveform expressed in that input unit.

The analytic point and line sources use the second convention. Coordinates are in µm, resistivity is in Ω·cm, and their return value is numerically in mV/mA (equivalently, the potential in mV produced by a 1 mA source). Therefore use a temporal waveform in mA. The product is then mV because (mV/mA) * mA = mV.

The scalar precomputed interpolators preserve the values supplied by the caller without unit conversion. Their data may therefore be absolute mV or a lead field with any declared normalization, provided the temporal waveform makes the final product mV. PreComputedInterpolate1D.from_ascent converts ASCENT values stored in V to mV, but that representation conversion does not change the source data’s reference-amplitude normalization.

The E-field interpolators expect electric-field vectors in V/m and model coordinates in µm. They integrate those vectors along the morphology and return quasipotentials in mV. Treat that result as an absolute mV field with a dimensionless relative waveform, or normalize it to a chosen input amplitude before pairing it with a dimensional waveform.

See Stimulation and waveforms for accepted shapes and broadcasting, and Units used in Dendra for Dendra’s broader unit conventions.

Analytic lead fields#

class isotropic_point(**kwargs)[source]#

Isotropic point source for electric potential calculation.

Calculates the electric potential in a medium with uniform (isotropic) resistivity, where the resistivity is the same in all directions.

Parameters:
  • x (float, optional) – X-coordinate of the point source in μm. Default is 0.0.

  • y (float, optional) – Y-coordinate of the point source in μm. Default is 0.0.

  • z (float, optional) – Z-coordinate of the point source in μm. Default is 0.0.

  • rhoe (float, optional) – Extracellular resistivity in Ω·cm. Default is 300.0.

Notes

The potential is calculated using the standard point source equation:

\[\Phi(x,y,z) = \frac{\rho_e}{4\pi r}\]

where \(r = \sqrt{(x-x_0)^2 + (y-y_0)^2 + (z-z_0)^2} \cdot 10^{-4}\) is the source distance in cm.

The result has units of Ω and is represented numerically as a lead field in mV/mA, because Ω × mA = mV. Equivalently, it is the potential in mV produced by a 1 mA point source.

class anisotropic_point(**kwargs)[source]#

Anisotropic point source for electric potential calculation.

Calculates the electric potential in a medium with anisotropic resistivity, where the resistivity values can be different along the x, y, and z axes.

Parameters:
  • x (float, optional) – X-coordinate of the point source in μm. Default is 0.0.

  • y (float, optional) – Y-coordinate of the point source in μm. Default is 0.0.

  • z (float, optional) – Z-coordinate of the point source in μm. Default is 0.0.

  • rhox (float, optional) – Resistivity in the x-direction in Ω·cm. Default is 300.0.

  • rhoy (float, optional) – Resistivity in the y-direction in Ω·cm. Default is 300.0.

  • rhoz (float, optional) – Resistivity in the z-direction in Ω·cm. Default is 300.0.

Notes

The potential is calculated using the anisotropic medium equation:

\[\Phi(x,y,z) = \frac{1}{4\pi \sqrt{\frac{(x-x_0)^2}{\rho_y \rho_z} + \frac{(y-y_0)^2}{\rho_x \rho_z} + \frac{(z-z_0)^2}{\rho_x \rho_y}}}\]

where all coordinate differences are converted from μm to cm before the expression is evaluated.

The result has units of Ω and is represented numerically as a lead field in mV/mA, because Ω × mA = mV. Equivalently, it is the potential in mV produced by a 1 mA point source.

class line3d(start, end, samples=2, **kwargs)[source]#

Straight 3-D line source between start and end.

class arbitrary_line(xyz, **kwargs)[source]#

Analytic line source defined by an arbitrary polyline trajectory.

class arc_line(x, radius, orbit, phase=0.0, samples=100, **kwargs)[source]#

Planar arc line source at fixed x.

class helix_line(x_start, x_end, radius, orbits, phase=0.0, samples=100, **kwargs)[source]#

Helical line source parameterized around the x-axis.

Parametric E-fields#

class parametric_efield(n_azimuthal, n_polar, relative_mag_change_per_mm=0.0)[source]#

Generate quasipotentials for a grid of uniform E-field directions.

The public forward() path treats model.x, model.y, and model.z as coordinates in µm, accepts an E-field magnitude in V/m, and returns extracellular quasipotentials in mV. Let D be n_azimuthal * n_polar and Q be the product of every model coordinate axis except the final compartment axis. Direction-to-model alignment is explicit:

  • D == Q pairs one direction with each flattened logical model lane and restores the exact model coordinate shape.

  • D == 1 broadcasts the single direction over all Q lanes and restores the exact model coordinate shape.

  • Q == 1 with D > 1 is field-generation mode and returns (D, C). Any singleton leading axes in a higher-rank model are intentionally collapsed. When D == Q == 1, the single-direction rule takes precedence and preserves the exact coordinate shape.

  • All other D/Q combinations raise ValueError; they never form an implicit Cartesian product.

Parameters:
  • n_azimuthal (int) – The number of azimuthal angles (phi) to sample (e.g., around the z-axis).

  • n_polar (int) – The number of polar/inclination angles (theta) to sample (from the z-axis).

  • relative_mag_change_per_mm (Union[float, List[float], torch.Tensor]) – Percentage change in E-field magnitude per mm along the somatodendritic axis (z-axis). For example, 200.0 means 200% per mm. Can be a single value or a list of values. A positive value means the E-field magnitude increases from the soma towards negative z. This parameter is used by the internal spatial-gradient integration path; the public forward() path generates a uniform field.

Notes

e_field_strength_Vm is the physical E-field magnitude in V/m, not a Dendra conversion scalar. The returned value already has units of mV, so when it is used as the spatial component of extracellular stimulation it should normally be paired with a dimensionless relative waveform.

forward(model, e_field_strength_Vm=1.0)[source]#

Return uniform-field quasipotentials for every sampled direction.

Parameters:
  • model (object) – Model whose x, y, and z tensors contain compartment coordinates in µm.

  • e_field_strength_Vm (float, default 1.0) – Uniform E-field magnitude in V/m.

Returns:

Quasipotentials in mV. See the class-level direction-alignment contract for the exact output shape.

Return type:

torch.Tensor

Precomputed#

class PreComputedInterpolate1D(data=None, x=None, outside='zero', *, truncate=None, truncate_mode='best_fit', **kwargs)[source]#

Use PreComputed data sampled along x at different (y, z) locations.

Parameters:
  • data (torch.Tensor) – 2D tensor of shape (D, N) containing the precomputed field values. The values retain the caller’s normalization; see Notes.

  • x (torch.Tensor) – 1D or 2D tensor of shape (N,) or (D, N) containing the x-coordinates in μm corresponding to the data values. If 1D, the same x-coordinates are used for all D rows. If 2D, each row can have different x-coordinates (i.e., can be sampled at different locations along x).

  • outside (str, optional) – Behavior for points outside the interpolation range. Options are “zero” or “point_source”. If “point_source”, the interpolation uses a point-source model outside the (optionally truncated) support. Default is “zero”.

  • truncate (float or None, optional) – Amount to truncate the data symmetrically. Default is None (no truncation).

  • truncate_mode (str, optional) – Mode for truncation, either “best_fit” or “safe”. Default is “best_fit”.

  • **kwargs – Additional keyword arguments passed to PreparedInterp1d.

Notes

  • The input data and x tensors must have the same shape (D, N), where D is the number of data rows and N is the number of samples per row.

  • The x values for each row must be sorted in ascending order, either by setting sort_xy=True (default) or ensuring they are pre-sorted when sort_xy=False.

  • Truncation removes a fraction of the data symmetrically from both ends of the x-domain.

  • The outside parameter determines how values outside the interpolation range are handled. If set to “point_source”, a point-source extrapolation is applied based on the peak and boundary values of each row.

  • Interpolation preserves the units and reference-amplitude normalization of data. For extracellular stimulation, data may be an absolute potential in mV paired with a dimensionless waveform, or a lead field in mV per input unit paired with a waveform in that unit. The final product supplied through extra must be in mV.

  • Model coordinates follow the field contract (*batch, N, C). A single LUT row broadcasts everywhere. A bank of N rows aligns with the model population axis and repeats over every outer batch axis. A bank with one row per flattened logical lane also aligns row-wise. Other mappings are ambiguous and require explicit indices.

classmethod from_ascent(ascent_dir, sample, model, sim, contact, **kwargs)[source]#

Create a PreComputedInterpolate1D instance from precomputed data generated by the ASCENT pipeline.

Parameters:
  • ascent_dir (str) – “ASCENT_PROJECT_PATH” as used in your ASCENT env.json, e.g. “/path/to/ascent_project”.

  • sample (int) – Sample number, e.g. 0.

  • model (int) – Model number, e.g. 0.

  • sim (int) – Simulation number, e.g. 0.

  • contact (int) – Contact number, e.g. 0.

Returns:

An instance initialized with the precomputed data converted from V to mV. This conversion preserves the ASCENT dataset’s original reference-amplitude normalization.

Return type:

PreComputedInterpolate1D

class dendra.models.fields.precomputed_interpolate_1d#

Alias of dendra.models.fields.PreComputedInterpolate1D.

class PreComputedInterpolate3DRect(x, y, z, field, **kwargs)[source]#

Interpolate 3D field from rectilinear grid.

Parameters:
  • x (torch.Tensor) – 1D tensor of x-coordinates of the grid points (in μm).

  • y (torch.Tensor) – 1D tensor of y-coordinates of the grid points (in μm).

  • z (torch.Tensor) – 1D tensor of z-coordinates of the grid points (in μm).

  • field (torch.Tensor) – Tensor of shape (Nx, Ny, Nz, …) containing the field values at the grid points. Interpolation preserves the caller’s units and reference-amplitude normalization.

  • **kwargs (additional keyword arguments for PreparedInterp3dRect.)

Notes

  • Model coordinates and the scalar result have shape (*batch, N, C).

  • All operations remain on the same device/dtype as the model.

  • The module is differentiable w.r.t. the model’s coordinates; the field grid points/values are treated as constants (buffers).

  • The module is differentiable w.r.t. the field values, but must be specified explicitly with learnable=True as a kwarg.

  • For extracellular stimulation, the interpolated field multiplied by its temporal waveform must be in mV.

class dendra.models.fields.precomputed_interpolate_3d_rect#

Alias of dendra.models.fields.PreComputedInterpolate3DRect.

class PreComputedInterpolate3DScattered(xyz, field, **kwargs)[source]#

Interpolate 3D field from scattered points.

Parameters:
  • xyz (torch.Tensor) – A tensor of shape (N, 3) containing the coordinates (x, y, z) in μm.

  • field (torch.Tensor) – A tensor of shape (N, 1) containing the field values at the coordinates. Interpolation preserves the caller’s units and reference-amplitude normalization.

  • **kwargs (additional keyword arguments for PreparedInterp3dScattered.)

Notes

  • Model coordinates and the scalar result have shape (*batch, N, C).

  • All operations remain on the same device/dtype as the model.

  • The module is differentiable w.r.t. the model’s coordinates; the sample points/values are treated as constants (buffers).

  • The module is differentiable w.r.t. the field values, but must be specified explicitly with learnable=True as a kwarg.

  • For extracellular stimulation, the interpolated field multiplied by its temporal waveform must be in mV.

class dendra.models.fields.precomputed_interpolate_3d_scattered#

Alias of dendra.models.fields.PreComputedInterpolate3DScattered.

class EfieldInterpolate3DRect(x, y, z, efield, **kwargs)[source]#

Interpolate 3D E-field from rectilinear grid and compute quasipotentials.

Parameters:
  • x (torch.Tensor) – 1D tensor of x-coordinates of the grid points (in μm).

  • y (torch.Tensor) – 1D tensor of y-coordinates of the grid points (in μm).

  • z (torch.Tensor) – 1D tensor of z-coordinates of the grid points (in μm).

  • efield (torch.Tensor) – 4D tensor of shape (Nx, Ny, Nz, 3) containing the electric-field vectors at the grid points in V/m.

  • **kwargs (additional keyword arguments for PreparedInterp3dRect.)

Notes

  • Model coordinates have shape (*batch, N, C); interpolated vectors have one trailing component axis and quasipotentials preserve the model coordinate shape.

  • All operations remain on the same device/dtype as the model.

  • The module is differentiable w.r.t. the model’s coordinates; the E-field grid points/values are treated as constants (buffers).

  • The module is differentiable w.r.t. the efield values, but must be specified explicitly with learnable=True as a kwarg.

  • Calling the module integrates the interpolated E-field along the model morphology and returns quasipotentials in mV.

class dendra.models.fields.efield_interpolate_3d_rect#

Alias of dendra.models.fields.EfieldInterpolate3DRect.

class EfieldInterpolate3DScattered(xyz, efield, **kwargs)[source]#

Interpolate 3D E-field from scattered points and compute quasipotentials.

Parameters:
  • xyz (torch.Tensor) – A tensor of shape (N, 3) containing the coordinates (x, y, z) in μm.

  • efield (torch.Tensor) – A tensor of shape (N, 3) containing the electric-field vectors at the coordinates in V/m.

  • **kwargs (additional keyword arguments for PreparedInterp3dScattered.)

Notes

  • Model coordinates have shape (*batch, N, C); interpolated vectors have one trailing component axis and quasipotentials preserve the model coordinate shape.

  • All operations remain on the same device/dtype as the model.

  • The module is differentiable w.r.t. the model’s coordinates; the sample points/values are treated as constants (buffers).

  • The module is differentiable w.r.t. the efield values, but must be specified explicitly with learnable=True as a kwarg.

  • Calling the module integrates the interpolated E-field along the model morphology and returns quasipotentials in mV.

class dendra.models.fields.efield_interpolate_3d_scattered#

Alias of dendra.models.fields.EfieldInterpolate3DScattered.

Unstructured meshes#

class EfieldInterpolate3DMesh(interpolator, *, coordinate_scale=1.0, coordinate_offset=None)[source]#

Interpolate a mesh-defined 3-D E-field and compute quasipotentials.

This is the tetrahedral-mesh analogue of EfieldInterpolate3DRect and EfieldInterpolate3DScattered. E-field solutions from SimNIBS are stored as ElementData with three components per element, so construction is normally via from_ElementData().

Parameters:
  • interpolator (PreparedInterp3dFEM) – Prepared FEM interpolator created from vector ElementData.

  • coordinate_scale (float, optional) – Multiplicative conversion from model coordinates to mesh coordinates before interpolation. Use 1e-3 when model coordinates are in micrometers and the SimNIBS mesh is in millimeters. Default is 1.0.

  • coordinate_offset (array-like, optional) – Three-element offset with shape (3,), applied after scaling in mesh-coordinate units.

Notes

Model coordinates have shape (*batch, N, C); interpolated vectors have one trailing component axis and quasipotentials preserve the coordinate shape.

The supplied ElementData values must be electric-field vectors in V/m; calling the module returns quasipotentials in mV.

The default from_ElementData(..., method='linear', continuous=False) path reproduces SimNIBS’ tag-wise element-to-node recovery followed by barycentric interpolation, which is the appropriate high-quality interpolation path for discontinuous E-fields across tissue boundaries.

classmethod from_ElementData(element_data, *, out_fill=nan, method='linear', continuous=False, th_indices=None, coordinate_scale=1.0, coordinate_offset=None, dtype=None, device=None, learnable_values=False, values_requires_grad=True)[source]#

Create an E-field interpolator from SimNIBS-like ElementData.

Parameters mirror ElementData.interpolate_scattered where relevant. The default method='linear', continuous=False is selected for E-fields because it preserves tag-wise discontinuities by preparing separate recovered nodal fields per tissue tag.

classmethod from_element_data(element_data, *, out_fill=nan, method='linear', continuous=False, th_indices=None, coordinate_scale=1.0, coordinate_offset=None, dtype=None, device=None, learnable_values=False, values_requires_grad=True)#

Create an E-field interpolator from SimNIBS-like ElementData.

Parameters mirror ElementData.interpolate_scattered where relevant. The default method='linear', continuous=False is selected for E-fields because it preserves tag-wise discontinuities by preparing separate recovered nodal fields per tissue tag.

interpolate_efield(model)[source]#

Return interpolated E-field vectors at model coordinates.

forward(model)[source]#

Interpolate E-field vectors and convert them to quasipotentials.

class dendra.models.fields.efield_interpolate_3d_mesh#

Alias of dendra.models.fields.EfieldInterpolate3DMesh.

class PreComputedInterpolate3DMesh(interpolator, *, coordinate_scale=1.0, coordinate_offset=None)[source]#

Interpolate a scalar mesh-defined field at model coordinates.

This wrapper is the tetrahedral-mesh analogue of PreComputedInterpolate3DRect and PreComputedInterpolate3DScattered. It delegates the actual mesh-guided FEM interpolation to PreparedInterp3dFEM, which reproduces SimNIBS NodeData.interpolate_scattered behavior.

Parameters:
  • interpolator (PreparedInterp3dFEM) – Prepared FEM interpolator, normally created with from_NodeData().

  • coordinate_scale (float, optional) – Multiplicative conversion from model coordinates to mesh coordinates before interpolation. Use 1e-3 when model coordinates are in micrometers and the SimNIBS mesh is in millimeters. Default is 1.0.

  • coordinate_offset (array-like, optional) – Three-element offset with shape (3,), applied after scaling in mesh-coordinate units.

Notes

  • Model coordinates and the scalar result have shape (*batch, N, C).

  • Scalar values retain the units and reference-amplitude normalization of the supplied NodeData. For extracellular stimulation, the interpolated field multiplied by its temporal waveform must be in mV.

  • The SimNIBS mesh point-location step remains CPU/NumPy/Cython based inside PreparedInterp3dFEM; value gathering/blending runs in torch on the interpolator device.

  • Gradients may flow to learnable field values when the prepared interpolator was constructed with learnable_values=True. Gradients do not flow through the discrete tetrahedron lookup or back to query coordinates.

classmethod from_NodeData(node_data, *, out_fill=nan, th_indices=None, coordinate_scale=1.0, coordinate_offset=None, dtype=None, device=None, learnable_values=False, values_requires_grad=True)[source]#

Create a scalar mesh interpolator from a SimNIBS-like NodeData.

NodeData is the natural format for scalar nodal fields such as voltage. The wrapped prepared interpolator uses tetrahedron containment plus barycentric interpolation, matching node_data.interpolate_scattered.

classmethod from_node_data(node_data, *, out_fill=nan, th_indices=None, coordinate_scale=1.0, coordinate_offset=None, dtype=None, device=None, learnable_values=False, values_requires_grad=True)#

Create a scalar mesh interpolator from a SimNIBS-like NodeData.

NodeData is the natural format for scalar nodal fields such as voltage. The wrapped prepared interpolator uses tetrahedron containment plus barycentric interpolation, matching node_data.interpolate_scattered.

forward(model)[source]#

Interpolate the scalar field at model.x, model.y, model.z.

class dendra.models.fields.precomputed_interpolate_3d_mesh#

Alias of dendra.models.fields.PreComputedInterpolate3DMesh.