Python 将随机浮点数舍入到二维均匀网格上的最近点

Python rounding of random floats to nearest points on a 2D uniform mesh grid

尽管 numpy 和 scipy 有很多舍入函数,但我找不到一个可以让我在 2D 均匀网格中根据节点离散化随机浮点数的函数。例如,

# create mesh grid
n = 11
l = 16.
x = np.linspace(-l/2, l/2, n)
y = np.linspace(-l/2, l/2, n)
xx, yy = np.meshgrid(x, y, sparse=True)

>>> xx
array([-8. , -6.4, -4.8, -3.2, -1.6,  0. ,  1.6,  3.2,  4.8,  6.4,  8. ])    
>>> yy
array([[-8. ],
       [-6.4],
       [-4.8],
       [-3.2],
       [-1.6],
       [ 0. ],
       [ 1.6],
       [ 3.2],
       [ 4.8],
       [ 6.4],
       [ 8. ]])

如果我有 m 个正态分布的随机浮点数 a=np.random.multivariate_normal([0,0], [[l/2,0],[0,l/2]], m),我如何将它们四舍五入到最近的网格节点(假设有周期性边界)?

在另一个 SO 问题中,我帮助提问者使用了 scipy 最近邻插值器。

Repeating Scipy's griddata

据此我找到了解决您问题的方法。在 scipy.interpolate 中我找到一个 NearestNDInterpolator。由此我发现 scipy.spatial 有一种寻找最近邻居的方法:

In [936]: from scipy import interpolate
In [937]: interpolate.NearestNDInterpolator?
...
Docstring:
NearestNDInterpolator(points, values)

Nearest-neighbour interpolation in N dimensions.
...
Uses ``scipy.spatial.cKDTree``

In [938]: from scipy import spatial
In [939]: spatial.cKDTree?

cKDTree分2步使用;从网格创建一棵树,并查询最近的邻居。

从你的网格我可以创建一个 (n,2) 点数组

In [940]: xx, yy = np.meshgrid(x, y)
In [941]: xygrid=np.array([xx,yy])
In [942]: xygrid=xygrid.reshape(2,-1).T  # clumsy

创建搜索树:

In [943]: tree=spatial.cKDTree(xygrid)

测试点集,(10,2):

In [944]: a=np.random.multivariate_normal([0,0], [[l/2,0],[0,l/2]],10)

搜索树的查询给出了 2 个数组,一个是距最近邻居的距离,另一个是索引:

In [945]: I=tree.query(a)

In [946]: I
Out[946]: 
(array([ 0.70739099,  0.9894934 ,  0.44489157,  0.3930144 ,  0.273121  ,
        0.3537348 ,  0.32661876,  0.55540787,  0.58433421,  0.538722  ]),
 array([61, 72, 85, 72, 82, 39, 38, 62, 25, 59]))

a 个点与 xygrid 个最近邻网格点进行比较,表明它们确实看起来很接近。散点图会更好。

In [947]: a
Out[947]: 
array([[ 1.44861113, -0.69100176],
       [ 1.00827575,  0.80693026],
       [ 4.37200745,  3.07854676],
       [ 1.2193471 ,  1.50220587],
       [ 0.12668563,  2.95803754],
       [ 1.4758331 , -3.53122635],
       [ 0.28425494, -3.03913067],
       [ 2.8203361 ,  0.40538034],
       [-3.67726571, -4.46285921],
       [-1.07228578, -0.10834709]])

In [948]: xygrid[I[1],:]
Out[948]: 
array([[ 1.6,  0. ],
       [ 1.6,  1.6],
       [ 4.8,  3.2],
       [ 1.6,  1.6],
       [ 0. ,  3.2],
       [ 1.6, -3.2],
       [ 0. , -3.2],
       [ 3.2,  0. ],
       [-3.2, -4.8],
       [-1.6,  0. ]])

rth 的 link 中的解决方案也使用 cKDTree。我只是填写有关如何从您的网格数据工作的详细信息。 Finding index of nearest point in numpy arrays of x and y coordinates