简体   繁体   English

计算python中n维字段的邻居

[英]calculate the neighbours of n-dimensional fields in python

When given a matrix of n-dimension and a grid size of 1 I'd like to calculate the nearest neighbours of a field. 当给定一个n维矩阵且网格大小为1时,我想计算一个字段的最近邻居。 Given below is an example for a 2-dimensional field 下面给出的是二维字段的示例

P = (1,1)

p_neighbours = [(0,0),(2,2),(0,1),(0,2),(1,0),(2,0),(2,1),(1,2)]

Mathematically this can be as easily described as P +/- 1 in a vectorian system (as far as I understand). 在数学上,这可以很容易地描述为矢量系统中的P +/- 1(据我所知)。 The size of the n-dimensional neighbour array is described as (n^3)-1 I've already found a pretty good old topic , anyhow I couldn't understand how any of the presented solutions could be extended to a n-dimensional function.. n维邻居数组的大小描述为(n ^ 3)-1我已经找到了一个很好的老话题 ,无论如何,我不明白如何将提出的解决方案扩展到n维功能..

from itertools import product

def stencil(dim):
    stencils = list(product([-1,0,1], repeat=dim))
    zero = ((0,) * dim)
    stencils.remove(zero)
    return stencils

def neighbours(P):
    stencils = stencil(len(P))
    return [tuple([sum(x) for x in zip(P,s)]) for s in stencils]

P = (4, 4, 4)

print(neighbours(P))

正确地说,n维邻居数组的大小不是(n ^ 3)-1,而是(3 ^ n)-1(如果n> 3,则数组大小要大得多!)生成邻居在任何维度上,您都必须实现一个递归算法,该算法在维度上进行迭代并调用自身(我不知道确切地如何实现此方法,但是我正在研究它)

I guess should be something like this 我想应该是这样的

p_neighbours = []
for x in [-1,0,1]:
  for y in [-1,0,1]:
    p_neighbours.append((P(0)+x,P(1)+y))

I think the clearest way to go here is to use a simple list comprehension: 我认为最简单的方法是使用简单的列表理解:

p = (1,1)
px, py = p
p_neighbours = [(px+x,py+y) for x in range(-1,2) for y in range(-1,2) if (x,y) != (0,0)]

Here we check that (x,y) is not (0,0) to avoid adding p itself to its neighbors. 在这里,我们检查(x,y)是否不是(0,0),以避免将p自身添加到其邻居中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM