Python 3 & Numpy.
Use pip:
pip install pairwiseDistances
or manually:
python setup.py install
and in your code:
from pairwiseDistances import *
See also the examples folder.
A common problem is to calculate pairwise distances for n particles. This occurs in particle simulations (e.g. electrostatics) and many other scientific fields. This simple module aims to perform this calculation and implements several common efficiency strategies:
-
Storage: Calculating pairwise distances is
O(n^2)(actuallynchoose 2). It is inefficient to repeatedly calculate this. In many codes, only one or a few particles are changed at a time. Adding a particle, removing a particle, or moving a particle are allO(n)operations. They are implemented here, such that when a particle is added/removed/moved, not all pairwise distances are recalculated. -
Cutoff distance: A cutoff distance (or radius) usually exist beyond which interactions between particles are negligible. This is implemented here as well.
A further improvement used in most applications (but not implemented for you here) is to divided space into some partitions (a.k.a. voxels or bins) that are approximately the size of the cutoff distance, such that far interactions are not considered. This code can be used in this regard as well, where each partition would contain the pairwise interactions with particles in the same and neighboring voxels.
-
Labels: Optional labels can be attached to every particle to keep track of them. The method
get_particle_idx_from_labelcan be used to retrieve an index from a label by searching a numpy array withargwhere(note that this may be slow). -
Centers: Optional centers
(x_i + x_j)/2can also be computed and tracked for every pair of particles. As before, adding/removing/moving particles are allO(n)operations here. -
Different species: All the same jazz as above, but now the input are two lists of particles, and we are only interested in the cross-species (cross-list) distances between particles. In other words, let the first list be the particles of species
A, and the second list of speciesB. In this application, we are only interested in the distances betweenA-B, and notA-AorB-B. If they are of lengthnAandnB, this is thennA*nBdistances, rather than((nA+nB) choose 2) = (nA+nB) * (nA+nB-1) / 2distances. -
Disable keeping track of pairwise distances: Keeping track of the pairwise distances can be disabled in the add/remove/move particle methods with the
keep_dists_validflag. They can then be recomputed with thecompute_distsmethod.
See the examples folder.
Tests using pytest are in the tests folder.