Coverage for cvpack/base_path_cv.py: 98%

61 statements  

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

1""" 

2.. class:: BasePathCV 

3 :platform: Linux, MacOS, Windows 

4 :synopsis: A base class for path-related collective variables 

5 

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

7 

8""" 

9 

10import re 

11import typing as t 

12from collections import OrderedDict 

13from copy import deepcopy 

14 

15import numpy as np 

16import openmm 

17 

18from .collective_variable import CollectiveVariable 

19from .path import Metric, deviation, progress 

20 

21# OpenMM's limit on the number of collective variables of a CustomCVForce 

22MAX_CVS = 32 

23 

24 

25def _kernel_sum_expression( 

26 squared_distances: t.Sequence[str], 

27 lam: float, 

28 progress_terms: t.Sequence[str] | None = None, 

29 divisor: float = 1, 

30) -> str: 

31 """ 

32 Return an expression for the soft minimum of the squared distances, or, if 

33 ``progress_terms`` is given, for the average of these terms weighted by the 

34 Gaussian kernels and divided by ``divisor``. 

35 """ 

36 n = len(squared_distances) 

37 definitions = OrderedDict( 

38 {f"x{i}": sqdist for i, sqdist in enumerate(squared_distances)} 

39 ) 

40 definitions["lambda"] = lam 

41 definitions["xmin0"] = "x0" 

42 for i in range(1, n): 

43 definitions[f"xmin{i}"] = f"min(xmin{i - 1},x{i})" 

44 # Shifting all exponents by about the smallest squared distance keeps the 

45 # weights between exp(-1) and 1 for the nearest milestone. The metrics do not 

46 # depend on the shift, and floor() has a zero derivative, so the derivatives 

47 # of the expression do not contain those of the chain of minima, which made 

48 # Context creation scale steeply with the number of milestones. 

49 definitions["shift"] = f"floor(lambda*xmin{n - 1})/lambda" 

50 for i in range(n): 

51 definitions[f"w{i}"] = f"exp(lambda*(shift-x{i}))" 

52 definitions["wsum"] = "+".join(f"w{i}" for i in range(n)) 

53 expressions = [f"{key}={value}" for key, value in definitions.items()] 

54 if progress_terms is None: 

55 expressions.append("shift-log(wsum)/lambda") 

56 else: 

57 numerator = "+".join( 

58 f"{term}*w{i}" for i, term in enumerate(progress_terms) if term != "0" 

59 ) 

60 expressions.append(f"({numerator or 0})/({divisor}*wsum)") 

61 return "; ".join(reversed(expressions)) 

62 

63 

64def _make_cv_force( 

65 expression: str, variables: dict[str, CollectiveVariable] 

66) -> openmm.CustomCVForce: 

67 force = openmm.CustomCVForce(expression) 

68 for name, variable in variables.items(): 

69 # Each force takes ownership of its variables, which cannot be shared 

70 force.addCollectiveVariable(name, deepcopy(variable)) 

71 return force 

72 

73 

74class BasePathCV(CollectiveVariable, openmm.CustomCVForce): 

75 """ 

76 A base class for path-related collective variables 

77 

78 Parameters 

79 ---------- 

80 metric 

81 A measure of progress or deviation with respect to a path in CV space 

82 sigma 

83 The width of the Gaussian kernels 

84 squared_distances 

85 Expressions for the squared distance to each milestone 

86 variables 

87 A dictionary of collective variables used in the expressions for the squared 

88 distances 

89 """ 

90 

91 def __init__( 

92 self, 

93 metric: Metric, 

94 sigma: float, 

95 squared_distances: t.Sequence[str], 

96 variables: dict[str, CollectiveVariable], 

97 ) -> None: 

98 n = len(squared_distances) 

99 lam = 1 / (2 * sigma**2) 

100 progress_terms = [str(i) for i in range(n)] if metric == progress else None 

101 if len(variables) <= MAX_CVS: 

102 super().__init__( 

103 _kernel_sum_expression(squared_distances, lam, progress_terms, n - 1) 

104 ) 

105 for name, variable in variables.items(): 

106 self.addCollectiveVariable(name, variable) 

107 return 

108 # A CustomCVForce cannot have more than MAX_CVS variables, so each chunk of 

109 # milestones becomes an inner CustomCVForce. The deviation is a soft minimum, 

110 # which can be taken over the soft minima of the chunks. The progress also 

111 # needs the progress within each chunk, weighted by the chunk's kernel sum. 

112 forces_per_chunk = 1 if metric == deviation else 2 

113 num_chunks = -(-n // MAX_CVS) 

114 if forces_per_chunk * num_chunks > MAX_CVS: 

115 raise ValueError( 

116 f"A path with {metric.name} metric supports at most " 

117 f"{MAX_CVS * MAX_CVS // forces_per_chunk} milestones." 

118 ) 

119 outer_variables = {} 

120 for c, chunk in enumerate(np.array_split(np.arange(n), num_chunks)): 

121 chunk_distances = [squared_distances[i] for i in chunk] 

122 chunk_variables = { 

123 name: variable 

124 for name, variable in variables.items() 

125 if any(re.search(rf"\b{name}\b", x) for x in chunk_distances) 

126 } 

127 outer_variables[f"z{c}"] = _make_cv_force( 

128 _kernel_sum_expression(chunk_distances, lam), chunk_variables 

129 ) 

130 if metric == progress: 

131 outer_variables[f"s{c}"] = _make_cv_force( 

132 _kernel_sum_expression( 

133 chunk_distances, lam, [str(i) for i in chunk], n - 1 

134 ), 

135 chunk_variables, 

136 ) 

137 super().__init__( 

138 _kernel_sum_expression( 

139 [f"z{c}" for c in range(num_chunks)], 

140 lam, 

141 [f"s{c}" for c in range(num_chunks)] if metric == progress else None, 

142 ) 

143 ) 

144 for name, variable in outer_variables.items(): 

145 self.addCollectiveVariable(name, variable) 

146 

147 def _generateName(self, metric: Metric, name: str, kind: str) -> str: 

148 if metric not in (progress, deviation): 

149 raise ValueError( 

150 "Invalid metric. Use 'cvpack.path.progress' or 'cvpack.path.deviation'." 

151 ) 

152 if name is None: 

153 return f"path_{metric.name}_in_{kind}_space" 

154 return name