python - 具有圆形距离的网格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 函数可以快速计算这样的成对距离矩阵?
解决方案
我不知道有什么功能可以做到这一点,但是手动计算很容易:
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
推荐阅读
- c# - 加载母版页时,Ajax.Get 调用未在部分视图中触发
- javascript - 单击按钮后为 html 页面动态生成的内容
- javascript - 用于插件的文本字段 onblur 的 Ember 表单不起作用
- swiftui - 为什么我得到数据模型错误只有具体类型可以符合协议
- c# - 无法将方法组转换为 func
- javascript - react prop-types:来自现有 prop-types 的可重用验证器
- model-view-controller - 使用mvc在服务器上删除文件的问题
- python - 计算带有 np.nan 的熊猫数据框的值的平均值的最佳方法是什么?
- javascript - 如何使用 javascript 识别唯一设备?
- reactjs - React TypeScript 16.8 如何向 useEffect() 添加依赖项