Multivariate data interpolation on a regular grid (RegularGridInterpolator)
Suppose you have N-dimensional data on a regular grid, and you
want to interpolate it. In such a case, RegularGridInterpolator can be
useful. Several interpolation strategies are supported: nearest-neighbor,
linear, and tensor product splines of odd degree.
Strictly speaking, this class efficiently handles data given on rectilinear
grids: hypercubic lattices with possibly unequal spacing between points.
The number of points per dimension can be different for different dimensions.
The following example demonstrates its use, and compares the interpolation results
using each method.
As expected, the higher degree spline interpolations are closest to the
true values, though are more expensive to compute than with linear
or nearest. The slinear interpolation also matches the linear
interpolation.
If your data is such that spline methods produce ringing, you may consider
using method="pchip", which uses the tensor product of PCHIP interpolators,
a PchipInterpolator per dimension.
If you prefer a functional interface opposed to explicitly creating a class instance,
the interpn convenience function offers the equivalent functionality.
Specifically, these two forms give identical results:
For data confined to an (N-1)-dimensional subspace of N-dimensional space, i.e.
when one of the grid axes has length 1, the extrapolation along this axis is
controlled by the fill_value keyword parameter:
>>> x=np.array([0,5,10])>>> y=np.array([0])>>> data=np.array([[0],[5],[10]])>>> rgi=RegularGridInterpolator((x,y),data,... bounds_error=False,fill_value=None)>>> rgi([(2,0),(2,1),(2,-1)])# extrapolates the value on the axisarray([2., 2., 2.])>>> rgi.fill_value=-101>>> rgi([(2,0),(2,1),(2,-1)])array([2., -101., -101.])
Batch dimensions of values
Suppose you have a vector function f(x)=y, where x and y are
vectors, potentially of different lengths, and you want to sample the function on a grid
of x values. One way to address this is to use the fact that RegularGridInterpolator
allows values with trailing dimensions.
In accordance with how 1D interpolators
interpret multidimensional arrays, the interpretation is
that the first N dimensions of the values arrays are data dimensions
(i.e. they correspond to the points defined by the grid argument), and the trailing
dimensions are batch axes. Note that this disagrees with the usual NumPy broadcasting
conventions, where broadcasting proceeds along the leading dimensions.
To illustrate:
>>> n=5# the number of batch components
>>> # make a 3D grid>>> x1=np.linspace(-np.pi,np.pi,10)>>> x2=np.linspace(0.0,np.pi,15)>>> x3=
In this example, we evaluated a batch of n=5 functions on a
three-dimensional grid. In general, multiple batching dimensions are allowed, and the
shape of the result follows by appending the batching shape (in this example, (5,))
to the shape of the input x (in this example, (1,)).
Uniformly spaced data
If you are dealing with data on Cartesian grids with integer coordinates, e.g.
resampling image data, these routines may not be the optimal choice. Consider
using scipy.ndimage.map_coordinates instead.
fromscipy.ndimageimportmap_coordinatesclassCartesianGridInterpolator:def__init__(self,points,values,method='linear'):self.limits=np.array([[min(x),max(x)]forxinpoints])self.values=np.asarray(values,dtype=float)self.order={'linear':1,'cubic':3,'quintic':5}[method]def__call__(self,xi):""" `xi` here is an array-like (an array or a list) of points. Each "point" is an ndim-dimensional array_like, representing the coordinates of a point in ndim-dimensional space. """# transpose the xi array into the ``map_coordinates`` convention# which takes coordinates of a point along columns of a 2D array.xi=np.asarray(xi).T# convert from data coordinates to pixel coordinatesns=self.values.shapecoords=[(n-1)*(val-lo)/(hi-lo)forval,n,(lo,hi)inzip(xi,ns,self.limits)]# interpolatereturnmap_coordinates(self.values,coords,order=self.order,cval=np.nan)# fill_value
This wrapper can be used as a(n almost) drop-in replacement for the
RegularGridInterpolator:
Note that the example above uses the map_coordinates boundary conditions.
Thus, results of the cubic and quintic interpolations may differ from
those of the RegularGridInterpolator.
Refer to scipy.ndimage.map_coordinates documentation for more details on
boundary conditions and other additional arguments.
Finally, we note that this simplified example assumes that the input data is
given in the ascending order.