Skip to content

Instantly share code, notes, and snippets.

@yangyushi
Created July 6, 2020 15:09
Show Gist options
  • Save yangyushi/38bdd59ba47ce5425103d8f57665e126 to your computer and use it in GitHub Desktop.
Save yangyushi/38bdd59ba47ce5425103d8f57665e126 to your computer and use it in GitHub Desktop.
pairwise distance calculation for n-dimensional coordinates
import numpy as np
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
def pdist_pbc(positions, box):
"""
Get the pair-wise distances of particles in a priodic boundary box
Args:
positiosn (:obj:`numpy.ndarray`): coordinate of particles, shape (N, dim)
box (:obj:`float`): the length of the priodic bondary.
The box should be cubic
Return:
the pairwise distance, shape ( (N * N - N) / 2, ), use
:obj:`scipy.spatial.distance.squareform` to recover the matrix form.
"""
n, dim = positions.shape
result = np.zeros(int((n * n - n) / 2), dtype=np.float64)
for d in range(dim):
dist_1d = pdist(positions[:, d][:, np.newaxis])
dist_1d[dist_1d > box / 2] -= box
result += np.power(dist_1d, 2)
return np.sqrt(result)
if __name__ == "__main__":
dists = pdist_pbc(np.random.random((1000, 3)), box=1)
plt.hist(dists, bins=200, density=True)
plt.plot([np.sqrt(3)/2, np.sqrt(3)/2], [0, 5], color='k', ls='--')
plt.ylim(0, 4)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment