openmmtools.forces.find_forces

openmmtools.forces.find_forces(system, force_type, only_one=False, include_subclasses=False)[source]

Find all the Force object of a given type in an OpenMM system.

Parameters:
systemopenmm.System

The system to search.

force_typestr, or type

The class of the force to search, or a regular expression that is used to match its name. Note that re.match() is used in this case, not re.search(). The iter_subclasses argument must be False when this is a string.

only_onebool

If True, an exception is raised when multiple forces of the same type are found in the system, and only a single force is returned.

include_subclassesbool, optional

If True, all forces inheriting from force_type are returned as well (default is False). This can’t be enabled if force_type` is not a class.

Returns:
forcesOrderedDict or tuple

If only_one is False, a dictionary force_index: force is returned with all the forces matching the criteria. Otherwise,, a single pair (force_idx, force) is returned.

Raises:
NoForceFoundError

If only_one is True and no forces matching the criteria are found.

MultipleForcesError

If only_one is True and multiple forces matching the criteria are found

Examples

The only_one flag can be used to retrieve a single force.

>>> from openmmtools import testsystems
>>> system = testsystems.TolueneVacuum().system
>>> force_index, force = find_forces(system, openmm.NonbondedForce, only_one=True)
>>> force.__class__.__name__
'NonbondedForce'

It is possible to search for force subclasses.

>>> class MyHarmonicForce(utils.RestorableOpenMMObject, openmm.CustomBondForce):
...     pass
>>> force_idx = system.addForce(openmm.CustomBondForce('0.0'))
>>> force_idx = system.addForce(MyHarmonicForce('0.0'))
>>> forces = find_forces(system, openmm.CustomBondForce, include_subclasses=True)
>>> [(force_idx, force.__class__.__name__) for force_idx, force in forces.items()]
[(5, 'CustomBondForce'), (6, 'MyHarmonicForce')]

A regular expression can be used instead of a class.

>>> forces = find_forces(system, 'HarmonicAngleForce')
>>> [(force_idx, force.__class__.__name__) for force_idx, force in forces.items()]
[(1, 'HarmonicAngleForce')]
>>> forces = find_forces(system, '.*Harmonic.*')
>>> [(force_idx, force.__class__.__name__) for force_idx, force in forces.items()]
[(0, 'HarmonicBondForce'), (1, 'HarmonicAngleForce'), (6, 'MyHarmonicForce')]