I'm using interpolate.interp2d() to fit a 2-D spline over a function. How can I get the first derivative of the spline w.r.t. each of the dependent variables? Here is my code so far, Z are the descrete points on a mesh-grid that I have
from scipy import interpolate
YY, XX = np.meshgrid(Y, X)
f = interpolate.interp2d(AA, XX, Z, kind='cubic')
So, I need df/dx and df/dy. Note also that my Y-grid is not evenly spaced. I guess I can numerically differentiate Z and then fit a new spline, but it seemed like too much hassle. Is there an easier way?
You can differentiate the output of interp2d
by using the function bisplev
on the tck
property of the interpolant with the optional arguments dx
and dy
.
If you've got some meshed data which you've interpolated:
X = np.arange(5.)
Y = np.arange(6., 11)
Y[0] = 4 # Demonstrate an irregular mesh
YY, XX = np.meshgrid(Y, X)
Z = np.sin(XX*2*np.pi/5 + YY*YY*2*np.pi/11)
f = sp.interpolate.interp2d(XX, YY, Z, kind='cubic')
xt = np.linspace(X.min(), X.max())
yt = np.linspace(Y.min(), Y.max())
then you can access the appropriate structure for bisplev
as f.tck
: the partial derivative of f
with respect to x
can be evaluated as
Z_x = sp.interpolate.bisplev(xt, yt, f.tck, dx=1, dy=0)
Edit: From this answer, it looks like the result of interp2d
can itself take the optional arguments of dx
and dy
:
Z_x = f(xt, yt, dx=1, dy=0)