Skip to content Skip to sidebar Skip to footer

Differentiate A 2d Cubic Spline In Python

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 fa

Solution 1:

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)

Post a Comment for "Differentiate A 2d Cubic Spline In Python"