首页 > 解决方案 > 具有圆形距离的网格python

问题描述

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

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

观察距离(a[q-2,j],a[0,j]) 是从 0 到 q-2 和从 q2 到 0 的较短垂直路径(利用网格的圆形度)。同样的事情发生在水平方向。

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

标签: pythonnumpydistance

解决方案


我不知道有什么功能可以做到这一点,但是手动计算很容易:

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

推荐阅读