使用scipy.interpolate.griddata时如何设置插值点之间的最大距离?

时间:2015-06-04 23:12:34

标签: python matplotlib scipy

我有一个空间数据集,我希望使用一些matplotlib或scipy模块进行插值。我的XY点具有凹形,我不希望在空区域中插入值。是否有一种方法可以轻松地允许用户设置点之间的最大距离,以避免在空区域中插值?

1 个答案:

答案 0 :(得分:6)

我努力解决同样的问题并通过重新使用scipy本身用于最近邻居插值的kd-tree实现来找到解决方法,用kd-tree查询结果的结果屏蔽插值结果数组。 / p>

考虑以下示例代码:

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt

# Generate some random data
xy = np.random.random((2**15, 2))
z = np.sin(10*xy[:,0]) * np.cos(10*xy[:,1])

grid = np.meshgrid(
    np.linspace(0, 1, 512),
    np.linspace(0, 1, 512)
)

# Interpolate
result1 = scipy.interpolate.griddata(xy, z, tuple(grid), 'linear')

# Show
plt.figimage(result1)
plt.show()

# Remove rectangular window
mask = np.logical_and.reduce((xy[:,0] > 0.2, xy[:,0] < 0.8, xy[:,1] > 0.2, xy[:,1] < 0.8))
xy, z = xy[~mask], z[~mask]

# Interpolate
result2 = scipy.interpolate.griddata(xy, z, tuple(grid), 'linear')

# Show
plt.figimage(result2)
plt.show()

这会生成以下两个图像。注意到强插值假象,因为数据中心缺少矩形窗口。

original data missing data

现在,如果我们在相同的示例数据上运行以下代码,则会获得以下图像。

THRESHOLD = 0.01

from scipy.interpolate.interpnd import _ndim_coords_from_arrays
from scipy.spatial import cKDTree

# Construct kd-tree, functionality copied from scipy.interpolate
tree = cKDTree(xy)
xi = _ndim_coords_from_arrays(tuple(grid), ndim=xy.shape[1])
dists, indexes = tree.query(xi)

# Copy original result but mask missing values with NaNs
result3 = result2[:]
result3[dists > THRESHOLD] = np.nan

# Show
plt.figimage(result3)
plt.show()

masked result

我意识到它可能不是你完全追求的视觉效果。特别是如果您的数据集不是非常密集,则需要具有高距离阈值才能使合法插值的数据不被屏蔽。如果您的数据足够密集,您可能能够以相对较小的半径逃脱,或者可能会提供更智能的截止功能。希望有所帮助。

相关问题