insilichem / ommprotocol

A command line application to launch molecular dynamics simulations with OpenMM
http://ommprotocol.readthedocs.io
GNU Lesser General Public License v3.0
39 stars 8 forks source link

Fix: particle indexes passed to addParticle #17

Closed aizvorski closed 3 years ago

aizvorski commented 4 years ago

Without this fix, it appears that the particle indexes passed to force.addParticle() in restraint_force() were incorrect when selectors are used.

I've been using this code to learn how to write my own steered MD protocol, and I ran into this part while going through it. The first argument to addParticle() is a particle index; it should always be equal to the index used to subscript positions[index]. When calling enumerate in this way, in general, i is not the same as index.

The particle index is also expected to be an int; MDTrajTopology select() returns an ndarray of int64, which needs an explicit cast as done here. Omitting the cast would case NotImplementedError: Wrong number or type of arguments for overloaded function 'CustomExternalForce_addParticle'..

The original code appears to works correctly if no selectors are used, since in that case i and index would be equal. But if any selectors (eg "backbone") are used, then it would add forces to the wrong particles.

I would be grateful if you can double-check this and let me know if my understanding of what is going on is correct.

aizvorski commented 3 years ago

Good catch! Thanks for your submission. Please see the comment below!

Hi Jamie - Thanks! I may have imported nanometers in my test code somewhere; of course u.nanometers is correct

I think the int() cast is also needed, if the indices come from MDTrajTopology select(). The indices are an ndarray of int64, and those don't work as an argument to addParticle(). Try something like indices = np.zeros((1,), dtype=np.int64), it should throw an exception

Best, Alex