Coverage for cvpack/openmm_force_wrapper.py: 100%

36 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-21 18:13 +0000

1""" 

2.. class:: OpenMMForceWrapper 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: A collective variable built from the potential energy of an OpenMM force 

5 

6.. classauthor:: Charlles Abreu <craabreu@gmail.com> 

7 

8""" 

9 

10from __future__ import annotations 

11 

12import functools 

13import importlib 

14import typing as t 

15 

16import openmm 

17from openmm import unit as mmunit 

18 

19from .collective_variable import CollectiveVariable 

20from .units import Unit, VectorQuantity 

21 

22 

23class OpenMMForceWrapper(CollectiveVariable, openmm.Force): 

24 r""" 

25 A collective variable whose numerical value is computed from the potential energy, 

26 in kJ/mol, of an OpenMM force object. 

27 

28 Parameters 

29 ---------- 

30 openmmForce 

31 The OpenMM force whose potential energy will be used to define the collective 

32 variable. It can be passed as an instance of :OpenMM:`Force` or as a string 

33 containing the XML serialization of the force. 

34 unit 

35 The unit of measurement of the collective variable. It must be compatible 

36 with the MD unit system (mass in `daltons`, distance in `nanometers`, time 

37 in `picoseconds`, temperature in `kelvin`, energy in `kilojoules_per_mol`, 

38 angle in `radians`). If the collective variable does not have a unit, use 

39 `dimensionless`. 

40 periodicBounds 

41 The periodic bounds of the collective variable if it is periodic, or `None` if 

42 it is not. 

43 name 

44 The name of the collective variable. 

45 forceClass 

46 The Python class of the wrapped force, as ``"module:QualifiedName"``. It is 

47 detected automatically and only needs to be recorded when OpenMM's generic 

48 :OpenMM:`XmlSerializer` would deserialize the force as a base class, as it 

49 does for forces from plugins (e.g. a ``SlicedNonbondedForce`` comes back as a 

50 ``NonbondedForce``). The force is then rebuilt by the ``__setstate__`` method of 

51 this class, so that its plugin-specific methods remain available. 

52 

53 Example 

54 ------- 

55 >>> import cvpack 

56 >>> import numpy as np 

57 >>> import openmm 

58 >>> from openmm import unit 

59 >>> from openmmtools import testsystems 

60 >>> model = testsystems.AlanineDipeptideVacuum() 

61 >>> torsion = openmm.CustomTorsionForce("theta") 

62 >>> _ = torsion.addTorsion(4, 6, 8, 14) 

63 >>> cv = cvpack.OpenMMForceWrapper( 

64 ... torsion, 

65 ... unit.radian, 

66 ... periodicBounds=[-np.pi, np.pi] * unit.radian, 

67 ... ) 

68 >>> cv.addToSystem(model.system) 

69 >>> integrator = openmm.VerletIntegrator(0) 

70 >>> platform = openmm.Platform.getPlatformByName("Reference") 

71 >>> context = openmm.Context(model.system, integrator, platform) 

72 >>> context.setPositions(model.positions) 

73 >>> cv.getValue(context) 

74 -3.1415... rad 

75 >>> cv.getEffectiveMass(context) 

76 0.04795... nm**2 Da/(rad**2) 

77 """ 

78 

79 def __init__( 

80 self, 

81 openmmForce: openmm.Force | str, 

82 unit: mmunit.Unit, 

83 periodicBounds: VectorQuantity | None = None, 

84 name: str = "openmm_force_wrapper", 

85 forceClass: str | None = None, 

86 ) -> None: 

87 if isinstance(openmmForce, openmm.Force): 

88 cls = type(openmmForce) 

89 is_cv = isinstance(openmmForce, CollectiveVariable) 

90 openmmForce = openmm.XmlSerializer.serialize(openmmForce) 

91 if forceClass is None and not is_cv: 

92 generic = openmm.XmlSerializer.deserialize(openmmForce) 

93 if not isinstance(generic, cls): 

94 forceClass = f"{cls.__module__}:{cls.__qualname__}" 

95 unit = Unit(unit) 

96 self._wrapped_force = self._deserialize(openmmForce, forceClass) 

97 self.this = self._wrapped_force.this 

98 self._registerCV( 

99 name, 

100 unit, 

101 openmmForce=openmmForce, 

102 unit=unit, 

103 periodicBounds=periodicBounds, 

104 **({} if forceClass is None else {"forceClass": forceClass}), 

105 ) 

106 if periodicBounds is not None: 

107 self._registerPeriodicBounds(*periodicBounds) 

108 

109 @staticmethod 

110 def _deserialize(xml: str, forceClass: str | None) -> openmm.Force: 

111 if forceClass is None: 

112 return openmm.XmlSerializer.deserialize(xml) 

113 module, _, qualname = forceClass.partition(":") 

114 cls = functools.reduce( 

115 getattr, qualname.split("."), importlib.import_module(module) 

116 ) 

117 force = cls.__new__(cls) 

118 force.__setstate__(xml) 

119 return force 

120 

121 def __getattr__(self, name: str) -> t.Any: 

122 return getattr(self._wrapped_force, name) 

123 

124 

125OpenMMForceWrapper.registerTag("!cvpack.OpenMMForceWrapper")