在多维网格中实现周期性边界条件

时间:2019-11-22 23:29:19

标签: python numpy indexing grid

我尝试实现一种算法,该算法在具有周期性边界条件的N维网格中查找点的邻居。

例如,我有一个立方3D网格,其长度= 3(3x3x3),所以我有27个点。每个点都通过numpy.ravel_multi_index分配给索引(参见图片)。 现在,我想找到一个任意点的邻居。我的代码适用于内点:

def nneighbour(index , dim, Length):
    neighbour = np.zeros(dim*2) 
    up_down = np.empty((dim*2,),int)
    up_down[::2] = 1
    up_down[1::2] = -1 # array for left right -1 = left, +1 = right
    D = np.repeat(np.arange(0, dim, 1), 2) # neighbour dimension : first 2 elements in 1d, next 2 elements in 2d and so on
    neighbour = index + up_down*np.power(Length, D)
    return neighbour

nneighbour(13, 3, 3)返回例如[14 12 16 10 22 4]。前两个点是第一维的邻居,第二个点是第二维的邻居,依此类推。 但是我不知道如何实现边缘点的周期性边界条件。对于index = 10,应该是[11 9 13 16 19 1]而不是[11 9 13 7 19 1](因为我们越过了第二层的底部边界)。

Flattened 3x3x3 grid

1 个答案:

答案 0 :(得分:1)

最简单的方法是解散-邻居-拉夫:

def nneighbour(index,dim,length):
    index = np.asarray(index)
    shp = dim*(length,)
    neighbours = np.empty((*index.shape,dim,dim,2),int)
    neighbours.T[...] = np.unravel_index(index,shp)
    ddiag = np.einsum('...iij->...ij',neighbours)
    ddiag += (-1,1)
    ddiag %= length
    return np.ravel_multi_index(np.moveaxis(neighbours,-3,0),shp).ravel()

示例:

nneighbour(10,3,3)
# array([ 1, 19, 16, 13,  9, 11])