If all you need is a linear (a.k.a. broken line) interpolation, you can use
the numpy.interp routine. It takes two arrays of data to interpolate, x,
and y, and a third array, xnew, of points to evaluate the interpolation on:
One limitation of numpy.interp is that it does not allow controlling the
extrapolation. See the interpolation with B-Splines section
section for alternative routines which provide this kind of functionality.
Cubic splines
Of course, piecewise linear interpolation produces corners at data points,
where the linear pieces join. To produce a smoother curve, you can use cubic
splines, where the interpolating curve is made of cubic pieces with matching
first and second derivatives. In code, these objects are represented by instances of the
CubicSpline class. An instance is constructed with the x and
y arrays of data, and then it can be evaluated using the target xnew
values:
A CubicSpline object’s __call__ method accepts both scalar values and
arrays. It also accepts a second argument, nu, to evaluate the
derivative of order nu. As an example, we plot the derivatives of a spline:
Note that the first and second derivatives are continuous by construction, and
the third derivative jumps at data points.
Monotone interpolants
Cubic splines are by construction twice continuously differentiable. This may
lead to the spline function oscillating and ‘’overshooting’’ in between the
data points. In these situations, an alternative is to use the so-called
monotone cubic interpolants: these are constructed to be only once
continuously differentiable, and attempt to preserve the local shape implied
by the data. scipy.interpolate provides two objects of this kind:
PchipInterpolator and Akima1DInterpolator. To illustrate, let’s consider
data with an outlier:
B-splines form an alternative (though formally equivalent) representation of piecewise polynomials. This basis is generally more computationally stable than the power basis and is useful for a variety of applications which include interpolation, regression and curve representation. Details are given in the piecewise polynomials section, and here we illustrate their usage by constructing the interpolation of a sine function:
>>> x=np.linspace(0,3/2,7)>>> y=np.sin(np.pi*x)
To construct the interpolating objects given data arrays, x and y,
we use the make_interp_spline function:
This function returns an object which has an interface similar to that
of the CubicSpline objects. In particular, it can be evaluated at a data
point and differentiated:
>>> der=bspl.derivative()# a BSpline representing the derivative>>> importmatplotlib.pyplotasplt>>> xx=np.linspace(0,3/2,51)>>> plt.plot(xx,
Note that by specifying k=3 in the make_interp_spline call, we requested
a cubic spline (this is the default, so k=3 could have been omitted); the
derivative of a cubic is a quadratic:
>>> bspl.k,der.k(3, 2)
By default, the result of make_interp_spline(x,y) is equivalent to
CubicSpline(x,y). The difference is that the former allows several optional
capabilities: it can construct splines of various degrees (via the optional
argument k) and predefined knots (via the optional argument t).
Boundary conditions for the spline interpolation can be controlled by
the bc_type argument to make_interp_spline function and CubicSpline
constructor. By default, both use the ‘not-a-knot’ boundary
condition.
Non-cubic splines
One use of make_interp_spline is constructing a linear interpolant with
linear extrapolation since make_interp_spline extrapolates by default. Consider
Univariate interpolators accept not only one-dimensional y arrays, but also
y.ndim>1. The interpretation is that y is a batch of 1D data arrays: by
default, the zeroth dimension of y is the interpolation axis, and the trailing
dimensions are batch dimensions.
Consider a collection (a batch) of functions fj sampled at the points
xi. We can instantiate a single interpolator for all of these functions by
providing a two-dimensional array y such that y[i,j] records fj(xi).
Several notes are in order. First and foremost, the behavior here looks similar to
NumPy’s broadcasting, but differs in two respects:
The x array is expected to be 1D even if the y array is not: x.ndim==1
while y.ndim>=1. There is no broadcasting of x vs y.
By default, the trailing dimensions are used as batch dimensions, in contrast
to the NumPy convention of using the leading dimensions as batch dimensions.
Second, the interpolation axis can be controlled by an optional axis argument. The
example above uses the default value of axis=0. For a non-default values, the
following is true:
y.shape[axis]==x.size (otherwise an error is raised)
the shape of spl(xv) is y.shape[axis:]+xv.shape+y.shape[:axis]
So far we considered spline functions, where the data, y, is expected to
depend explicitly on the independent variable x—so that the interpolating
function satisfies f(xj)=yj. Spline curves treat
the x and y arrays as coordinates of points, pj on a
plane, and an interpolating curve which passes through these points is
parameterized by some additional parameter (typically called u). Note that
this construction readily generalizes to higher dimensions where
pj are points in an N-dimensional space.
Spline curves can be easily constructed using the fact that interpolation
functions handle multidimensional data arrays, as discussed in
the previous section.
The values of the parameter, u, corresponding to the data points, need to be
separately supplied by the user.
The choice of parametrization is problem-dependent and different parametrizations
may produce vastly different curves. As an example, we consider three
parametrizations of (a somewhat difficult) dataset, which we take from
Chapter 6 of Ref [1] listed in the BSpline docstring:
>>> x=[0,1,2,3,4,5,6]>>> y=[0,0,0,9,0,0,0]>>> p
We take elements of the p array as coordinates of seven points on the
plane, where p[:,j] gives the coordinates of the point
pj.
First, consider the uniform parametrization, uj=j:
>>> u_unif=x
Second, we consider the so-called chord length parametrization, which is
nothing but a cumulative length of straight line segments connecting the
data points:
uj=uj−1+∣pj−pj−1∣
for j=1,2,… and u0=0. Here ∣⋯∣ is the
length between the consecutive points on the plane.
>>> dp=p[:,1:]-p[:,:-1]# 2-vector distances between points>>> l=(dp**2).sum(axis=0)# squares of lengths of 2-vectors between points>>> u_chord=np.sqrt
Finally, we consider what is sometimes called the centripetal
parametrization: uj=uj−1+∣pj−pj−1∣1/2.
Due to the extra square root, the difference between consecutive values
will be smaller than for the chord length parametrization:
We note that scipy.interpolate does not support interpolation with missing
data. Two popular ways of representing missing data are using masked arrays of
the numpy.ma library, and encoding missing values as not-a-number, NaN.
Neither of these two approaches is directly supported in scipy.interpolate.
Individual routines may offer partial support, and/or workarounds, but in
general, the library firmly adheres to the IEEE 754 semantics where a NaN
means not-a-number, i.e. a result of an illegal mathematical operation
(e.g., division by zero), not missing.
There are two principal ingredients which affect the out-of-bounds behavior:
bc_type and extrapolate arguments. The former controls how the object
is constructed, and the latter controls how it is evaluated.
The bc_type parameter
For CubicSpline and make_interp_spline, the bc_type
construction-time argument controls the shape of the spline at its boundaries and
therefore also affects extrapolation. When bc_type="periodic", periodic boundary
conditions are enforced and the interpolant is smooth at the join point. For all other
values of bc_type, out-of-bounds behavior is controlled separately by the
extrapolate argument described below.
To illustrate, we compare several values of the constructor argument
for , including which produces a smooth
periodic interpolant:
The extrapolate constructor argument
All the interpolators listed above accept an extrapolate keyword at construction
time, which sets the default out-of-bounds behavior for all subsequent evaluations:
extrapolate=True (default for most): evaluate the boundary polynomial pieces;
extrapolate=False: return NaN;
extrapolate="periodic" (if supported): wrap the evaluation periodically.
The default is True for most interpolators, with two exceptions:
defaults to , and
forces the default to .
Overriding extrapolate per call
The extrapolate argument can also be passed at evaluation time (i.e. when
calling the interpolator object). Passing extrapolate=None (the default) means
“use the value that was set at construction time.” Passing any other value
overrides the construction-time setting for that call only:
The interp1d class in scipy.interpolate is a convenient method to
create a function based on fixed data points, which can be evaluated
anywhere within the domain defined by the given data using linear
interpolation. An instance of this class is created by passing the 1-D
vectors comprising the data. The instance of this class defines a
__call__ method and can therefore be treated like a function which
interpolates between known data values to obtain unknown values.
Behavior at the boundary can be
specified at instantiation time. The following example demonstrates
its use, for linear and cubic spline interpolation:
The ‘cubic’ kind of interp1d is equivalent to make_interp_spline, and
the ‘linear’ kind is equivalent to numpy.interp while also allowing
N-dimensional y arrays.
Another set of interpolations in interp1d is nearest, previous, and
next, where they return the nearest, previous, or next point along the
x-axis. Nearest and next can be thought of as a special case of a causal
interpolating filter. The following example demonstrates their use, using the
same data as in the previous example:
As mentioned, interp1d class is legacy: we have no plans to remove it; we
are going to keep supporting its existing usages; however
we believe there are better alternatives which we recommend using in new code.
Here we list specific recommendations, depending on the interpolation kind.
Linear interpolation,kind="linear"
The default recommendation is to use numpy.interp function. Alternatively,
you can use linear splines, , see
.
Note that using bc_type="periodic" (red curve) enforces equal derivatives at the
boundaries of the interpolation interval (x=0 and x=4), so that the resulting
interpolant extends smoothly as a periodic function.
On the contrary, using extrapolate="periodic" together with the default value for bc_type (the green curve) does not enforce any boundary conditions, and simply extends the interpolant
+ periodically outside the data domain. See CubicSpline extend the boundary conditions for an additional discussion of how different bc_type values affect the interpolant.
Akima1DInterpolator
False
bc_type="periodic"
extrapolate="periodic"
To illustrate, we consider PchipInterpolator with several values of the
extrapolate constructor argument:
Note that PchipInterpolator has no bc_type argument, so there is
no way to construct a truly periodic PCHIP interpolant. Using
extrapolate="periodic" only wraps evaluation at the domain boundaries
and makes no guarantees about smoothness at the join point, as visible in
the plot above.
First, we note that interp1d(x,y,kind='previous') is equivalent to
make_interp_spline(x,y,k=0).
More generally however, all these piecewise constant interpolation modes are
based on numpy.searchsorted. For example, the "nearest" mode is nothing but
>>> x=np.arange(8)>>> y=x**2>>> x_new=np.linspace(0,7,101)# input points>>> x_bds=x[:-1]/2.0+x[1:]/2.0# halfway points>>> idx=np.searchsorted(x_bds,x_new,side='left')>>> idx=np.clip(idx,0,len(x)-1)# clip the indices so that they are within the range of x indices.>>> importmatplotlib.pyplotasplt>>> plt.plot(x,y,'o')>>> plt.plot(x_new,y[idx],'--')>>> plt.show()
Other variants are similar, see the interp1dsource code
for details.