Scipy KDTree() 获取矩形相邻网格点

Scipy KDTree() Get rectagular shaped neighbouring grid points

我在使用这个模块时遇到了一个小问题。事实上,该模块完全按照我要求他做的...找到该网格中给定坐标的所有最近的网格点。

但是,当给定的坐标非常接近网格的一个点并且网格的一侧有较长的步长时,它会给出如下内容:

所以在这个图像中,计算最近邻的点是你可以在左下角看到的红点。 KDTree给出的结果就是蓝色方块。绿色菱形是我想要得到的第 4 个点,而不是图像顶部唯一的蓝色菱形。

代码:

>>> grid.head()
          x         y
0  0.000000 -9.490125
1  0.959131 -9.490125
2  1.918263 -9.490125
3  2.877394 -9.490125
4  3.836526 -9.490125

>>> pt
[4.0092010999999998e-05, -9.4901299629261011]

>>>tree = ssp.KDTree(grid)
>>>dis, idx = tree.query(pt,4)

>>> idx 
array([  0,  71,   1, 142])

>>> grid.iloc[idx]
            x         y
0    0.000000 -9.490125
71   0.000000 -8.980481
1    0.959131 -9.490125
142  0.000000 -8.470837

问题:

有没有办法指定我们想要在查询中使用矩形数组之类的东西?也许通过指定我们只需要 2 个 y 来代替一个 x?

首先,让我们尝试create a Minimal, Complete, and Verifiable example

>>> import pandas as pd
>>> import numpy as np
>>> x0, dx = 0, 0.959131
>>> x  = np.arange(x0, x0+5*dx,dx) 
>>> y0, dy = -9.4901299629261011, 8.980481-8.470837
>>> y  = np.arange(y0, y0+2*dy,dy)
>>> data = np.transpose([np.tile(x, len(y)), np.repeat(y, len(x))])
>>> grid = pd.DataFrame(data=data, columns=['x', 'y'])
>>> grid.head()
          x        y
0  0.000000 -9.49013
1  0.959131 -9.49013
2  1.918262 -9.49013
3  2.877393 -9.49013
4  3.836524 -9.49013

其中 grid.head() 是基于 grid 图形表示的等价数值

>>> grid
           x         y
0   0.000000 -9.490130 # the red dot
1   0.959131 -9.490130 # the bottom right blue square
2   1.918262 -9.490130
3   2.877393 -9.490130
4   3.836524 -9.490130
5   0.000000 -8.980486 # the middle left blue square
6   0.959131 -8.980486 # the green diamond
7   1.918262 -8.980486
8   2.877393 -8.980486
9   3.836524 -8.980486
10  0.000000 -8.470842 # the unwanted top left blue square
11  0.959131 -8.470842
12  1.918262 -8.470842
13  2.877393 -8.470842
14  3.836524 -8.470842

因此,您希望点 156 作为点 0.

的邻域

为此,您可能需要查看 the sklearn.neighbors module which implements the k-nearest neighbors algorithm. Playing with it, and setting the power parameter for the Minkowski metricp、大于 2 的函数 kneighbors_graph,比如说 3(取p>2的思路基本上是将单位正方形中的对角线和边之间的欧几里得2平方根因子减小到1),如下

>>> from sklearn.neighbors import kneighbors_graph
>>> _3n_graph = kneighbors_graph(grid,
                                 n_neighbors=3,
                                 p=3,
                                 mode='connectivity',
                                 include_self=False)

产量

>>> grid.iloc[_3n_graph[0].indices]
          x         y
5  0.000000 -8.980486
1  0.959131 -9.490130
6  0.959131 -8.980486