Interpolation and utilities#

Python module dendra.utils.

Interpolation#

class PreparedInterp1d(x, y, *, outside='clamp', fill_value=0.0, learnable_y=False, y_requires_grad=True, sort_xy=True, eps=None, exact_clamp=True, uniform='auto', uniform_rtol=1e-05, uniform_atol=1e-07)[source]#

Prepared 1D piecewise-linear interpolator with optional learnable ordinates.

This module implements fast, GPU-friendly 1D linear interpolation for either a single lookup table (unbatched) or a batch of lookup tables (batched). It performs all static preparation once at initialization, including optional sorting of x (and corresponding permutation of y) to satisfy torch.searchsorted preconditions.

Supported regimes (enforced)#

Exactly one of the following input regimes is supported:

  1. Unbatched: x and y are both 1D arrays of shape (N,) representing a single tabulated function.

  2. Batched: x and y are both 2D arrays of shape (D, N) representing a batch of D independent tabulated functions.

Query points (x_new) are accepted in both regimes as either: - 1D array of shape (P,) - 2D array of shape (Q, P)

Disambiguation via indices#

In batched mode, some x_new shapes are ambiguous with respect to which LUT row should be used. This module resolves ambiguity as follows:

  • If x, y are (D, N) and x_new is (D, P), then the mapping is unambiguous and the default behavior is row-wise alignment (row d of x_new uses row d of x, y).

  • Otherwise, the user must provide indices to specify the mapping:

    • If x_new is (Q, P), then indices must have length Q and maps each query row q to a LUT row indices[q] in [0, D-1].

    • If x_new is (P,) (internally treated as (1, P)), then indices selects which LUT rows to evaluate that same query against. If indices has length L, the output will be shaped (L, P).

Out-of-bounds behavior#

Values outside the domain of x are handled according to outside:

  • outside="clamp": constant extension using the endpoint values (left of domain -> first y, right of domain -> last y).

  • outside="zero": out-of-domain values are set to 0.

  • outside="fill": out-of-domain values are set to fill_value.

Differentiability w.r.t. y#

If learnable_y=True, y is stored as an nn.Parameter and interpolation remains differentiable with respect to y (piecewise linear in y). In this mode, slopes are not precomputed as constants; instead, y[i] and y[i+1] are gathered per query and combined with a precomputed inverse dx derived from x.

Notes

  • This module relies on torch.searchsorted for interval selection. The selected interval index is a discrete operation; gradients do not propagate through changes in the selected interval.

  • If sort_xy=True, x is sorted along its last dimension at initialization and y is permuted to match. This ensures searchsorted is valid even if the user provides unsorted x.

  • Duplicate x entries are handled by replacing zero-length segments with an epsilon in the denominator. This avoids division-by-zero but does not make the interpolation well-defined at duplicates; consider de-duplicating if needed.

Examples

Unbatched LUT, 1D query:

>>> x = torch.tensor([0., 1., 2.], device="cuda")
>>> y = torch.tensor([0., 1., 0.], device="cuda")
>>> interp = PreparedInterp1d(x, y, outside="clamp", sort_xy=True).cuda()
>>> xq = torch.tensor([-1., 0.5, 3.0], device="cuda")
>>> yq = interp(xq)  # shape (3,)

Batched LUTs, aligned 2D query:

>>> x = torch.stack([torch.linspace(0, 1, 5), torch.linspace(0, 2, 5)]).cuda()
>>> y = torch.randn_like(x)
>>> interp = PreparedInterp1d(x, y, outside="zero").cuda()
>>> xq = torch.randn(2, 16, device="cuda")  # (D,P) -> aligned
>>> yq = interp(xq)  # (2,16)

Batched LUTs, ambiguous query resolved by indices:

>>> xq = torch.randn(7, 16, device="cuda")       # (Q,P), Q != D
>>> idx = torch.randint(0, 2, (7,), device="cuda")
>>> yq = interp(xq, indices=idx)                 # (7,16)

Learnable y:

>>> interp = PreparedInterp1d(x, y, learnable_y=True).cuda()
>>> yq = interp(xq)
>>> loss = yq.square().mean()
>>> loss.backward()  # gradients flow to interp.y

Initialize and prepare the interpolator.

param x:

Abscissae (x-coordinates) of the lookup table(s).

Must be either: - shape (N,) in unbatched mode, or - shape (D, N) in batched mode.

If sort_xy=True, x may be unsorted; it will be sorted internally. If sort_xy=False, x must already be sorted ascending along its last dimension for torch.searchsorted to behave correctly.

type x:

torch.Tensor

param y:

Ordinates (y-coordinates) of the lookup table(s), same shape as x (either (N,) or (D, N)). If sort_xy=True, y is permuted to remain aligned with sorted x.

type y:

torch.Tensor

param outside:

Policy for handling query points outside the domain of x.

  • “clamp”: return endpoint values (constant extension).

  • “zero”: return 0 outside domain.

  • “fill”: return fill_value outside domain.

type outside:

{“clamp”, “zero”, “fill”}, default=”clamp”

param fill_value:

Fill value used when outside="fill".

type fill_value:

float, default=0.0

param learnable_y:

If True, y is stored as an nn.Parameter and the forward pass is differentiable with respect to y. If False, y is treated as constant and stored as a buffer.

type learnable_y:

bool, default=False

param y_requires_grad:

Only relevant when learnable_y=True. Sets requires_grad on the internally stored parameter.

type y_requires_grad:

bool, default=True

param sort_xy:

If True, sort x along its last dimension at initialization, and permute y identically. This guarantees valid behavior of torch.searchsorted.

type sort_xy:

bool, default=True

param eps:

Epsilon used to replace zero-length segments when computing 1/dx. If None, uses torch.finfo(dtype).eps for x’s dtype.

type eps:

float or None, default=None

param exact_clamp:

Only relevant when outside="clamp" (either as default or overridden in forward). If True, endpoint clamping is enforced with explicit comparisons (<= x_min and >= x_max) to guarantee constant extension semantics even in edge cases. If False, x_new is clamped into the domain prior to interval selection; this is typically sufficient and can save two torch.where operations.

type exact_clamp:

bool, default=True

param uniform:

Whether to check for uniform spacing in x and use a fast path if so. - “auto”: check for uniform spacing and use fast path if detected. - “never”: always use the general (non-uniform) path. - “always”: assume x is uniformly spaced; raise an error if not.

type uniform:

{“auto”, “never”, “always”}, default=”auto”

param uniform_rtol:

Relative tolerance used when checking for uniform spacing in x rows.

type uniform_rtol:

float, default=1e-5

param uniform_atol:

Absolute tolerance used when checking for uniform spacing in x rows.

type uniform_atol:

float, default=1e-7

raises ValueError:

If x and y do not share the same dimensionality (both 1D or both 2D), or shapes are inconsistent (e.g., x is (D,N) but y is not).

raises TypeError:

If tensors are not floating-point.

forward(x_new, *, indices=None, outside=None, fill_value=None, out=None)[source]#

Interpolate at query points x_new.

Parameters:
  • x_new (torch.Tensor) –

    Query points at which to evaluate the interpolant(s).

    Accepted shapes:

    • (P,): a single query vector

    • (Q, P): a batch of query vectors

    In unbatched LUT mode (x,y are 1D), both shapes are always unambiguous.

    In batched LUT mode (x,y are 2D), shape compatibility determines whether an explicit indices mapping is required. See indices.

  • indices (int or sequence of int or torch.Tensor, optional) –

    Mapping from query rows in x_new to LUT rows in x/y (batched mode).

    • If x,y are 1D: indices is optional; if provided, it must be all zeros.

    • If x,y are 2D (D,N):

      • If x_new is (D, P) and indices is None: row-wise alignment is used (row d uses LUT row d).

      • If x_new is (Q, P) and Q != D: indices must be length Q, where indices[q] selects which LUT row to use for query row q.

      • If x_new is (P,): indices must be provided and selects which LUT rows to evaluate the same query vector against. If indices has length L, output is (L,P).

    Values in indices must be within [0, D-1].

  • outside ({"clamp", "zero", "fill"}, optional) – Override the module’s default out-of-bounds policy for this call.

  • fill_value (float, optional) – Override the module’s default fill value for this call when outside="fill".

  • out (torch.Tensor, optional) – Optional output tensor to write results into. Must have exactly the same shape as the computed output.

Returns:

y_new – Interpolated values.

Output shape

Let:

  • P = x_new.shape[-1]

  • D be the LUT batch size when x, y are batched (i.e., x, y have shape (D, N))

  • If x_new is 2D, define Q = x_new.shape[0]

  • If indices is provided, define L = len(indices) (after conversion to a 1D index tensor)

The output shape is determined as follows:

1) Unbatched LUT mode (x, y are 1D with shape (N,))

  • If x_new has shape (P,), output has shape (P,)

  • If x_new has shape (Q, P), output has shape (Q, P)

(In unbatched mode, indices is never required; if provided it must be all zeros.)

2) Batched LUT mode (x, y are 2D with shape (D, N))

  • If x_new has shape (D, P) and indices is None:

    • output has shape (D, P) (Row-wise alignment: query row d uses LUT row d.)

  • If x_new has shape (Q, P) and indices is provided with length Q:

    • output has shape (Q, P) (Query row q uses LUT row indices[q].)

  • If x_new has shape (Q, P) with Q != D and indices is None: error (ambiguous mapping)

  • If x_new has shape (P,):

    • indices is required (otherwise ambiguous)

    • The same query vector is evaluated against each selected LUT row.

    Let L = len(indices):

    • If L == 1, output has shape (P,) (the module returns 1D when the input was 1D and only one effective query row is evaluated)

    • If L > 1, output has shape (L, P)

Forcing a 2D output for a single selected LUT row

If you want a 2D output of shape (1, P) when selecting a single LUT row, pass x_new as 2D ((1, P)) rather than 1D ((P,)), e.g.:

y = interp(x_new[None, :], indices=[k])  # -> (1, P)

Return type:

torch.Tensor

Raises:
  • ValueError – If x_new is not 1D/2D, has incompatible batch dimension in batched mode without indices, or if indices is missing or malformed in ambiguous cases.

  • TypeError – If x_new is not floating-point.

class PreparedInterp1dUniform(x, y, *, outside='clamp', fill_value=0.0, learnable_y=False, y_requires_grad=True, sort_xy=True, check_uniform=False, rtol=1e-05, atol=1e-07, eps=None, exact_clamp=True)[source]#

Prepared 1D uniform-grid linear interpolator.

Same input/output regimes as PreparedInterp1d, but assumes x is uniformly spaced (per row, if batched), enabling O(1) interval selection without searchsorted.

forward(x_new, *, indices=None, outside=None, fill_value=None, out=None)[source]#

Interpolate at query points x_new.

Parameters:
  • x_new (torch.Tensor) – Query points at which to evaluate the interpolant(s). Accepted shapes are (P,) for unbatched interpolation and (Q, P) for batched interpolation with Q batches.

  • indices (int or sequence of int or torch.Tensor, optional) – Mapping from query rows in x_new to LUT rows in x/y (batched mode).

  • outside ({"clamp", "zero", "fill"}, optional) – Override the module’s default out-of-bounds policy for this call.

  • fill_value (float, optional) – Override the module’s default fill value for this call when outside="fill".

  • out (torch.Tensor, optional) – Optional output tensor to write results into. Must have exactly the same shape as the computed output.

Returns:

y_new – Interpolated values.

Return type:

torch.Tensor

Raises:
  • ValueError – If x_new is not 1D/2D, has incompatible batch dimension in batched mode without indices, or if indices is missing or malformed in ambiguous cases.

  • TypeError – If x_new is not floating-point.

class PreparedInterp3dRect(x, y, z, values, *, outside='clamp', fill_value=0.0, learnable_values=False, values_requires_grad=True, sort_xyz=True, eps=None, uniform='auto', uniform_rtol=1e-05, uniform_atol=1e-07)[source]#

Prepared trilinear interpolator on a rectilinear (tensor-product) grid.

Non-uniform axes use searchsorted. Uniform axes (detected per row) use arithmetic indexing as a fast-path.

forward(xyz_new, *, indices=None, outside=None, fill_value=None, out=None)[source]#

Interpolate at new query points.

Parameters:
  • xyz_new (torch.Tensor) – Shape (P,3) or (Q,P,3) (or generally (1,P,3) broadcastable). If 2D, single grid is used (unbatched). If 3D, Q is the batch size.

  • indices (int or Sequence[int], optional) – If the interpolator is batched (D > 1), specifies which grid(s) to use. Can be a single int (applied to all points) or a sequence of length Q. If None and batched, then Q must equal D and all grids are used.

  • outside ({"clamp", "zero", "fill"}, optional) – Out-of-bounds handling override. If None, uses the setting from constructor. - “clamp”: values outside are clamped to endpoint values - “zero”: values outside are set to 0 - “fill”: values outside are set to fill_value

  • fill_value (float, optional) – Fill value to use if outside=”fill”. If None, uses the setting from constructor.

  • out (torch.Tensor, optional) – Optional output buffer. If provided, must have the correct shape.

Returns:

values_new – Interpolated values at xyz_new. Shape is (P,C) if unbatched, or (Q,P,C) if batched (or generally broadcastable to that).

Return type:

torch.Tensor

laplacian_values(*, boundary='valid')[source]#

Compute the discrete (finite-difference) Laplacian of the grid values.

This is NOT the analytic Laplacian of the trilinear interpolant (which is 0 within each cell). Instead, it computes a second-derivative stencil along each axis on the rectilinear grid and returns:

lap = d2/dx2(values) + d2/dy2(values) + d2/dz2(values)

Parameters:

boundary ({"replicate", "zero", "one-sided", "valid"}, optional) – How to fill the Laplacian at the boundary indices along each axis: - “valid” (default): only compute Laplacian at fully interior nodes (requires Nx, Ny, Nz >= 3) - “replicate”: copy nearest interior value (e.g. lap[0]=lap[1]) - “zero”: leave boundary Laplacian as 0 - “one-sided”: use a 3-point one-sided second-derivative formula at the edges

Returns:

lap – Same shape as the original values passed to __init__: - unbatched: (Nx,Ny,Nz) or (Nx,Ny,Nz,C) - batched: (D,Nx,Ny,Nz) or (D,Nx,Ny,Nz,C)

Return type:

torch.Tensor

class PreparedInterp3dRectUniform(x, y, z, values, *, outside='clamp', fill_value=0.0, learnable_values=False, values_requires_grad=True, sort_xyz=True, check_uniform=False, rtol=1e-05, atol=1e-07, eps=None)[source]#

Prepared trilinear interpolator on a uniform rectilinear (tensor-product) grid.

Same regimes as the non-uniform 3D rectilinear interpolator, but assumes each axis is uniformly spaced (per row, if batched).

forward(xyz_new, *, indices=None, outside=None, fill_value=None, out=None)[source]#

Interpolate values at query points xyz_new.

Parameters:
  • xyz_new ((Q,P,3) or (P,3) float tensor) – Query points.

  • indices (Optional[IndexLike], optional) – Indices for batched interpolation, by default None

  • outside (Optional[OutsideMode], optional) – How to handle points outside the interpolation domain, by default None

  • fill_value (Optional[float], optional) – Value to use for points outside the domain if outside=’fill’, by default None

  • out (Optional[torch.Tensor], optional) – Optional output tensor to write results into, by default None

Returns:

Interpolated values at query points.

Return type:

torch.Tensor

class PreparedInterp3dScattered(points, values, *, method='idw', k=8, knn_backend='auto', recompute_d2=True, power=2.0, mls_reg=1e-06, radius=None, outside='none', fill_value=0.0, chunk_size=4096, eps=None, learnable_values=False, values_requires_grad=True, faiss_factory=None, faiss_nprobe=16)[source]#

Scattered-data interpolator in 3D using kNN-based local methods.

Required inputs#

points : (N,3) float tensor values : (N,P) or (N,) float tensor

Query#

xq : (…,3) -> (…,P) (or (…) if values were scalar)

Interpolation methods#

  • nearest : nearest neighbor (k ignored; uses k=1)

  • idw : inverse-distance weighted average over k neighbors

  • mls : moving least squares local affine fit (reproduces linear fields)

Optional accelerated kNN backends#

knn_backend=”auto” chooses based on device & availability:

CUDA:
  1. pytorch3d (knn_points) if installed

  2. torch_cluster if installed

  3. torch fallback

CPU:
  1. faiss (IndexFlatL2) if installed

  2. torch fallback

Notes

  • Neighbor selection is discrete, so gradients do not flow through changes in the neighbor set. Gradients do flow to values and (optionally) to xq inside a fixed neighbor set when recompute_d2=True.

forward(xq, *, out=None)[source]#

Interpolate values at query points xq.

Parameters:
  • xq ((...,3) float tensor) – Query points.

  • out ((...,P) or (...) float tensor, optional) – Optional output tensor to write results into.

Returns:

y – Interpolated values at query points. If input values were scalar, shape is (…); otherwise (…,P).

Return type:

(…,P) or (…) float tensor

interp1d(x, y, xnew, out=None, *, outside='zero', uniform='auto', uniform_rtol=1e-05, uniform_atol=1e-07)[source]#

Linear 1D interpolation for PyTorch (CPU/GPU) with batched support.

This function returns interpolated values of one or more 1D functions tabulated on x with values y, evaluated at query points xnew. It parallelizes over the leading (batch) dimension when inputs are 2D.

Notes

  • torch.searchsorted assumes x is sorted ascending along its last dimension (for each batch row, if batched).

  • Interpolation is piecewise-linear. The segment selection (searchsorted) is non-differentiable, but values are differentiable w.r.t. x, y, and xnew within each segment.

Parameters:
  • x (torch.Tensor) – Shape (N,) or (D, N). Abscissae (must be sorted ascending along last dim).

  • y (torch.Tensor) – Shape (N,) or (D, N). Ordinates. Must match x in columns; rows may be either equal or one of them may be 1 (broadcast across rows).

  • xnew (torch.Tensor) – Shape (P,) or (D, P) (or generally (1, P) broadcastable). If xnew has a single row, it will be broadcast to the effective batch size determined by x and y.

  • out (torch.Tensor, optional) – Optional output buffer. If provided, must have numel == D_eff * P. The returned tensor will be a view of out with shape (D_eff, P). If x and y are both 1D and xnew is 1D, output is reshaped back to (P,).

  • outside ({"zero", "clamp"}, default="zero") – Out-of-bounds handling: - “zero”: values with xnew < x_min or xnew > x_max are set to 0 - “clamp”: values outside are clamped to endpoint values y_min / y_max

  • uniform ({"never", "auto", "always"}, default="auto") – Whether to use the uniform-grid fast path (O(1) interval selection). - “never”: always use searchsorted (O(log N) interval selection) - “auto”: use uniform fast path if x is uniformly spaced (per row) - “always”: assume x is uniformly spaced; raise ValueError if not

  • uniform_rtol (float, default=1e-5) – Relative tolerance for uniformity check (when uniform=”auto”).

  • uniform_atol (float, default=1e-7) – Absolute tolerance for uniformity check (when uniform=”auto”).

Returns:

ynew – Interpolated values. Shape matches xnew in the common cases:

  • if x,y,xnew are 1D -> (P,)

  • if batched -> typically (D_eff, P)

  • special case: if x,y are single-row and xnew has multiple rows, the output is reshaped back to match xnew’s original 2D shape.

Return type:

torch.Tensor

interp1d_uniform(x, y, xnew, out=None, *, outside='zero')[source]#

Uniform-grid 1D linear interpolation for PyTorch with batched support.

Same calling convention as interp1d(x,y,xnew,…) but assumes x is uniformly spaced per row (if batched). Uses arithmetic indexing, not searchsorted.

Parameter sweeps and tensor shapes#

These helpers construct flattened parameter grids and align one-dimensional parameters with model tensors without materializing an intermediate meshgrid.

cartesian_product(*seqs, dtype=None, device=None, require_1d=True, return_stacked=False)[source]#

Compute a Cartesian product over 1D numerical sequences and return 1D expanded tensors.

This function takes an arbitrary number of 1D sequences (Python lists/tuples, NumPy arrays, or PyTorch tensors) and returns the Cartesian product “grid” as separate 1D tensors (one per input), each of length:

N = prod_i len(seqs[i])

The returned tensors correspond to the flattened coordinates of the full Cartesian product, without constructing an intermediate k-dimensional meshgrid.

Parameters:
  • *seqs (array-like) –

    Arbitrarily many 1D numerical sequences. Each element may be a list, tuple, NumPy array, or torch.Tensor.

    If require_1d=True, each sequence must be 1D (or scalar). Scalars are treated as length-1 sequences.

  • dtype (torch.dtype, optional) –

    Output dtype. If None, a common promoted dtype is inferred from inputs using PyTorch type promotion rules.

    Note: integer + float mixes will promote to float; float32 + float64 mixes will promote to float64, etc.

  • device (torch.device or str, optional) –

    Output device. If None:
    • if any input is a torch.Tensor, the device of the first torch.Tensor is used (and all torch.Tensor inputs must already be on the same device), otherwise

    • CPU is used.

  • require_1d (bool, default=True) – If True, enforce that each input is 1D (or scalar). If False, each input is flattened via .reshape(-1).

  • return_stacked (bool, default=False) – If False (default), return a tuple of k tensors, each shape (N,). If True, return a single tensor of shape (N, k) equivalent to torch.stack(outputs, dim=-1).

Returns:

outputs –

If return_stacked=False:

A tuple (x0, x1, …, x{k-1}) where each xi is a 1D tensor of shape (N,) representing the i-th coordinate of the Cartesian product.

If return_stacked=True:

A tensor of shape (N, k), where column i is the i-th coordinate tensor.

Return type:

tuple[torch.Tensor, …] or torch.Tensor

Notes

Ordering#

The ordering matches the standard “nested loops” with the last sequence varying fastest:

>>> for a0 in seq0:
...   for a1 in seq1:
...     ...
...       for a{k-1} in seq{k-1}:
...         emit (a0, a1, ..., a{k-1})

Memory#

This function materializes k outputs of length N, which is unavoidable if you want the full Cartesian product explicitly. It avoids constructing an intermediate k-dimensional meshgrid (which can be significantly larger).

Autograd#

If any input is a torch.Tensor requiring gradients, the outputs remain differentiable w.r.t. those inputs. Repeated elements will accumulate gradients accordingly.

Examples

Basic usage:

>>> x, y = cartesian_product([1, 2], [10, 20, 30])
>>> x
tensor([1, 1, 1, 2, 2, 2])
>>> y
tensor([10, 20, 30, 10, 20, 30])

Three sequences:

>>> a, b, c = cartesian_product(torch.tensor([0., 1.]), [5, 6], np.array([9, 10, 11]))
>>> a.shape, b.shape, c.shape
(torch.Size([12]), torch.Size([12]), torch.Size([12]))

Stacked output:

>>> grid = cartesian_product([1, 2], [10, 20], return_stacked=True)
>>> grid
tensor([[ 1, 10],
        [ 1, 20],
        [ 2, 10],
        [ 2, 20]])

Empty sequence yields empty outputs:

>>> x, y = cartesian_product([], [1, 2, 3])
>>> x.shape, y.shape
(torch.Size([0]), torch.Size([0]))
add_dims_as_necessary(a, b)[source]#

Reshape a scalar or vector so that it broadcasts against b.

Scalars are returned unchanged. For a vector, the first dimension of b whose size matches the vector length is selected and singleton dimensions are inserted around it. The returned tensor is a broadcast-ready view; it is not expanded to the shape of b.

Parameters:
  • a (torch.Tensor) – A scalar or one-dimensional tensor.

  • b (torch.Tensor) – Tensor whose shape determines the desired alignment.

Returns:

a itself when scalar, or a reshaped view of a when it is a vector. Device, dtype, and autograd history are preserved.

Return type:

torch.Tensor

Raises:

ValueError – If a has more than one dimension or no dimension of b matches the vector length.

NEURON morphology paths#

The path helpers operate on connected NEURON Section trees. They return sections in traversal order and return None when no qualifying path exists.

path_sections(a, b)[source]#

Return the unique simple section path from a to b.

The returned Python list includes both endpoints and is ordered from a to b. If the sections belong to disconnected trees, return None.

path_via(a: _SectionLike, b: _SectionLike, c: _SectionLike, *, return_sectionlist: Literal[False] = False) → list[_SectionLike] | None[source]#
path_via(a: _SectionLike, b: _SectionLike, c: _SectionLike, *, return_sectionlist: Literal[True]) → _SectionListLike | None

Return the simple path from a to b when it passes through c.

Because NEURON sections form a tree, there is exactly one simple path between connected sections. Return None when a and b are disconnected or when their path does not contain c.

Parameters:
  • a (_SectionLike) – Endpoints of the requested path.

  • b (_SectionLike) – Endpoints of the requested path.

  • c (_SectionLike) – Section that the path must contain.

  • return_sectionlist (bool) – When true, return a NEURON h.SectionList instead of a Python list. Ordering and endpoint inclusion are otherwise unchanged.

Finite-element interpolation#

class PreparedInterp3dFEM(mesh, values, *, kind='node', out_fill=nan, th_indices=None, squeeze=True, field_name='', dtype=None, device=None, learnable_values=False, values_requires_grad=True, tag_states=None)[source]#

Mesh-guided tetrahedral FEM interpolator compatible with SimNIBS-style NodeData.interpolate_scattered and ElementData.interpolate_scattered.

This module deliberately uses the mesh’s own tetrahedron point-location routine during forward and then performs the value gathering/blending in PyTorch. That preserves the high-quality mesh-guided behavior of the original methods:

  • node data: barycentric interpolation inside the containing tetrahedron;

  • element data, method="assign": assign the containing tetrahedron’s value;

  • element data, method="linear", continuous=True: recover element data to nodes once with ElementData.elm_data2node_data and then use node-data barycentric interpolation;

  • element data, method="linear", continuous=False: perform the same tag-wise superconvergent patch recovery as ElementData.interpolate_scattered and interpolate with the recovered nodal field of the containing tag.

Parameters:
  • mesh (object) – A mesh object implementing the relevant mesh_io.Msh API: find_tetrahedron_with_points, nodes.find_closest_node, find_closest_element, elm.node_number_list, elm.tag1, and elm.tetrahedra.

  • values (array-like or torch.Tensor) – Nodal values for kind="node" or element values for kind="element_assign". For kind="element_linear_discontinuous" this is used only for the outside out_fill="nearest" behavior; tag-wise recovered nodal values must be provided via tag_states.

  • kind ({"node", "element_assign", "element_linear_discontinuous"}) – Prepared interpolation regime.

  • out_fill (float or "nearest", default=np.nan) – Outside-volume policy, matching the mesh_io.py methods.

  • th_indices (array-like, optional) – One-based tetrahedron/element numbers to consider as the valid volume. Tetrahedra outside this set are treated as outside.

  • squeeze (bool, default=True) – Match the squeeze behavior of the original methods.

  • learnable_values (bool, default=False) – Store values as a parameter. Supported for kind="node" and kind="element_assign". For tag-wise element-linear interpolation, use the classmethod defaults unless you intentionally want only outside-nearest element values to be learnable.

Notes

Gradients flow to stored values through the PyTorch gather/blend operations. Gradients do not flow through the discrete tetrahedron search, and barycentric coordinates are computed by the mesh’s NumPy/Cython locator, matching the source implementation rather than providing differentiability with respect to query coordinates.

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

Build an interpolator from a mesh_io.NodeData-like object.

The returned module reproduces node_data.interpolate_scattered(points, out_fill=out_fill, squeeze=squeeze, th_indices=th_indices) for the same mesh and points, up to normal floating-point roundoff.

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

Build an interpolator from a mesh_io.ElementData-like object.

This mirrors ElementData.interpolate_scattered:

  • method='assign' stores element values and assigns containing-tet values in forward.

  • method='linear', continuous=True performs the same global elm_data2node_data recovery once and then returns a node-data FEM interpolator using the recovered nodal field.

  • method='linear', continuous=False performs tag-wise recovery once and selects the containing tetrahedron’s tag-specific nodal field in forward.

forward(points, *, out_fill=None, squeeze=None, th_indices=None, out=None)[source]#

Interpolate at query points.

Parameters:
  • points (torch.Tensor) – Query coordinates with shape (..., 3). They may live on CPU or GPU; point-location is performed by the mesh implementation on a detached CPU copy, and the output is returned on the module value buffers’ device.

  • out_fill (float or "nearest", optional) – Per-call outside policy override. Defaults to the constructor setting.

  • squeeze (bool, optional) – Per-call squeeze override. Defaults to the constructor setting.

  • th_indices (array-like, optional) – Per-call valid tetrahedron/element subset override. Defaults to the constructor setting. Passing this argument does not mutate the prepared object.

  • out (torch.Tensor, optional) – Optional output tensor.