使用 RegularGridInterpolator 时,如何仅在边界外使用最近邻插值
How can I use nearest neighbor interpolation only outside of bounds when using RegularGridInterpolator
使用 RegularGridInterpolator
获取输入数据外壳(边界)之外的值,可以在外推值或固定值之间进行选择。如何在船体内部进行线性插值,在船体外部进行最近邻插值?
下面的class使用了两个插值器。第一个将船体外的所有值设置为 np.nan
。第二个插值器仅对那些 nan
值进行最近邻插值。
class RegularGridInterpolatorNNextrapol:
def __init__( self, points, values, method='linear' ):
self.interp = RegularGridInterpolator(points, values, method=method,
bounds_error=False, fill_value=np.nan)
self.nearest = RegularGridInterpolator(points, values, method='nearest',
bounds_error=False, fill_value=None)
def __call__( self, xi ):
vals = self.interp( xi )
idxs = np.isnan( vals )
vals[idxs] = self.nearest( xi[idxs] )
return vals
这是一个生成下图的示例:
x = np.linspace( -0.5, 0.5, 5 )
y = np.linspace( -0.5, 0.5, 5 )
X1, Y1 = np.meshgrid(x, y)
z = np.hypot(X1, Y1)
interp = RegularGridInterpolatorNNextrapol((x,y), z)
X = np.linspace(min(x)-0.2, max(x)+0.2,40)
Y = np.linspace(min(y)-0.2, max(y)+0.2,40)
X, Y = np.meshgrid(X, Y) # 2D grid for interpolation
pts = np.column_stack((X.flatten(),Y.flatten()))
Z = interp( pts )
plt.pcolormesh(X, Y, Z.reshape(X.shape), shading='auto')
plt.plot(X1, Y1, "ok" )
plt.legend()
plt.colorbar()
plt.axis("equal")
plt.show()
使用 RegularGridInterpolator
获取输入数据外壳(边界)之外的值,可以在外推值或固定值之间进行选择。如何在船体内部进行线性插值,在船体外部进行最近邻插值?
下面的class使用了两个插值器。第一个将船体外的所有值设置为 np.nan
。第二个插值器仅对那些 nan
值进行最近邻插值。
class RegularGridInterpolatorNNextrapol:
def __init__( self, points, values, method='linear' ):
self.interp = RegularGridInterpolator(points, values, method=method,
bounds_error=False, fill_value=np.nan)
self.nearest = RegularGridInterpolator(points, values, method='nearest',
bounds_error=False, fill_value=None)
def __call__( self, xi ):
vals = self.interp( xi )
idxs = np.isnan( vals )
vals[idxs] = self.nearest( xi[idxs] )
return vals
这是一个生成下图的示例:
x = np.linspace( -0.5, 0.5, 5 )
y = np.linspace( -0.5, 0.5, 5 )
X1, Y1 = np.meshgrid(x, y)
z = np.hypot(X1, Y1)
interp = RegularGridInterpolatorNNextrapol((x,y), z)
X = np.linspace(min(x)-0.2, max(x)+0.2,40)
Y = np.linspace(min(y)-0.2, max(y)+0.2,40)
X, Y = np.meshgrid(X, Y) # 2D grid for interpolation
pts = np.column_stack((X.flatten(),Y.flatten()))
Z = interp( pts )
plt.pcolormesh(X, Y, Z.reshape(X.shape), shading='auto')
plt.plot(X1, Y1, "ok" )
plt.legend()
plt.colorbar()
plt.axis("equal")
plt.show()