我正在使用scipy.interpolate.griddata,以便将数据从原始网格插入到该网格的子区域,但分辨率更高。为了加快计算速度,我只使用包含目标区域(带缓冲区)的部分,而不是使用整个原始数据。令我惊讶的是,如果我使用线性插值,即使在我的子区域中间,我也会获得不同的结果。
下面的代码说明了这一点。我想知道这是否是预期的,或者它是否是griddata中的错误。请注意,如果我在代码中使用'nearest'而不是'linear',则差异为null,正如我所料。
任何帮助表示感谢。
# modification to expample 1 of
# http://scipy-cookbook.readthedocs.io/item/Matplotlib_Gridding_irregularly_spaced_data.html
# to show problems with griddata
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
import numpy.ma as ma
# generate inital fields on 2d grid
x = np.arange(-2,2.1,0.1)
y = np.arange(-2,2.1,0.1)
x2d, y2d = np.meshgrid(x,y)
z = np.abs(x*np.exp(-x2d**2-y2d**2)) + 1
# define target grid
# (sub region of initial grid but with finer mesh)
x_target = np.arange(-1,1,0.01)
y_target = np.arange(-1,1,0.01)
x2d_target, y2d_target = np.meshgrid(x_target, y_target)
# define interpolation function
def f_int(data, x, y, xt, yt):
nj, ni = data.shape
nij = ni * nj
zi = data.reshape((nij))
xi = x.ravel()
yi = y.ravel()
xo = xt.ravel()
yo = yt.ravel()
zo = griddata((xi, yi), zi, (xo, yo),
method = 'linear', fill_value = np.nan)
zo = zo.reshape(xt.shape)
return zo
# interpolate on target grid using the whole initial field
z_int_full = f_int(z, x2d, y2d, x2d_target, y2d_target)
# interpolate on taget grid using a subset of initial field
buffer = 5
x2d_sub = x2d[buffer:-buffer, buffer:-buffer]
y2d_sub = y2d[buffer:-buffer, buffer:-buffer]
z_sub = z[buffer:-buffer, buffer:-buffer]
z_int_sub = f_int(z_sub, x2d_sub, y2d_sub, x2d_target, y2d_target)
# show the results
fig = plt.figure()
fig.set_size_inches(fig.get_size_inches() * 2)
ax1 = fig.add_subplot(221)
plt.pcolormesh(x2d, y2d, z)
plt.colorbar()
plt.title('initial data')
ax2 = fig.add_subplot(222)
plt.pcolormesh(x2d_target, y2d_target, z_int_full)
plt.colorbar()
plt.title('interpolate from full grid')
ax3 = fig.add_subplot(223)
plt.pcolormesh(x2d_target, y2d_target, z_int_sub)
plt.colorbar()
plt.title('interpolate from sub grid')
ax4 = fig.add_subplot(224)
diff = (z_int_full - z_int_sub)
rel = diff / z_int_full * 100
plt.pcolormesh(x2d_target, y2d_target, rel)
plt.colorbar()
plt.title('relative difference between \n interpolated data [%]')
plt.show()
修改 添加了代码生成的数字。正如您在右下图中所看到的,存在0.1%的相对误差,这是我不期望的。我试图简化问题来制定我的问题但是对于我正在研究的数据,这转化为内插表面温度的1 deg_K的差异,这对我来说是一个问题。