Skip to content
Advertisement

grid with circular distances python

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:

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement