Skip to content

brainhops._ext.interpol

B-spline interpolation of arrays, with NumPy or CuPy.

This package resamples arrays at arbitrary coordinates with B-splines of order 0 to 7, and computes the spline coefficients of an array. It is a port of torch-interpol 0.3.0, written for PyTorch, to array code that runs with NumPy or with CuPy. The functions run with the package of their input, so that an array on a GPU is processed on the GPU, and CuPy is only imported when it is installed. The package does not depend on brainhops.

The functions also take dask arrays, whose blocks may be NumPy or CuPy arrays, and then return dask arrays. Each task of the result runs the same code on the part of the input that it needs, and the results equal those of the whole arrays to rounding errors. Dask is only imported when an argument is a dask array.

Compared with scipy.ndimage.map_coordinates, pull takes one order and one boundary condition per axis, and takes batch axes, whose items it processes together rather than one at a time. Coordinates are in voxels, the last axis of the grid holds them, and the sample i of an axis lies at the coordinate i. As in torch-interpol, the grid has as many output spatial axes as coordinates, and its leading axes are batch axes that broadcast against those of the input.

Beyond the edges of the input, the values follow the boundary condition. The argument clip of pull sets margins, in voxels, beyond which the values are zero instead. It replaces the argument extrapolate of torch-interpol: extrapolate=False becomes clip=0, and extrapolate="edges" becomes clip=0.5.

A spline of order 2 or more does not pass through its coefficients. spline_coeff computes the coefficients of the spline that passes through the values of an array, and pull calls it when prefilter is true. These coefficients are exact for every boundary condition: sampling them at the integer coordinates with the same order and boundary gives back the values, to rounding errors.

The boundary condition says how the array continues beyond its edges, which matters near the edges for every order above 0. Each condition has several names: the name used by SciPy, when SciPy has the same condition, the names used by torch-interpol, and the name of the discrete transform whose implicit extension it is. The extensions of an array a b c d are as follows.

SciPy torch-interpol extension
grid-constant zero, zeros 0 0 0 [a b c d] 0 0 0
nearest replicate, nearest a a a [a b c d] d d d
mirror dct1, mirror d c b [a b c d] c b a
reflect dct2, reflect c b a [a b c d] d c b
grid-wrap dft b c d [a b c d] a b c
dst1, antimirror -b -a 0 [a b c d] 0 -d -c
dst2, antireflect -c -b -a [a b c d] -d -c -b

SciPy also accepts grid-mirror for reflect, and the package accepts it too. The SciPy modes constant and wrap are refused, because the package implements neither of them. The SciPy mode wrap is a shifted periodic extension, unlike the wrap of torch-interpol, which is grid-wrap, so the name is refused rather than read in either sense.

The prefilter of torch-interpol applied the filter of dct1 to the zero boundary and the filter of dct2 to the replicate boundary, and it returned its input unchanged for an axis of length 1. Its coefficients therefore did not interpolate the values near the edges, at every order for the zero boundary and from order 4 for the replicate boundary. The port computes them exactly, as explained in spline_coeff1d.

Functions:

spline_coeff

spline_coeff(
    input: Any,
    order: Any = 3,
    bound: Any = "reflect",
    ndim: int | None = None,
) -> Any

Compute the spline coefficients of an array along its last axes.

The prefilter runs along each of the last ndim axes in turn, with the order and the boundary of that axis. The coefficients are those whose spline, sampled at the integer coordinates with pull, gives back the input exactly. The computation runs with the package of the input, NumPy or CuPy. A dask array gives a dask array with the same chunks, computed as explained in spline_coeff1d.

Parameters:

Name Type Description Default
input array

The values, with shape (*batch, *spatial).

required
order int or sequence of int

The spline order, from 0 to 7, for all axes or for each of the spatial axes.

3
bound str or sequence of str

The boundary condition, for all axes or for each of the spatial axes, by any name of the table in the documentation of the package.

"reflect"
ndim int

The number of spatial axes. By default, it is the length of order or bound when one of them is a sequence, and all the axes of the input otherwise.

None

Returns:

Type Description
array

The coefficients, with the shape of the input and a floating data type. Its axes may be laid out in memory in another order than theirs, which pull reads without a copy.

Raises:

Type Description
ValueError

spline_coeff1d

spline_coeff1d(
    input: Any,
    order: int = 3,
    bound: str = "reflect",
    axis: int = -1,
) -> Any

Compute the spline coefficients of an array along one axis.

The coefficients are those whose spline, sampled at the integer coordinates with pull and the same order and boundary, gives back the input exactly. The computation runs with the package of the input, NumPy or CuPy.

For the boundaries mirror, reflect, grid-wrap, antimirror and antireflect, the coefficients are computed with the recursive filter of torch-interpol, which makes one causal and one anticausal pass over the axis for each pole of the spline. Each pass starts from a value that is exact for the boundary, so that no correction is needed. The zero and the replicate boundaries use the filters of antimirror and reflect, which are exact for them at orders 2 and 3. From order 4, the coefficients near each edge are then corrected exactly, which costs a few multiply-adds per value within the first and last 39 to 63 samples, depending on the order. torch-interpol applied the filter of mirror to the zero boundary and the filter of reflect to the replicate boundary without a correction. Its coefficients were therefore wrong near the edges, at every order for the zero boundary and from order 4 for the replicate boundary.

A dask array gives a dask array with the same chunks. The coefficients of a chunk depend on the values within the horizon of the filter, from 23 samples at order 2 to 63 samples at order 7, beyond which the weight of a value is below 1e-17. Each chunk is therefore computed by one task, which runs the filter above on the chunk extended by the horizon on each side, and keeps the chunk. The task reads all the chunks that overlap this window, however short they are, and the whole axis when the axis is short. At an edge of the array, the window keeps the boundary condition of the array. Where the window cuts the array, the boundary condition that the filter applies changes the coefficients of the chunk by less than their rounding errors, since the cut is at least the horizon away from the chunk.

Parameters:

Name Type Description Default
input array

The values, of any shape. An integer array is converted to float64.

required
order int

The spline order, from 0 to 7. Orders 0 and 1 return a copy of the input, since their splines pass through their coefficients.

3
bound str

The boundary condition, by any name of the table in the documentation of the package.

"reflect"
axis int

The axis to filter.

-1

Returns:

Type Description
array

The coefficients, with the shape of the input.

Raises:

Type Description
ValueError

pull

pull(
    input: Any,
    grid: Any,
    order: Any = 1,
    bound: Any = "reflect",
    clip: Any = None,
    prefilter: bool = False,
    strategy: str = "auto",
    block_size: int | None = None,
) -> Any

Interpolate an array at the coordinates of a grid.

Use this function to resample an image with a transformation: the grid holds, for each output voxel, the coordinates of the point of the input that it takes its value from. The interpolation is a B-spline of the given order, separately along each axis, and the boundary condition says how the input continues beyond its edges. The computation runs with the package of the arrays, NumPy or CuPy, and every intermediate array is created with that package.

Coordinates are in voxels, and the sample i of an axis lies at the coordinate i. The length ndim of the last axis of the grid is the number of spatial axes. The last ndim axes of the input are its spatial axes, and the ndim axes of the grid before its last one are the spatial axes of the output. A list of scattered points therefore needs a grid such as (npoints, 1, 1, 3) in three dimensions. The other, leading axes of the input and of the grid are batch axes, which broadcast against each other with the rules of NumPy. This convention is the one of torch-interpol.

Each output value is a sum over the order + 1 samples, or taps, that each axis reads. The code loops in Python over these taps and over blocks of the output, and each tap gathers the samples of all the points and batch items of a block at once. The two strategies differ in the size of the blocks:

  • The blocked strategy splits the output points, and the batch items when there are many, into blocks of at most block_size values, and adds all the taps of a block before it moves on to the next one. The indices and the weights of the taps are computed once per block of points and reused for all its batch items. With the default size, the arrays of a block stay in the cache of the processor, so that each tap reads and writes the cache instead of the main memory. On a processor, this made the resampling of volumes of 128 to 192 voxels per side 1.6 to 2.4 times faster than the batched strategy, and the temporary arrays take a few megabytes instead of hundreds.
  • The batched strategy makes a single block of all the points and all the batch items. Each step is then one operation on whole arrays, which suits a GPU, where every operation launches a kernel and the memory is fast, so that more blocks would only add launches. Its temporary arrays take about 2 * ndim * (order + 1) arrays of the size of the grid, for the indices and the weights, and two arrays of the size of the output.

The default strategy, "auto", is the blocked one for NumPy arrays and the batched one for CuPy arrays. Both give the same values.

When the input or the grid is a dask array, the function returns a dask array of the same values, which dask computes block by block. The output has the chunks of the grid along its spatial axes. Each block of the output is one task, which reads only the window of the input that its coordinates need, and runs the computation above on that window. With the prefilter, the coefficients of the window are computed from the values within a margin of 23 to 63 samples around it, depending on the order, which gives the coefficients of the whole input to rounding errors. The strategy and the block size apply to each block. For dask arrays, the default strategy is the batched one, because the many small operations of the blocked strategy are serialized by the lock of the Python interpreter under the threaded scheduler of dask. Dask is only imported when an argument is a dask array.

Order 0 takes the nearest sample, and a coordinate exactly halfway between two samples takes the upper one, as in SciPy. Outside the array, the tie is broken before the boundary condition is applied. SciPy applies mirror and reflect to the coordinate first, so that at exact ties beyond the edges, the two can take different samples.

Parameters:

Name Type Description Default
input array

The values, or the spline coefficients when prefilter is false and the order is 2 or more, with shape (*batch_input, *spatial_in).

required
grid array

The coordinates, with shape (*batch_grid, *spatial_out, ndim), where spatial_out has ndim axes.

required
order int or sequence of int

The spline order, from 0 to 7, for all axes or for each spatial axis.

1
bound str or sequence of str

The boundary condition, for all axes or for each spatial axis, by any name of the table in the documentation of the package.

"reflect"
clip float or sequence

The margins beyond which the output is zero. By default, every value is kept, and the boundary condition gives the values outside the input. A number sets the same margin below and above every axis. A pair (lower, upper) sets the margins of every axis, and a sequence of ndim pairs sets them for each spatial axis, in the order of the coordinates. A value is zero when one of its coordinates lies outside the closed interval [-lower, size - 1 + upper] of its axis, widened by 1e-5 voxel on each side so that rounding errors do not drop a coordinate that lies on a limit. The coordinates themselves are never clamped. A margin of 0 keeps the values up to the centres of the edge samples, and a margin of 0.5 up to their outer edges.

None
prefilter bool

Whether to compute the spline coefficients of the input first, with spline_coeff, so that the spline passes through the values of the input.

False
strategy (auto, blocked, batched)

How the computation is split, as explained above. The value "auto" chooses the blocked strategy for NumPy arrays and the batched one for CuPy arrays.

"auto"
block_size int

The largest number of values, that is, batch items times points, in each temporary array of the blocked strategy. A block also holds at most 16384 points. By default, it is 65536. The batched strategy ignores it.

None

Returns:

Type Description
array

The interpolated values, with shape (*batch, *spatial_out), where batch is the broadcast of batch_input and batch_grid. The data type is that of the input, or float64 for an integer input.

Raises:

Type Description
ValueError