Interpolation, padding - does the padding x value matter?
%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 matplotlib.pylab as plt
import scipy.interpolate as spi
x = np.arange(5)
# Some random numbers for the ys
y = np.array([-0.16001414, 0.88690672, 0.32057716, 0.09396015, 0.54394511])
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x10641df90>]
First we try a padding x value at -1, so 1 unit away from the first real value of x == 0
padded_x = np.r_[-1, x]
padded_y = np.r_[y[0], y]
interp = spi.interp1d(padded_x, padded_y, 'cubic')
interped = interp([-0.1, 0.5])
interped
array([-0.28503175, 0.4983204 ])
Now we try and padding x value of -0.1, much closer to the first real value of 0. We use the same padding value of y. The interpolated value for 0.5 is different in this case:
padded_x_close = np.r_[-0.1, x]
interp_closer = spi.interp1d(padded_x_close, padded_y, 'cubic')
interped_closer = interp_closer([-0.1, 0.5])
interped_closer
array([-0.16001414, 0.32943714])
We can see why by plotting the full interpolated time courses:
fine_time_short = np.linspace(-0.1, 4)
fine_time_long = np.linspace(-1, 4)
plt.plot(fine_time_long, interp(fine_time_long), 'r:', label='Distant padding')
plt.plot(padded_x, padded_y, 'go', fillstyle='none') # so we can see the +'s below
plt.plot(fine_time_short, interp_closer(fine_time_short), 'b:', label='Close padding')
plt.plot(padded_x_close, padded_y, 'k+')
plt.xlim([-1.2, 4.2])
plt.legend()
<matplotlib.legend.Legend at 0x106929dd0>
The nearness of the padding value dictates the sharpness of the curve after the next point, because the slope of the curve from the previous segment influences the slope of the next segments. This is in the nature of the spline interpolation we have used - the slope of the curve has to be the same just before and just after each data point.