具有圆形距离的网格 python

grid with circular distances python

我有一个暗淡的 q(行)p(列)的二维网格。 网格的元素是元素本身的索引。 所以元素 a[i,j]=(i,j).

现在我需要在具有圆度约束的这些点之间创建成对距离,这意味着元素 distance(a[i,p-1],a[i,0])=1(我使用 0 - 基于索引的矩阵,如 Python 中所示)。类比 distance(a[q-1,j],a[0,j])=1

观察 distance(a[q-2,j],a[0,j]) 是从 0 到 q-2 的较短垂直路径和从 q2 到 0 的路径(利用网格)。横向发生同样的事情。

我的问题是:是否有 NumPy 函数可以快速计算这样的成对距离矩阵?

我不知道有哪个函数可以执行此操作,但手动计算非常容易:

import numpy as np

q = 6  # rows
p = 5  # columns

# Create array of indices
a = np.mgrid[0:q, 0:p].transpose(1, 2, 0)

# The array `a` now has shape (q, p, 2) :
a[1, 2]  # array([1, 2])
a[3, 0]  # array([3, 0])

# Create a new array measuring the i,j difference between all pairs of 
# locations in the array. `diff` will have shape (q, p, q, p, 2) :
diff = a[None, None, :, :, :] - a[:, :, None, None, :]

# Modify diff to obey circularity constraint
di = diff[..., 0]
dj = diff[..., 1]
di[di > q//2] -= q
dj[dj > p//2] -= p

# compute distance from diff
dist = (diff[..., 0]**2 + diff[..., 1]**2)**0.5

# test:
dist[1, 0, 1, 0]  #  0.0
dist[1, 0, 1, 1]  #  1.0
dist[1, 0, 1, 2]  #  2.0
dist[1, 0, 1, 3]  #  2.0
dist[1, 0, 1, 4]  #  1.0