Coverage for openxps/system.py: 100%

45 statements  

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

1""" 

2.. module:: openxps.system 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: System for extended phase-space simulations with OpenMM. 

5 

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

7 

8""" 

9 

10import warnings 

11 

12import openmm as mm 

13 

14from .couplings import Coupling 

15from .dynamical_variable import DynamicalVariable 

16 

17 

18class ExtendedSpaceSystem(mm.System): 

19 """An :OpenMM:`System` object that includes extra dynamical variables (DVs) and 

20 allows for extended phase-space (XPS) simulations. 

21 

22 **Note**: The system provided as argument is modified in place. 

23 

24 Parameters 

25 ---------- 

26 system 

27 The :OpenMM:`System` to be used in the XPS simulation. 

28 coupling 

29 A :class:`Coupling` object, required to couple the physical and extended 

30 phase-space systems. The dynamical variables are obtained from this coupling. 

31 Its forces are moved into ``system``, so a coupling can be part of only one 

32 system. To reuse it, pass a deep copy (``copy.deepcopy(coupling)``). 

33 

34 Example 

35 ------- 

36 >>> import openxps as xps 

37 >>> from math import pi 

38 >>> import openmm 

39 >>> import cvpack 

40 >>> from openmm import unit 

41 >>> from openmmtools import testsystems 

42 >>> model = testsystems.AlanineDipeptideVacuum() 

43 >>> mass = 3 * unit.dalton*(unit.nanometer/unit.radian)**2 

44 >>> phi0 = xps.DynamicalVariable("phi0", unit.radian, mass, xps.CircularBounds()) 

45 >>> harmonic_force = xps.HarmonicCoupling( 

46 ... cvpack.Torsion(6, 8, 14, 16, name="phi"), 

47 ... phi0, 

48 ... 1000 * unit.kilojoules_per_mole / unit.radian**2, 

49 ... ) 

50 >>> system = xps.ExtendedSpaceSystem(model.system, harmonic_force) 

51 >>> system.getDynamicalVariables() 

52 (DynamicalVariable(name='phi0', unit=rad, mass=3 nm**2 Da/(rad**2), bounds=...),) 

53 >>> system.getExtensionSystem().getNumParticles() 

54 1 

55 """ 

56 

57 def __init__( 

58 self, 

59 system: mm.System, 

60 coupling: Coupling, 

61 ) -> None: 

62 if not isinstance(coupling, Coupling): 

63 raise TypeError("The coupling must be an instance of Coupling.") 

64 if not all(force.thisown for force in coupling.getForces()): 

65 raise RuntimeError( 

66 "The coupling is already part of another system. Create a new " 

67 "coupling or pass a deep copy of this one (copy.deepcopy)." 

68 ) 

69 self._coupling = coupling 

70 self._extension_system = mm.System() 

71 for dv in coupling.getDynamicalVariables(): 

72 self._extension_system.addParticle(dv.mass / dv.mass.unit) 

73 coupling.addToExtensionSystem(self._extension_system) 

74 self._checkOtherForces(system) 

75 coupling.addToPhysicalSystem(system) 

76 self._warnAboutLongRangeCorrections(system) 

77 self.this = system.this 

78 

79 def _warnAboutLongRangeCorrections(self, system: mm.System) -> None: 

80 """Warn about long-range corrections that depend on the coupling parameters. 

81 

82 OpenMM computes the long-range correction of a CustomNonbondedForce on the 

83 CPU whenever one of the force's global parameters changes. The coupling 

84 changes its parameters at every step, which can make the correction cost 

85 more than the step itself. 

86 """ 

87 protected = self._coupling.getProtectedParameters() 

88 forces = list(system.getForces()) 

89 while forces: 

90 force = forces.pop() 

91 if isinstance(force, mm.CustomCVForce): 

92 forces.extend( 

93 force.getCollectiveVariable(index) 

94 for index in range(force.getNumCollectiveVariables()) 

95 ) 

96 if not ( 

97 isinstance(force, mm.CustomNonbondedForce) 

98 and force.getUseLongRangeCorrection() 

99 ): 

100 continue 

101 names = { 

102 force.getGlobalParameterName(index) 

103 for index in range(force.getNumGlobalParameters()) 

104 } 

105 if shared := names & protected: 

106 warnings.warn( 

107 f"Force {force.getName()} uses a long-range correction and depends " 

108 "on parameters that change at every step: " 

109 + ", ".join(sorted(shared)) 

110 + ". OpenMM then recomputes the correction on the CPU at every " 

111 "step, which can take longer than the step itself. Unless it is " 

112 "needed, call setUseLongRangeCorrection(False) on this force.", 

113 stacklevel=3, 

114 ) 

115 

116 def _checkOtherForces(self, system: mm.System) -> None: 

117 """Reject forces outside the coupling that depend on its parameters. 

118 

119 The coupling sets these parameters from the dynamical variables, but the 

120 extension system only feels the forces of the coupling itself, so a force 

121 outside it would act on the physical system without a counterpart. 

122 """ 

123 protected = self._coupling.getProtectedParameters() 

124 for force in system.getForces(): 

125 if not hasattr(force, "getNumGlobalParameters"): 

126 continue 

127 names = { 

128 force.getGlobalParameterName(i) 

129 for i in range(force.getNumGlobalParameters()) 

130 } 

131 if shared := names & protected: 

132 raise ValueError( 

133 f"Force {force.getName()} is not part of the coupling but depends " 

134 "on parameters controlled by it: " 

135 + ", ".join(sorted(shared)) 

136 + ". Include this force in the coupling." 

137 ) 

138 

139 def getDynamicalVariables(self) -> tuple[DynamicalVariable]: 

140 """ 

141 Get the dynamical variables included in the extended phase-space system. 

142 

143 Returns 

144 ------- 

145 t.Tuple[DynamicalVariable] 

146 The dynamical variables, converted to MD units. Their order is the one 

147 expected by the methods of :class:`ExtendedSpaceContext` that get or set 

148 the values and velocities of dynamical variables. 

149 """ 

150 return tuple(self._coupling.getDynamicalVariables()) 

151 

152 def getCoupling(self) -> Coupling: 

153 """ 

154 Get the coupling included in the extended phase-space system. 

155 

156 Returns 

157 ------- 

158 Coupling 

159 The coupling. 

160 """ 

161 return self._coupling 

162 

163 def getExtensionSystem(self) -> mm.System: 

164 """ 

165 Get the extension system included in the extended phase-space system. 

166 

167 Returns 

168 ------- 

169 mm.System 

170 The extension system. 

171 """ 

172 return self._extension_system