scipy的griddata和RectBivariateSpline

时间:2015-08-31 16:04:57

标签: python numpy scipy interpolation

在(例如)2D网格中进行插值时,可以使用函数griddata(来自scipy.interpolate包)或来自同一包的RectBivariateSpline

他们中的任何一个是否优于另一个,如果是,为什么?据我所知,griddata可以处理不规则形状的输入,而RectBivariateSpline则不能。

1 个答案:

答案 0 :(得分:0)

好吧,我没有这个问题的答案,因为它相当..通用。.但是对于那些也落在此页面上并且想要使用这两个功能的人..在下面的代码中,您可以测试一下差异。

我个人认为,通过查看误差图,RectBivariateSpline可以更好地工作。同样,在这种情况下,输入数据的方式也更加方便。

import scipy.interpolate
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
import matplotlib.pyplot as plt

d_coarse = 0.5
X_coarse = np.arange(-5, 5, d_coarse)
Y_coarse = np.arange(-5, 5, d_coarse)
X_fine = np.arange(-5, 5, d_coarse/2)
Y_fine = np.arange(-5, 5, d_coarse/2)

X_coarse_mesh, Y_coarse_mesh = np.meshgrid(X_coarse, Y_coarse)
X_fine_mesh, Y_fine_mesh = np.meshgrid(X_fine, Y_fine)

R_coarse = np.sqrt(X_coarse_mesh**2 + Y_coarse_mesh**2)
Z_coarse = np.sin(R_coarse)
R_fine = np.sqrt(X_fine_mesh **2 + Y_fine_mesh **2)
Z_fine = np.sin(R_fine)

# First make a mapping/interpolation object..
interpolate_obj = scipy.interpolate.RectBivariateSpline(X_coarse, Y_coarse, Z_coarse)
Z_fine_rectbiv = interpolate_obj(X_fine, Y_fine)

XY_coarse_list = np.concatenate([np.reshape(X_coarse_mesh, (-1, 1)), np.reshape(Y_coarse_mesh, (-1, 1))], axis=1)
XY_fine_list = np.concatenate([np.reshape(X_fine_mesh, (-1, 1)), np.reshape(Y_fine_mesh, (-1, 1))], axis=1)
Z_list = np.reshape(Z_coarse, (-1, 1))


z = scipy.interpolate.griddata(XY_coarse_list, Z_list, XY_fine_list, method='cubic')
Z_fine_griddata = np.reshape(z, (40, 40))

# Plot the surface.
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X_coarse_mesh, Y_coarse_mesh, Z_coarse, linewidth=0, antialiased=False)
plt.title('coarse grid')
plt.show()

# Plot the surface on a finer grid
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X_fine_mesh, Y_fine_mesh, Z_fine_griddata-Z_fine, linewidth=0, antialiased=False)
plt.title('griddata')
plt.show()

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X_fine_mesh, Y_fine_mesh, Z_fine_rectbiv-Z_fine, linewidth=0, antialiased=False)
plt.title('RectBivariateSpline')
plt.show()