%pylab inline
Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.kernel.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'.
import numpy as np
import scipy.interpolate as spi
The data we have:
x = np.linspace(-np.pi, pi)
y = np.cos(x)
Plotted:
import matplotlib.pyplot as plt
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x105195ad0>]
A spline interpolating tuple:
t, c, k = spi.splrep(x, y, s=0)
k
3
This means the default spline was order 3.
t, c, k = spi.splrep(x, y, k=5, s=0)
k
5
We interpolate the values with splev
:
x_desired = x * 1.1 - 0.1 # to go a little out of range
new_y = spi.splev(x_desired, (t, c, k))
plt.plot(x_desired, new_y)
[<matplotlib.lines.Line2D at 0x10569f410>]
Noticed how the spline interpolated nicely beyond the borders of the data (the uptick at both ends).
We can also do 1D interpolation on a 2D array (we interpolate over the columns).
y2 = np.column_stack((np.cos(x), np.sin(x)))
y2.shape
(50, 2)
plt.plot(x, y2)
[<matplotlib.lines.Line2D at 0x105789c10>, <matplotlib.lines.Line2D at 0x105789e50>]
tck2 = spi.splmake(x, y2, order=5)
y2_new = spi.spleval(tck2, x_desired)
plt.plot(x_desired, y2_new)
plt.hold(True)
plt.plot(x, y2, ':')
[<matplotlib.lines.Line2D at 0x105792490>, <matplotlib.lines.Line2D at 0x1057b7e10>]
Notice nasty zeros outside the defined values for x
, y
. Happily enough for us, the original data (dashed lines) are right on top of the interpolated data, when they are within range.
There is a spline interpolator in scipy.ndimage
, but I'm not sure what it does. It seems to induce a shift in the signal.
import scipy.ndimage as spn
y2_new = spn.spline_filter1d(y2, order=5, axis=0)
plt.plot(x_desired, y2_new)
plt.hold(True)
plt.plot(x, y2, ':')
[<matplotlib.lines.Line2D at 0x1057cbf50>, <matplotlib.lines.Line2D at 0x105ac0ed0>]