faster way to loop over atoms

100 views
Skip to first unread message

Daniel Konstantinovsky

unread,
Sep 1, 2022, 10:40:35 AM9/1/22
to MDnalysis discussion
Hi MDAnalysis!

I'm writing a custom hydrogen bonding analysis code and need to loop a lot over atoms. Right now my code is doing this:

for atom in atomGroup:
         pos1 = atom.position
         for atom2 in atomGroup2:
                 pos2 = atom2.position
                 doStuffWithPositions(pos1, pos2)

I tried looping over indices, like this

for i in range(atomGroup.n_atoms):
         pos1 = atomGroup.positions[i]
         for j in range(atomGroup2.n_atoms):
                 pos2 = atomGroup2.positions[j]
                 doStuffWithPositions(pos1, pos2)

but it was (even) slower. I noticed with the first version that just looping over the atoms took up 1/3 of the total time in my case (doStuffWithPositions etc are optimized Cython routines)! How can I loop over atoms faster? Why is there so much overhead? I need to extract positions, ix, and other information from each hydrogen bond so I can't just loop over position arrays. I am not doing any select_atoms() inside the loop of course.

Thank you!
Dan

Lily Wang

unread,
Sep 1, 2022, 5:26:16 PM9/1/22
to mdnalysis-...@googlegroups.com
Dear Dan,

A hidden gotcha with MDAnalysis is that any time you call atomGroup.positions, it returns a copy of the underlying positions array. Does the following rearrangement help speed anything up?

positions1 = atomGroup.positions
positions2 = atomGroup2.positions

for pos1 in positions1:
    for pos2 in positions2:
        doStuffWithPositions(pos1, pos2)


Cheers,
Lily

--
You received this message because you are subscribed to the Google Groups "MDnalysis discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mdnalysis-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mdnalysis-discussion/ec3add3f-ddb5-495c-9cc0-d6c62cf0cd51n%40googlegroups.com.

Daniel Konstantinovsky

unread,
Sep 1, 2022, 6:16:06 PM9/1/22
to mdnalysis-...@googlegroups.com
Hi Lily,

Thank you for the tip, I got a 60% speedup from changing it as you said!

Dan

You received this message because you are subscribed to a topic in the Google Groups "MDnalysis discussion" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/mdnalysis-discussion/LUdmxMV83Xk/unsubscribe.
To unsubscribe from this group and all its topics, send an email to mdnalysis-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mdnalysis-discussion/B724A98B-951D-4E52-BED9-9B04E0D758BB%40minium.com.au.
Reply all
Reply to author
Forward
0 new messages