Cubic interpolation with derivatives in numpy
Asked Answered
C

2

6

A recent immigrant to Python and scientific computing with Python. This is a question to avoid any duplication of code that might already exist.

I have a field that is sampled as a function of x and y in a regular grid. I would want to interpolate the data to obtain not only the value of the field at any point on the grid, but also the first and second derivatives. If I interpolate it with bicubic interpolation using interp2d, I can obtain the value of the field.

Does anyone have a suggestion on how to obtain the first and second derivatives of the field using an EXISTING numpy or scipy function?

Thanks!

Conversion answered 7/12, 2012 at 23:47 Comment(7)
Are you looking for numpy.diff ?Lascivious
docs.scipy.org/doc/numpy/reference/generated/…Chatterer
While UnivariateSpine has a method to return a derivative, for a 2D spline interpolation, I'd guess your best bet at the moment is to grab the coefficients via the get_coeffs and take it from there.Shizukoshizuoka
@Lascivious numpy.diff is something that I considered but I didn't have option of choosing forward, backward or central differences.Conversion
@MrE numpy.gradient would probably work fine as well.Conversion
@Zhenya That should serve my purpose. Computing the derivatives from the coefficients is just a polynomial evaluation with the appropriate weights. Thank y'all for responding!Conversion
@MrE you could post your comment as an answer...Mascarenas
S
2

The scipy.interpolate.interp2d.__call__ method has options dx and dy to evaluate higher derivatives at point (at least since version 0.14.0).

Spates answered 2/4, 2015 at 14:49 Comment(0)
C
0

Can not believe this question was not answered in detals for so long. This is a issue that is frequently encountered when one deals with numerical data. Here is the code:

from scipy.interpolate import RectBivariateSpline
import numpy as np
x = np.linspace(-1,1,50)
y = np.linspace(-2,2,50)

# some artifical data
f = x[:,None]*y[None,:]

# prepare the spline
f_spline = RectBivariateSpline(x,y, f, kx=3,ky=3)

# first derivatives
f_x = f_spline(x, y, dx=1, dy=0)
f_y = f_spline(x, y, dx=0, dy=1)

#second derivatives
f_xx = f_spline(x, y, dx=2, dy=0)
f_yy = f_spline(x, y, dx=0, dy=2)

Crossness answered 22/7 at 13:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.