Python Scipy Interpolate

This Python Scipy tutorial explains, Python Scipy Interpolate to interpolate the one, two, three, and multidimensional data using different methods like interpn1d and etc. We will also cover the following topics.

  • Python Scipy Interpolate 1d
  • How to interpolate 2d data in Scipy
  • How to interpolate griddata in Python Scipy
  • Python Scipy Interpolate Cubic Spline
  • How to interpolate using radial basis functions
  • Python Scipy Interpolate Interpn
  • Python Scipy Interpolate Nearest

Python Scipy Interpolate 1d

The Python Scipy contains a class interp1d() in a module scipy.interpolate that is used for 1-D function interpolation.

The syntax is given below.

scipy.interpolate.interp1d(x, y, kind='linear', axis=- 1, copy=True, bounds_error=None, fill_value=nan, assume_sorted=False)

Where parameters are:

  • x(array_data): A real values 1-D array.
  • y(array_data): A real value N-D array. It is necessary for the length of y along the interpolation axis to match the length of x.
  • kind(int, string): Specifies the type of interpolation in the form of a string or an integer, along with the order of the spline interpolator to be used. The string must fall into one of the following categories: linear, nearest, nearest-up, zero, slinear, quadratic, cubic, previous, or next. The terms “zero,” “slinear,” “quadratic,” and “cubic” denote spline interpolations of the zeroth, first, second, or third order; “previous,” “next,” and “nearest” simply return the previous or next value of the point; “nearest-up,” which rounds up, and “nearest,” which rounds down, are used when interpolating half-integers (such as 0.5, 1.5). Linear is the default.
  • axis(int): Specifies the y-axis that will be used for interpolation. The final axis of y is the interpolation’s default.
  • copy(boolean): If True, x and y are internally copied by the class. References to x and y are utilised if False. Copy is the default action.
  • bounds_error(boolean): If true, each time interpolation is tried on a value outside of the range of x, a ValueError is raised (where extrapolation is necessary). If False, the fill value is allocated to out-of-bounds values. Errors are raised by default unless fill value=”extrapolate” is specified.
  • fill_value(array_data, extrapolate): If true, each time interpolation is tried on a value outside of the range of x, a ValueError is raised (where extrapolation is necessary). If False, the fill value is allocated to out-of-bounds values. Errors are raised by default unless fill value=”extrapolate” is specified.
  • assume_sorted(boolean): If False, the values of x are sorted first and can be in any order. If True, x must be an array of values that increase monotonically.

Let’s take an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import numpy as np

Create x and y data and pass it to the method interp1d() to return the function using the below code.

x_ = np.arange(0, 15)
y_ = np.exp(-x_/4.0)
f_ = interp1d(x_, y_)

Plot the above-returned function with the new data using the below code.

xnew_ = np.arange(0, 14, 0.1)
ynew_ = f_(xnew_)
plt.plot(x_, y_, 'o', xnew_, ynew_, '-')
plt.show()
Python Scipy Interpolate 1d
Python Scipy Interpolate 1d

This is how to interpolate the one-dimensional array using the class interp1d() of Python Scipy.

Read Python Scipy Normal Test

Python Scipy Interpolate Griddata

The Python Scipy has a method griddata() in a module scipy.interpolate that is used for unstructured D-D data interpolation.

The syntax is given below.

scipy.interpolate.griddata(points, values, xi, method='linear', fill_value=nan, rescale=False)

Where parameters are:

  • points: Coordinates of a data point.
  • values: It is data values.
  • xi: Points where data can be interpolated.
  • method: Technique for interpolation like cubic, linear, nearest.
  • fill_value(float): Value used as a stand-in for requested points that are outside the convex hull of the input points. If nothing is given, nan is used as the default. In relation to the “nearest” technique, this option has no impact.
  • rescale(boolean): Interpolation is done after points have been rescaled to the unit cube. If any of the input dimensions contain units that are incommensurable and differ by large orders of magnitude, this is helpful.
READ:  Matplotlib set y axis range

The method griddata() returns ndarray which interpolated value array.

Let’s take an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

Think about interpolating the 2-D function as shown below.

def fun(x_, y_):
    return x_*(1-x_)*np.cos(3*np.pi*x_) * np.sin(3*np.pi*y_**2)**2

on a [0, 1]x[0, 1] grid.

grid_x_, grid_y_ = np.mgrid[0:1:100j, 0:1:200j]

yet we only have 1000 data points where we know its values.

rng_ = np.random.default_rng()
points_ = rng.random((1000, 2))
values_ = fun(points_[:,0], points_[:,1])

Griddata can be used to accomplish this; in the section below, we test each interpolation technique.

grid_z0_ = interpolate.griddata(points_, values_, (grid_x_, grid_y_), method='nearest')
grid_z1_ = interpolate.griddata(points_, values_, (grid_x_, grid_y_), method='linear')
grid_z2_ = interpolate.griddata(points_, values_, (grid_x_, grid_y_), method='cubic')

As can be seen, all approaches recreate the precise result to some extent, but for this smooth function, the piecewise cubic interpolant performs the best.

plt.subplot(221)
plt.imshow(fun(grid_x_, grid_y_).T, extent=(0,1,0,1), origin='lower')
plt.plot(points_[:,0], points_[:,1], 'k.', ms=1)
plt.title('Original')
plt.subplot(222)
plt.imshow(grid_z0_.T, extent=(0,1,0,1), origin='lower')
plt.title('Nearest')
plt.subplot(223)
plt.imshow(grid_z1_.T, extent=(0,1,0,1), origin='lower')
plt.title('Linear')
plt.subplot(224)
plt.imshow(grid_z2_.T, extent=(0,1,0,1), origin='lower')
plt.title('Cubic')
plt.gcf().set_size_inches(6, 6)
plt.show()
Python Scipy Interpolate Griddata
Python Scipy Interpolate Griddata

This is how to interplate the unstructured D-D data using the method griddata() of Python Scipy.

Read Python Scipy Mann Whitneyu

Python Scipy Interpolate 2d

The Python Scipy contains a class interp2d() in a module scipy.interpolate that is used for a 2-D grid of interpolation.

scipy.interpolate.interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None)[source]

Where parameters are:

  • x,y(array_data): Coordinates for data points are defined using arrays. If the points are on a regular grid, x and y can be used to define the column and row coordinates, respectively.
  • z(array_data): The interpolation values for the function at the data points. If z is a multidimensional array, “Fortran-ordering (order=’F’)” is used to flatten it before usage. If x and y define the column and row coordinates, the length of a flattened z array is “len(x)*len(y)”; otherwise, it is “len(z) == len(x) == len(y)”.
  • kind(quintic, linear, cubic): The appropriate spline interpolation type. Linear is the default.
  • copy(boolean): If True, internal copies of x, y, and z are made by the class. References may be used if False. Copy is the default action.
  • bounds_error(boolean): If True, a ValueError is raised whenever interpolated values are requested outside of the range of the input data (x, y). Fill value is utilised if False.
  • fill_value(number): The value to use for points outside the interpolation domain if specified. Values beyond the domain are extrapolated using nearest-neighbour extrapolation if missing (None).

Let’s take an example by following the below steps:

Import the required libraries or methods using the below code.

from scipy.interpolate import interp2d
import matplotlib.pyplot as plt
import numpy as np

Create a 2-D grid and do interpolation on it.

x_ = np.arange(-4.01, 4.01, 0.25)
y_ = np.arange(-4.01, 4.01, 0.25)
xx_, yy_ = np.meshgrid(x_, y_)
z_ = np.sin(xx_**2+yy_**2)
f_ = interp2d(x_, y_, z_, kind='cubic')

Plot the outcome using the interpolation function we just obtained using the below code.

xnew_ = np.arange(-4.01, 4.01, 1e-2)
ynew_ = np.arange(-4.01, 4.01, 1e-2)
znew_ = f_(xnew_, ynew_)
plt.plot(x_, z_[0, :], 'ro-', xnew_, znew_[0, :], 'b-')
plt.show()
Python Scipy Interpolate 2d
Python Scipy Interpolate 2d

This is how to interpolate over a two-dimensional array using the class interp2d() of Python Scipy.

Read Python Scipy Stats Poisson

Python Scipy Interpolate Cubic Spline

The Python Scipy has a class CubicSpline() in a module scipy that interpolate the data using cubic splines. Use a piecewise cubic polynomial that is twice continuously differentiable to interpolate data. The outcome is shown as a PPoly instance with breakpoints that match the supplied data.

READ:  Attributeerror: Module 'keras.backend' has no attribute 'get_session'

The syntax is given below.

scipy.interpolate.CubicSpline(x, y, axis=0, bc_type='not-a-knot', extrapolate=None)

Where parameters are:

  • x(array_data): 1-dimensional array storing the independent variable’s values. Real, finite, and strictly growing values are required.
  • y(array_data): Array holding the dependent variable’s values Regardless matter how many dimensions it has, the length along the axis (see below) must be equal to the length of x. Values must have an end.
  • axis(int): Axis that y is thought to vary along. In other words, the values for x[i] are np.take(y, I axis=axis).
  • bc_type(string, tuple): Type of boundary condition. To ascertain each segment’s polynomial coefficients, two additional equations that are provided by the boundary conditions are needed.
  • extrapolate(periodic, boolean): If bool decides whether to return NaNs or extrapolate to out-of-bounds points using the first and last intervals. Periodic extrapolation is employed if the term is “periodic”. Extrapolate is set to ‘periodic’ if bc type=’periodic’ if None (default) and to True otherwise.

Import the required libraries or methods using the below code.

from scipy.interpolate import CubicSpline
import matplotlib.pyplot as plt
import numpy as np

Let’s see how sampled sinusoid is interpolated using a cubic spline using the below code.

x_ = np.arange(10)
y_ = np.sin(x_)
cs_ = CubicSpline(x_, y_)

Plot the above data using the new data.

xs_ = np.arange(-0.5, 9.6, 0.1)
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.plot(x_, y_, 'o', label='data')
ax.plot(xs_, np.sin(xs_), label='true')
ax.plot(xs_, cs_(xs_), label="S")
ax.plot(xs_, cs_(xs_, 1), label="S'")
ax.plot(xs_, cs_(xs_, 2), label="S''")
ax.plot(xs_, cs_(xs_, 3), label="S'''")
ax.set_xlim(-0.5, 9.5)
ax.legend(loc='lower left', ncol=2)
plt.show()
Python Scipy Interpolate Cubic Spline
Python Scipy Interpolate Cubic Spline

This is how to interpolate the data using the method CubicSpline() of Python Scipy.

Read Python Scipy Stats Skew

Python Scipy Interpolate RBF

The Python Scipy has a class Rbf() in a module scipy.interpolate for interpolating functions from N-D scattered data to an M-D domain using radial basis functions.

The syntax is given below.

scipy.interpolate.Rbf(*args, **kwargs)

Where parameters are:

  • *args(array_data): The coordinates of the nodes are x, y, z,…, d, and the array of values at the nodes is d.
  • function(string): The radial basis function, with the default being “multiquadric,” is based on the radius, r, provided by the norm (default being Euclidean distance).
  • epsilon(float): Gaussian or multiquadrics functions provide an adjustable constant that, by default, is set to the approximate average distance between nodes (which is a good start).
  • smooth(float): Values higher than zero improve the approximation’s smoothness. When interpolation is set to 0, the function always passes through the nodal points.
  • norm(string): A function that takes an array of positions (x, y, z,…) as inputs and returns the “distance” between two points as an array of distance. For instance, the default setting is “euclidean,” which produces a matrix of the distances between each point in x1 and each point in x2, for example. The documentation for “scipy.spatial.distances.cdist” contains additional options.
  • mode(string): The interpolation mode can be either “1-D” (the default) or “N-D.” When it is “1-D,” the data d is treated as 1-D and internally flattened. The data d is taken to be an array of shapes (n samples, m) when it is “N-D,” where m is the dimension of the target domain.

Let’s see with an example by following the below steps:

Import the required libraries or methods using the below python code.

from scipy import integrate
import numpy as np

Create an instance of a radial basis function interpolator using the below code.

rng_ = np.random.default_rng()
x_, y_, z_, d_ = rng_.random((4, 40))
rbfi_ = interpolate.Rbf(x_, y_, z_, d_)

Let’s see the interpolated values using the below code.

xi_ = yi_ = zi_ = np.linspace(0, 1, 20)
di_ = rbfi_(xi_, yi_, zi_) 
di_.shape
Python Scipy Interpolate RBF
Python Scipy Interpolate RBF

This is how to interpolate the data using the radial basis functions like Rbf() of Python Scipy.

Read Python Scipy Kdtree

READ:  Attributeerror module 'tensorflow' has no attribute 'summary'

Python Scipy Interpolate Interpn

The Python Scipy has a method interpn() in a module scipy.interpolate that performs interpolation in several dimensions on rectilinear or regular grids.

This function only supports rectilinear grids, which are rectangular grids with even or uneven spacing, so strictly speaking, not all regular grids are supported.

The syntax is given below.

scipy.interpolate.interpn(points, values, xi, method='linear', bounds_error=True, fill_value=nan)

Where parameters are:

  • points(ndarray float): The n-dimensional regular grid is defined by the points. Each dimension’s points must absolutely ascend or descend.
  • values(array_data): The data in n dimensions in a regular grid. It is possible to accept complex data.
  • xi(ndim): The location of the sample points for the gridded data.
  • method(string): The interpolation technique to use The terms “linear,” “nearest,” and “splinef2d” are supported. Only 2-dimensional data is accepted for “splinef2d”.
  • bounds_error(boolean): If True, a ValueError is raised whenever interpolated values are requested outside of the range of the input data (x, y). Fill value is utilised if False.
  • fill_value(number): The value to use for points outside the interpolation domain if specified. Values beyond the domain are extrapolated using nearest-neighbour extrapolation if missing (None).

The method interpn() returns values_x(values interpolated at the input locations) of type ndarray.

Let’s take an example and apply a straightforward example function on the points of a standard 3-D grid.

Import the required libraries or methods using the below python code.

from scipy import interpolate
import numpy as np
def val_fun_3d(x_, y_, z_):
    return 2 * x_ + 2 * y_ - z_
x_ = np.linspace(0, 3, 4)
y_ = np.linspace(0, 4, 5)
z_ = np.linspace(0, 5, 6)
points_ = (x_, y_, z_)
values_ = val_fun_3d(*np.meshgrid(*points_, indexing='ij'))

At a specific location, evaluate the interpolating function using the below code.

point_ = np.array([2.20, 3.10, 1.12])
print(interpolate.interpn(points_, values_, point_))
Python Scipy Interpolate Interpn
Python Scipy Interpolate Interpn

This is how to interpolate the multidimensional data using the method interpn() of Python Scipy.

Read Python Scipy Eigenvalues

Python Scipy Interpolate Nearest

The class NearestNDInterpolator() of module scipy.interpolate in Python Scipy Which is used to Interpolate the nearest neighbour in N > 1 dimensions.

The syntax is given below.

scipy.interpolate.NearestNDInterpolator(x, y, rescale=False, tree_options=None)

Where parameters are:

  • x(Npoints, Ndims): Coordinates of a data point.
  • y(Npoints): It is data values.
  • rescale(boolean): Prior to applying interpolation, rescale the points to the unit cube. If some of the input dimensions have incommensurable units or deviate by large orders of magnitude, this is helpful.
  • tree_options: Options given to the cKDTree.

Let’s take an example by following the below steps:

Import the required libraries or methods using the below code.

from scipy.interpolate import interp2d
import matplotlib.pyplot as plt
import numpy as np

Generate a grid using the below code.

rng = np.random.default_rng()
x_ = rng.random(10) - 0.5
y_ = rng.random(10) - 0.5
z_ = np.hypot(x_, y_)
X_ = np.linspace(min(x_), max(x_))
Y_ = np.linspace(min(y_), max(y_))
X_, Y_ = np.meshgrid(X_, Y_) 

Now use the above 2d grid for interpolation using the below code.

interp_ = interpolate.NearestNDInterpolator(list(zip(x_, y_)), z_)
Z_ = interp_(X_, Y_)
plt.pcolormesh(X_, Y_, Z_, shading='auto')
plt.plot(x_, y_, "ok", label="input point")
plt.legend()
plt.colorbar()
plt.axis("equal")
plt.show()
Python Scipy Interpolate Nearest
Python Scipy Interpolate Nearest

This is how to interpolate the nearest neighbour in N > 1 dimensions using the method NearestNDInterpolator() of Python Scipy.

In this Python tutorial, we learned Python Scipy Interpolate and the below topics.

  • Python Scipy Interpolate 1d
  • How to interpolate 2d data
  • How to interpolate griddata
  • Python Scipy Interpolate Cubic Spline
  • How to interpolate using radia basis functions
  • Python Scipy Interpolate Interpn
  • Python Scipy Interpolate Nearest

You may like the following Python Scipy tutorials: