Coverage for ase/_4/optimize/run.py: 96.99%

133 statements  

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

1from __future__ import annotations 

2 

3import json 

4from collections.abc import Iterator 

5from dataclasses import dataclass 

6from pathlib import Path 

7from typing import Any 

8 

9import numpy as np 

10 

11from ase._4.optimize.lbfgs import OptimizerMethod 

12from ase._4.optimize.optimizable import Optimizable4 

13from ase.dependencies import ase_version_info 

14from ase.io.jsonio import default, object_hook 

15from ase.io.trajectory import Trajectory 

16from ase.parallel import world 

17 

18 

19def toplevel_header(target, method): 

20 import datetime 

21 

22 now = datetime.datetime.now() 

23 timestamp = now.strftime('%Y-%m-%d %H:%M:%S') 

24 

25 # Log initialization 

26 # Log fmax/smax if known? 

27 # Allow each object to write description of itself 

28 

29 return ( 

30 f'{ase_version_info()}\n' 

31 f"Optimizing '{target.__class__.__name__}' " 

32 f'using method {method.methodname!r} ' 

33 f'starting {timestamp}\n\n' 

34 ) 

35 

36 

37class Optimizer: 

38 def __init__( 

39 self, 

40 target: Optimizable4, 

41 method: OptimizerMethod, 

42 trajectory=None, 

43 restartfile=None, 

44 comm=world, 

45 logfile='-', 

46 step: Step | None = None, 

47 maxstep: float = 0.2, 

48 ): 

49 from ase.optimize.optimize import Log 

50 

51 self.log = Log(logfile, comm) 

52 self.comm = comm 

53 self.target = target 

54 self.method = method 

55 self.trajectory = trajectory 

56 if restartfile is not None: 

57 restartfile = Path(restartfile) 

58 self.restartfile = restartfile 

59 # TODO We need both "restart from" and "save restart to", somehow. 

60 # Altough maybe that feature can come via a classmethod 

61 self.maxstep = maxstep 

62 self.step = step 

63 

64 # If we don't have self.step, then restarting would need to 

65 # pass the step to run(), which may be awkward. 

66 # But having self.step is also awkward. 

67 

68 def run(self, *, steps: int | None = None) -> Step: 

69 for _ in self.irun(steps=steps): 

70 pass 

71 # Note: This may take zero steps, but self.step is always non-None 

72 assert self.step is not None 

73 return self.step 

74 

75 def irun(self, *, steps: int | None = None) -> Iterator[Step]: 

76 self.log.write(toplevel_header(self.target, self.method)) 

77 if self.step is None: 

78 # XXX does not allow the method to write anything. 

79 if hasattr(self.target, 'log_headers'): 

80 self.log.write(self.target.log_headers()) 

81 self.log.write('\n') 

82 self.step = Step.start(self.target) 

83 self._writefiles(self.step) 

84 yield self.step 

85 

86 if steps is not None: 

87 # (We may start from "step 17" if we restart) 

88 steps += self.step.i 

89 

90 def check_stop(step): 

91 # Would it be better to raise an error if we don't converge, 

92 # or should there be an option for doing so? 

93 return step.gradient_obj.converged or step.i == steps 

94 

95 while not check_stop(self.step): 

96 # (Both method and target change in this update) 

97 self.step = next_step( 

98 self.target, self.method, self.step, self.maxstep 

99 ) 

100 self._writefiles(self.step) 

101 yield self.step 

102 

103 self.log.write(f'\nOptimization ended with step {self.step.i}.\n') 

104 

105 def _writefiles(self, step): 

106 # XXX Also need to pass method, at least. 

107 # Or maybe method should log to a separate line. 

108 if hasattr(self.target, 'step_to_string'): 

109 self.log.write(self.target.step_to_string(step)) 

110 self.log.write('\n') 

111 else: 

112 write_to_log(self.method, self.log, self.step) 

113 if self.trajectory is not None: 

114 write_to_traj(self.target, self.trajectory, self.comm) 

115 if self.restartfile is not None and self.comm.rank == 0: 

116 write_restartfile(self.restartfile, self.method, self.target, step) 

117 

118 @classmethod 

119 def restart(cls, restartfile, calc, **kwargs): 

120 # We need these read behaviours: 

121 # * Start from scratch 

122 # * Read this file 

123 # * Read this file if it exists, else start from scratch 

124 # 

125 # ... and these write behaviours: 

126 # 

127 # * Do not write 

128 # * Write to this file 

129 # * Write to file we restarted from 

130 

131 # Since this method has "calc", it doesn't really belong on this 

132 # class (we know about Targets etc. but not calcs). 

133 # Maybe therefore this should be a standalone function. 

134 target, method, step = read_restartfile(restartfile, calc) 

135 return cls(target=target, method=method, step=step, **kwargs) 

136 

137 

138@dataclass 

139class Step: 

140 i: int 

141 x: np.ndarray 

142 gradient_obj: Any 

143 value: float 

144 

145 @classmethod 

146 def start(cls, target: Optimizable4) -> Step: 

147 step = cls(0, target.get_x(), target.get_gradient(), target.get_value()) 

148 assert step.gradient_obj.gradient.shape == (len(step.x),) 

149 return step 

150 

151 def datafy(self) -> dict[str, Any]: 

152 return { 

153 'i': self.i, 

154 'x': self.x.tolist(), 

155 'gradient_obj': self.gradient_obj.datafy(), 

156 'value': self.value, 

157 } 

158 

159 @classmethod 

160 def undatafy(cls, dct, gradient_obj): 

161 return cls( 

162 i=dct['i'], 

163 x=np.array(dct['x']), 

164 gradient_obj=gradient_obj, 

165 value=dct['value'], 

166 ) 

167 

168 

169def next_step( 

170 target: Optimizable4, 

171 method: OptimizerMethod, 

172 step: Step, 

173 maxstep: float | None, 

174) -> Step: 

175 dx = method.compute_step(step.gradient_obj.gradient) 

176 # TODO We do not have maxstep right now. This will not run the same 

177 # as legacy optimizations until we apply a maxstep. 

178 

179 # Questionable: We are using the function for computing norm of 

180 # the gradient to compute norm of another vector. 

181 if maxstep is not None: 

182 longest = target.gradient_norm(dx) 

183 if longest > maxstep: 

184 scale = maxstep / longest 

185 dx *= scale 

186 

187 # Target may apply constraints or other magic, so we may not 

188 # get the same x back as the one we set. 

189 target.set_x(step.x + dx) 

190 

191 newstep = Step( 

192 i=step.i + 1, 

193 x=target.get_x(), 

194 gradient_obj=target.get_gradient(), 

195 value=target.get_value(), 

196 ) 

197 

198 method.update( 

199 newstep.x, 

200 newstep.gradient_obj.gradient, 

201 step.x, 

202 step.gradient_obj.gradient, 

203 ) 

204 return newstep 

205 

206 

207def write_to_log(method, log, step): 

208 loginfo = step.gradient_obj.loginfo() 

209 name = method.methodname 

210 txt = ' '.join(f'{key}={value:e}' for key, value in loginfo.items()) 

211 msg = f'{name} i={step.i:4d} e={step.value:f} {txt}\n' 

212 log.write(msg) 

213 

214 

215def write_to_traj(target, trajpath, comm): 

216 with Trajectory(trajpath, comm=comm, mode='a') as traj: 

217 # TODO we are not setting metadata (like old optimizers) 

218 traj.write(target) 

219 

220 

221def read_images(trajpath): 

222 with Trajectory(trajpath) as traj: 

223 return [*traj] 

224 

225 

226def write_restartfile(restartfile, method, target, step): 

227 # TODO Unsafe if we just overwrite, we should backup/delete to prevent 

228 # accidental partial save 

229 

230 # Still need some things, like maximum iterations. 

231 # How about trajectory writing, logfile settings, etc.? 

232 # General observers obviously cannot be saved. 

233 savedata = { 

234 'method': [method.iotype, method.datafy()], 

235 'target': [target.iotype, target.datafy()], 

236 'step': step.datafy(), 

237 } 

238 json_text = json.dumps(savedata, default=default) 

239 restartfile.write_text(json_text) 

240 

241 

242def read_restartfile(restartfile, calc) -> tuple: 

243 json_text = restartfile.read_text() 

244 dct = json.loads(json_text, object_hook=object_hook) 

245 

246 assert {*dct} == {'method', 'target', 'step'} 

247 method_iotype, method_data = dct['method'] 

248 target_iotype, target_dct = dct['target'] 

249 

250 if method_iotype == 'bfgs': 

251 from ase._4.optimize.bfgs import BFGSMethod 

252 

253 method = BFGSMethod.undatafy(method_data) 

254 elif method_iotype == 'lbfgs': 

255 from ase._4.optimize.lbfgs import LBFGSMethod 

256 

257 method = LBFGSMethod.undatafy(method_data) 

258 else: 

259 raise ValueError(f'No such method: {method_iotype!r}') 

260 

261 if target_iotype == 'frechet': 

262 from ase._4.optimize.frechet import FrechetOptimizable 

263 

264 target = FrechetOptimizable.undatafy(target_dct, calc) 

265 elif target_iotype == 'symopt': 

266 from ase._4.optimize.symopt import SymOpt 

267 

268 target = SymOpt.undatafy(target_dct, calc) 

269 else: 

270 raise ValueError(f'No such target: {target_iotype!r}') 

271 

272 gradient_obj = target.undatafy_gradient(dct['step']['gradient_obj']) 

273 step = Step.undatafy(dct['step'], gradient_obj) 

274 

275 return target, method, step