2015-07-21 57 views
2

儘管numpy & scipy的許多舍入函數,我無法找到一個允許我關於2D均勻網格網格中的節點離散化隨機浮點數。例如,Python舍入隨機浮點數到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)的,我怎麼能圓他們到最近的網格節點(假設週期邊界)?

+0

在你的例子中,網格間距是統一的。情況總是如此嗎? –

+0

是的。我已經將它添加到描述中。 –

+0

可能的重複https://stackoverflow.com/questions/10818546/finding-index-of-nearest-point-in-numpy-arrays-of-x-and-y-coordinates – rth

回答

3

在另一個SO問題中,我幫助提問者使用了一個scipy最近的neigbhor插補器。

Repeating Scipy's griddata

從我想出了一個解決問題的方法工作。在scipy.interpolate我找到一個NearestNDInterpolator。從我發現scipy.spatial有尋找最近的鄰居的方法:

​​3210

cKDTree在2個步驟中使用;從網格創建一棵樹,並查詢最近的鄰居。

從你meshgrid我可以創建一個(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個數組,其中一個距離最近的鄰居,另一個索引ES:

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的鏈路A解決方案還使用cKDTree。我只是填寫如何從你的griddata工作的細節。 Finding index of nearest point in numpy arrays of x and y coordinates