Differentiate a 2d cubic spline in python

隐身守侯 提交于 2020-05-09 06:56:13

问题


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?


回答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)


来源:https://stackoverflow.com/questions/58608484/differentiate-a-2d-cubic-spline-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!