Coverage for ase/optimize/lbfgs.py: 89.69%

97 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1from typing import IO 

2 

3import numpy as np 

4 

5from ase import Atoms 

6from ase._4.optimize.lbfgs import LBFGSMethod 

7from ase.optimize.optimize import Optimizer 

8from ase.utils import deprecate_positionals 

9from ase.utils.linesearch import LineSearch 

10 

11 

12class LBFGS(Optimizer): 

13 """Limited memory BFGS optimizer. 

14 

15 A limited memory version of the BFGS algorithm. Unlike the BFGS algorithm 

16 used in bfgs.py, the inverse of Hessian matrix is updated. The inverse 

17 Hessian is represented only as a diagonal matrix to save memory 

18 

19 """ 

20 

21 @deprecate_positionals(2) 

22 def __init__( 

23 self, 

24 atoms: Atoms, 

25 restart: str | None = None, 

26 logfile: IO | str = '-', 

27 trajectory: str | None = None, 

28 maxstep: float | None = None, 

29 memory: int = 100, 

30 damping: float = 1.0, 

31 alpha: float = 70.0, 

32 use_line_search: bool = False, 

33 **kwargs, 

34 ): 

35 """ 

36 

37 Parameters 

38 ---------- 

39 atoms: :class:`~ase.Atoms` 

40 The Atoms object to relax. 

41 

42 restart: str 

43 JSON file used to store vectors for updating the inverse of 

44 Hessian matrix. If set, file with such a name will be searched 

45 and information stored will be used, if the file exists. 

46 

47 logfile: file object or str 

48 If *logfile* is a string, a file with that name will be opened. 

49 Use '-' for stdout. 

50 

51 trajectory: string 

52 Trajectory file used to store optimisation path. 

53 

54 maxstep: float 

55 How far is a single atom allowed to move. This is useful for DFT 

56 calculations where wavefunctions can be reused if steps are small. 

57 Default is 0.2 Angstrom. 

58 

59 memory: int 

60 Number of steps to be stored. Default value is 100. Three numpy 

61 arrays of this length containing floats are stored. 

62 

63 damping: float 

64 The calculated step is multiplied with this number before added to 

65 the positions. 

66 

67 alpha: float 

68 Initial guess for the Hessian (curvature of energy surface). A 

69 conservative value of 70.0 is the default, but number of needed 

70 steps to converge might be less if a lower value is used. However, 

71 a lower value also means risk of instability. 

72 

73 kwargs : dict, optional 

74 Extra arguments passed to 

75 :class:`~ase.optimize.optimize.Optimizer`. 

76 

77 

78 Examples 

79 -------- 

80 

81 >>> from ase import Atoms 

82 >>> from ase.optimize import LBFGS 

83 >>> from ase.calculators.emt import EMT 

84 ... 

85 >>> system = Atoms( 

86 ... 'N2', 

87 ... positions = [(0.0, 0.0, 0.0), (0.0, 0.0, 1.1)], 

88 ... calculator=EMT() 

89 ... ) 

90 >>> dyn = LBFGS(system) 

91 >>> dyn.run(fmax=0.05) # doctest:+ELLIPSIS 

92 Step Time Energy fmax 

93 LBFGS: 0 ... 0.440344 3.251800 

94 LBFGS: 1 ... 0.264361 0.347497 

95 LBFGS: 2 ... 0.262860 0.080535 

96 LBFGS: 3 ... 0.262777 0.001453 

97 ... 

98 """ 

99 # Initial approximation of inverse Hessian 1./70. is to emulate the 

100 # behaviour of BFGS. Note that this is never changed! 

101 from ase._4.optimize.optimizable import initial_inverse_position_hessian 

102 

103 H0 = initial_inverse_position_hessian(0, alpha) 

104 self.state = LBFGSMethod(memory=memory, initial_inverse_hessian=H0) 

105 

106 super().__init__(atoms, restart, logfile, trajectory, **kwargs) 

107 

108 H0 = initial_inverse_position_hessian(self.optimizable.ndofs(), alpha) 

109 self.state.H0 = H0 

110 

111 if maxstep is not None: 

112 self.maxstep = maxstep 

113 else: 

114 self.maxstep = self.defaults['maxstep'] 

115 

116 if self.maxstep > 1.0: 

117 raise ValueError( 

118 'You are using a much too large value for ' 

119 + 'the maximum step size: %.1f Angstrom' % self.maxstep 

120 ) 

121 

122 self.damping = damping 

123 self.use_line_search = use_line_search 

124 self.p = None 

125 self.function_calls = 0 

126 self.force_calls = 0 

127 

128 def initialize(self): 

129 """Initialize everything so no checks have to be done in step""" 

130 self.r0 = None 

131 self.f0 = None 

132 self.e0 = None 

133 self.task = 'START' 

134 self.load_restart = False 

135 

136 def read(self): 

137 """Load saved arrays to reconstruct the Hessian""" 

138 i, s, y, rho, self.r0, self.f0, self.e0, self.task = self.load() 

139 self.state.iteration = i 

140 self.state.s = s 

141 self.state.y = y 

142 self.state.rho = rho 

143 self.load_restart = True 

144 

145 def step(self, forces=None): 

146 """Take a single step 

147 

148 Use the given forces, update the history and calculate the next step -- 

149 then take it""" 

150 

151 forces = -self._get_gradient(forces) 

152 pos = self.optimizable.get_x() 

153 self.update(pos, forces, self.r0, self.f0) 

154 

155 self.p = self.state.compute_step(-forces) 

156 

157 g = -forces 

158 if self.use_line_search: 

159 e = self.func(pos) 

160 self.line_search(pos, g, e) 

161 dr = self.alpha_k * self.p 

162 else: 

163 self.force_calls += 1 

164 self.function_calls += 1 

165 dr = self.determine_step(self.p) * self.damping 

166 self.optimizable.set_x(pos + dr) 

167 

168 self.r0 = pos 

169 self.f0 = -g 

170 tmp = self.state.iteration, self.state.s, self.state.y, self.state.rho 

171 self.dump((*tmp, self.r0, self.f0, self.e0, self.task)) 

172 

173 def determine_step(self, dr): 

174 """Determine step to take according to maxstep 

175 

176 Normalize all steps as the largest step. This way 

177 we still move along the eigendirection. 

178 """ 

179 longest_step = self.optimizable.gradient_norm(dr) 

180 if longest_step >= self.maxstep: 

181 dr *= self.maxstep / longest_step 

182 

183 return dr 

184 

185 def update(self, pos, forces, r0, f0): 

186 """Update everything that is kept in memory 

187 

188 This function is mostly here to allow for replay_trajectory. 

189 """ 

190 if self.state.iteration > 0: 

191 self.state.update(pos, -forces, r0, -f0) 

192 

193 def _replay_trajectory(self, traj): 

194 """Initialize history from old trajectory.""" 

195 r0 = None 

196 f0 = None 

197 # The last element is not added, as we get that for free when taking 

198 # the first qn-step after the replay 

199 for i in range(len(traj) - 1): 

200 pos = traj[i].get_positions().ravel() 

201 forces = traj[i].get_forces().ravel() 

202 self.update(pos, forces, r0, f0) 

203 r0 = pos.copy() 

204 f0 = forces.copy() 

205 self.state.iteration += 1 

206 self.r0 = r0 

207 self.f0 = f0 

208 

209 def func(self, x): 

210 """Objective function for use of the optimizers""" 

211 self.optimizable.set_x(x) 

212 self.function_calls += 1 

213 return self.optimizable.get_value() 

214 

215 def fprime(self, x): 

216 """Gradient of the objective function for use of the optimizers""" 

217 self.optimizable.set_x(x) 

218 self.force_calls += 1 

219 return self.optimizable.get_gradient() 

220 

221 def line_search(self, r, g, e): 

222 p_size = np.sqrt((self.p**2).sum()) 

223 if p_size <= np.sqrt(self.optimizable.ndofs() / 3 * 1e-10): 

224 self.p /= p_size / np.sqrt(self.optimizable.ndofs() / 3 * 1e-10) 

225 ls = LineSearch(get_gradient_norm=self.optimizable.gradient_norm) 

226 self.alpha_k, e, self.e0, self.no_update = ls._line_search( 

227 self.func, 

228 self.fprime, 

229 r, 

230 self.p, 

231 g, 

232 e, 

233 self.e0, 

234 maxstep=self.maxstep, 

235 c1=0.23, 

236 c2=0.46, 

237 stpmax=50.0, 

238 ) 

239 if self.alpha_k is None: 

240 raise RuntimeError('LineSearch failed!') 

241 

242 

243class LBFGSLineSearch(LBFGS): 

244 """This optimizer uses the LBFGS algorithm, but does a line search that 

245 fulfills the Wolff conditions. 

246 """ 

247 

248 def __init__(self, *args, **kwargs): 

249 kwargs['use_line_search'] = True 

250 super().__init__(*args, **kwargs)