I have a 2d grid of dim q(rows) p(columns). The element of the grid are the indices of the element itself. So the element a[i,j]=(i,j).
Now I need to create pair-wise distances between these points with circularity constraint, meaning that the element distance(a[i,p-1],a[i,0])=1 (I am using 0-index based matrix as in Python). Analogously distance(a[q-1,j],a[0,j])=1
Observe that distance(a[q-2,j],a[0,j]) is the shorter vertical path going from 0 to q-2 and the path from q2 to 0 (leveraging the circularity of the grid). Same thing happens horizontally.
My question is: is there a NumPy function that enables to quickly calculate such a pairwise distances matrix?
Advertisement
Answer
I don’t know of a function do do this, but it’s pretty easy to compute manually:
JavaScript
x
32
32
1
import numpy as np
2
3
q = 6 # rows
4
p = 5 # columns
5
6
# Create array of indices
7
a = np.mgrid[0:q, 0:p].transpose(1, 2, 0)
8
9
# The array `a` now has shape (q, p, 2) :
10
a[1, 2] # array([1, 2])
11
a[3, 0] # array([3, 0])
12
13
# Create a new array measuring the i,j difference between all pairs of
14
# locations in the array. `diff` will have shape (q, p, q, p, 2) :
15
diff = a[None, None, :, :, :] - a[:, :, None, None, :]
16
17
# Modify diff to obey circularity constraint
18
di = diff[ , 0]
19
dj = diff[ , 1]
20
di[di > q//2] -= q
21
dj[dj > p//2] -= p
22
23
# compute distance from diff
24
dist = (diff[ , 0]**2 + diff[ , 1]**2)**0.5
25
26
# test:
27
dist[1, 0, 1, 0] # 0.0
28
dist[1, 0, 1, 1] # 1.0
29
dist[1, 0, 1, 2] # 2.0
30
dist[1, 0, 1, 3] # 2.0
31
dist[1, 0, 1, 4] # 1.0
32