[Tutor] Euclidean Distances between Atoms in a Molecule.

Steven D'Aprano steve at pearwood.info
Sun Apr 2 22:58:33 EDT 2017


On Sun, Apr 02, 2017 at 01:41:27PM -0400, Stephen P. Molnar wrote:
> I am trying to port a program that I wrote in FORTRAN twenty years ago 
> into Python 3 and am having a hard time trying to calculate the 
> Euclidean distance between each atom in the molecule and every other 
> atom in the molecule.
> 
> Here is a typical table of coordinates:
> 
> 
>       MASS         X         Y         Z
> 0   12.011 -3.265636  0.198894  0.090858
> 1   12.011 -1.307161  1.522212  1.003463
[...]

> What I need for further calculation is a matrix of the Euclidean 
> distances between the atoms.

It is quite likely that the third-party Numpy or Scipy packages include 
read-made solutions to this. It sounds like the sort of thing that they 
will do, and probably much more efficiently than pure Python code.

But as a simple example, if I have two coordinates written as tuples:

p  = (-3.265636, 0.198894, 0.090858)
q = (-1.307161, 1.522212, 1.003463)

I can write a Euclidean distance function like this:


import math

def distance(a, b):
    """Return the Euclidean distance between 3D points a and b."""
    return math.sqrt(
            (a[0] - b[0])**2 + (a[1] - b[1])**2 + (a[2] - b[2])**2
            )


and then call the function:

result = distance(p, q)

which will return 2.5337013913983633 and assign it to the variable 
"result".

Does that help?



-- 
Steve


More information about the Tutor mailing list