Interpolation with scipy

TODO

  • ...

In [ ]:
%matplotlib inline

Import modules and initialize data


In [ ]:
import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt

In [ ]:
xmin, xmax = 0., 4*np.pi

x = np.linspace(xmin, xmax, 10)
y = np.sin(x)

x2 = np.linspace(xmin, xmax, 100)

Linear interpollation


In [ ]:
# Linear interpolation with extrapolation
f = scipy.interpolate.interp1d(x, y,
                               kind='linear',
                               fill_value="extrapolate")

y2 = f(x2)

plt.plot(x, y, ":b", label="original")
plt.plot(x2, y2, "-r", label="interpollated")
plt.legend();

1-D Splines


In [ ]:
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splrep.html#scipy.interpolate.splrep
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splprep.html#scipy.interpolate.splprep

spl = scipy.interpolate.splrep(x, y)

y2 = scipy.interpolate.splev(x2, spl)

plt.plot(x, y, ":b", label="original")
plt.plot(x2, y2, "-r", label="interpollated")
plt.legend();

In [ ]:
spl = scipy.interpolate.splrep(x, y,
                               xb=x[0], xe=x[-1],   # The interval to fit
                               #s=0.,               # A smoothing factor
                               k=1)                 # The degree fo the spline fit

y2 = scipy.interpolate.splev(x2, spl)

plt.plot(x, y, ":b", label="original")
plt.plot(x2, y2, "-r", label="interpollated")
plt.legend();

Spline linear interpolation


In [ ]:
# Spline linear interpolation with extrapolation (should be the same than spline1...)
f = scipy.interpolate.interp1d(x, y,
                               kind='slinear',
                               fill_value="extrapolate")

y2 = f(x2)

plt.plot(x, y, ":b", label="original")
plt.plot(x2, y2, "-r", label="interpollated")
plt.legend();