linear_interpolator

odl.discr.discr_utils.linear_interpolator(f, coord_vecs)[source]

Return the linear interpolator for discrete function values.

Parameters:
fnumpy.ndarray

Function values that should be interpolated.

coord_vecssequence of numpy.ndarray

Coordinate vectors of the rectangular grid on which interpolation should be based. They must be sorted in ascending order. Usually they are obtained as grid.coord_vectors from a RectGrid.

Returns:
interpolatorfunction

Python function that will interpolate the given values when called with a point or multiple points (vectorized).

Examples

We interpolate a 1d function. If called with a single point, the interpolator returns a single value, and with multiple points at once, an array of values is returned:

>>> part = odl.uniform_partition(0, 2, 5)
>>> part.coord_vectors  # grid points
(array([ 0.2,  0.6,  1. ,  1.4,  1.8]),)
>>> f = [1.0, 2.0, 3.0, 4.0, 5.0]
>>> interpolator = linear_interpolator(f, part.coord_vectors)
>>> interpolator(0.3)  # 0.75 * 1 + 0.25 * 2 = 1.25
1.25
>>> # At 1.9, the value is interpolated between the last value 5.0 and
>>> # 0.0. The extra interpolation node is placed at the same distance
>>> # as the second-to-last, i.e., at 2.2. Hence, the interpolated value
>>> # is 0.75 * 5.0 + 0.25 * 0.0 = 3.75.
>>> interpolator([0.6, 1.3, 1.9])
array([ 2.  ,  3.75,  3.75])

In 2 dimensions, we can either use a (transposed) list of points or a meshgrid:

>>> part = odl.uniform_partition([0, 0], [1, 5], shape=(2, 4))
>>> part.coord_vectors  # grid points
(array([ 0.25,  0.75]), array([ 0.625,  1.875,  3.125,  4.375]))
>>> f = np.array([[1, 2, 3, 4],
...               [5, 6, 7, 8]],
...              dtype=float)
>>> interpolator = linear_interpolator(f, part.coord_vectors)
>>> interpolator([1, 1])  # single point
2.65
>>> x = np.array([[0.5, 2.0],
...               [0.0, 4.5],
...               [0.0, 3.0]]).T  # 3 points at once
>>> interpolator(x)
array([ 4.1 ,  1.8 ,  1.45])
>>> from odl.discr.grid import sparse_meshgrid
>>> mesh = sparse_meshgrid([0.0, 0.5, 1.0], [1.5, 3.5])
>>> interpolator(mesh)  # 3x2 grid of points
array([[ 0.85,  1.65],
       [ 3.7 ,  5.3 ],
       [ 2.85,  3.65]])