Coverage for ase/calculators/checkpoint.py: 86.58%

149 statements  

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

1"""Checkpointing and restart functionality for scripts using ASE Atoms objects. 

2 

3Initialize checkpoint object: 

4 

5CP = Checkpoint('checkpoints.db') 

6 

7Checkpointed code block in try ... except notation: 

8 

9try: 

10 a, C, C_err = CP.load() 

11except NoCheckpoint: 

12 C, C_err = fit_elastic_constants(a) 

13 CP.save(a, C, C_err) 

14 

15Checkpoint code block, shorthand notation: 

16 

17C, C_err = CP(fit_elastic_constants)(a) 

18 

19Example for checkpointing within an iterative loop, e.g. for searching crack 

20tip position: 

21 

22try: 

23 a, converged, tip_x, tip_y = CP.load() 

24except NoCheckpoint: 

25 converged = False 

26 tip_x = tip_x0 

27 tip_y = tip_y0 

28while not converged: 

29 ... do something to find better crack tip position ... 

30 converged = ... 

31 CP.flush(a, converged, tip_x, tip_y) 

32 

33The simplest way to use checkpointing is through the CheckpointCalculator. It 

34wraps any calculator object and does a checkpoint whenever a calculation 

35is performed: 

36 

37 calc = ... 

38 cp_calc = CheckpointCalculator(calc) 

39 atoms.calc = cp_calc 

40 e = atoms.get_potential_energy() # 1st time, does calc, writes to checkfile 

41 # subsequent runs, reads from checkpoint 

42""" 

43 

44from typing import Any 

45 

46import numpy as np 

47 

48import ase 

49from ase.calculators.calculator import Calculator 

50from ase.db import connect 

51 

52 

53class NoCheckpoint(Exception): 

54 pass 

55 

56 

57class DevNull: 

58 def write(str, *args): 

59 pass 

60 

61 

62class Checkpoint: 

63 _value_prefix = '_values_' 

64 

65 def __init__(self, db='checkpoints.db', logfile=None): 

66 self.db = db 

67 if logfile is None: 

68 logfile = DevNull() 

69 self.logfile = logfile 

70 

71 self.checkpoint_id = [0] 

72 self.in_checkpointed_region = False 

73 

74 def __call__(self, func, *args, **kwargs): 

75 checkpoint_func_name = str(func) 

76 

77 def decorated_func(*args, **kwargs): 

78 # Get the first ase.Atoms object. 

79 atoms = None 

80 for a in args: 

81 if atoms is None and isinstance(a, ase.Atoms): 

82 atoms = a 

83 

84 try: 

85 retvals = self.load(atoms=atoms) 

86 except NoCheckpoint: 

87 retvals = func(*args, **kwargs) 

88 if isinstance(retvals, tuple): 

89 self.save( 

90 *retvals, 

91 atoms=atoms, 

92 checkpoint_func_name=checkpoint_func_name, 

93 ) 

94 else: 

95 self.save( 

96 retvals, 

97 atoms=atoms, 

98 checkpoint_func_name=checkpoint_func_name, 

99 ) 

100 return retvals 

101 

102 return decorated_func 

103 

104 def _increase_checkpoint_id(self): 

105 if self.in_checkpointed_region: 

106 self.checkpoint_id += [1] 

107 else: 

108 self.checkpoint_id[-1] += 1 

109 self.logfile.write( 

110 'Entered checkpoint region {}.\n'.format(self.checkpoint_id) 

111 ) 

112 

113 self.in_checkpointed_region = True 

114 

115 def _decrease_checkpoint_id(self): 

116 self.logfile.write( 

117 'Leaving checkpoint region {}.\n'.format(self.checkpoint_id) 

118 ) 

119 if not self.in_checkpointed_region: 

120 self.checkpoint_id = self.checkpoint_id[:-1] 

121 assert len(self.checkpoint_id) >= 1 

122 self.in_checkpointed_region = False 

123 assert self.checkpoint_id[-1] >= 1 

124 

125 def _mangled_checkpoint_id(self): 

126 """ 

127 Returns a mangled checkpoint id string: 

128 check_c_1:c_2:c_3:... 

129 E.g. if checkpoint is nested and id is [3,2,6] it returns: 

130 'check3:2:6' 

131 """ 

132 return 'check' + ':'.join(str(id) for id in self.checkpoint_id) 

133 

134 def load(self, atoms=None): 

135 """ 

136 Retrieve checkpoint data from file. If atoms object is specified, then 

137 the calculator connected to that object is copied to all returning 

138 atoms object. 

139 

140 Returns tuple of values as passed to flush or save during checkpoint 

141 write. 

142 """ 

143 self._increase_checkpoint_id() 

144 

145 retvals = [] 

146 with connect(self.db) as db: 

147 try: 

148 dbentry = db.get(checkpoint_id=self._mangled_checkpoint_id()) 

149 except KeyError: 

150 raise NoCheckpoint 

151 

152 data = dbentry.data 

153 atomsi = data['checkpoint_atoms_args_index'] 

154 i = 0 

155 while i == atomsi or f'{self._value_prefix}{i}' in data: 

156 if i == atomsi: 

157 newatoms = dbentry.toatoms() 

158 if atoms is not None: 

159 # Assign calculator 

160 newatoms.calc = atoms.calc 

161 retvals += [newatoms] 

162 else: 

163 retvals += [data[f'{self._value_prefix}{i}']] 

164 i += 1 

165 

166 self.logfile.write( 

167 'Successfully restored checkpoint {}.\n'.format(self.checkpoint_id) 

168 ) 

169 self._decrease_checkpoint_id() 

170 if len(retvals) == 1: 

171 return retvals[0] 

172 else: 

173 return tuple(retvals) 

174 

175 def _flush(self, *args, **kwargs): 

176 data = {f'{self._value_prefix}{i}': v for i, v in enumerate(args)} 

177 

178 try: 

179 atomsi = [isinstance(v, ase.Atoms) for v in args].index(True) 

180 atoms = args[atomsi] 

181 del data[f'{self._value_prefix}{atomsi}'] 

182 except ValueError: 

183 atomsi = -1 

184 try: 

185 atoms = kwargs['atoms'] 

186 except KeyError: 

187 raise RuntimeError('No atoms object provided in arguments.') 

188 

189 try: 

190 del kwargs['atoms'] 

191 except KeyError: 

192 pass 

193 

194 data['checkpoint_atoms_args_index'] = atomsi 

195 data.update(kwargs) 

196 

197 with connect(self.db) as db: 

198 try: 

199 dbentry = db.get(checkpoint_id=self._mangled_checkpoint_id()) 

200 del db[dbentry.id] 

201 except KeyError: 

202 pass 

203 db.write( 

204 atoms, checkpoint_id=self._mangled_checkpoint_id(), data=data 

205 ) 

206 

207 self.logfile.write( 

208 'Successfully stored checkpoint {}.\n'.format(self.checkpoint_id) 

209 ) 

210 

211 def flush(self, *args, **kwargs): 

212 """ 

213 Store data to a checkpoint without increasing the checkpoint id. This 

214 is useful to continuously update the checkpoint state in an iterative 

215 loop. 

216 """ 

217 # If we are flushing from a successfully restored checkpoint, then 

218 # in_checkpointed_region will be set to False. We need to reset to True 

219 # because a call to flush indicates that this checkpoint is still 

220 # active. 

221 self.in_checkpointed_region = False 

222 self._flush(*args, **kwargs) 

223 

224 def save(self, *args, **kwargs): 

225 """ 

226 Store data to a checkpoint and increase the checkpoint id. This closes 

227 the checkpoint. 

228 """ 

229 self._decrease_checkpoint_id() 

230 self._flush(*args, **kwargs) 

231 

232 

233def atoms_almost_equal(a, b, tol=1e-9): 

234 return ( 

235 np.abs(a.positions - b.positions).max() < tol 

236 and (a.numbers == b.numbers).all() 

237 and np.abs(a.cell - b.cell).max() < tol 

238 and (a.pbc == b.pbc).all() 

239 ) 

240 

241 

242class CheckpointCalculator(Calculator): 

243 """ 

244 This wraps any calculator object to checkpoint whenever a calculation 

245 is performed. 

246 

247 This is particularly useful for expensive calculators, e.g. DFT and 

248 allows usage of complex workflows. 

249 

250 Example usage: 

251 

252 calc = ... 

253 cp_calc = CheckpointCalculator(calc) 

254 atoms.calc = cp_calc 

255 e = atoms.get_potential_energy() 

256 # 1st time, does calc, writes to checkfile 

257 # subsequent runs, reads from checkpoint file 

258 """ 

259 

260 implemented_properties = ase.calculators.calculator.all_properties 

261 default_parameters: dict[str, Any] = {} 

262 name = 'CheckpointCalculator' 

263 

264 property_to_method_name = { 

265 'energy': 'get_potential_energy', 

266 'energies': 'get_potential_energies', 

267 'forces': 'get_forces', 

268 'stress': 'get_stress', 

269 'stresses': 'get_stresses', 

270 } 

271 

272 def __init__(self, calculator, db='checkpoints.db', logfile=None): 

273 Calculator.__init__(self) 

274 self.calculator = calculator 

275 if logfile is None: 

276 logfile = DevNull() 

277 self.checkpoint = Checkpoint(db, logfile) 

278 self.logfile = logfile 

279 

280 def calculate(self, atoms, properties, system_changes): 

281 Calculator.calculate(self, atoms, properties, system_changes) 

282 try: 

283 results = self.checkpoint.load(atoms) 

284 prev_atoms, results = results[0], results[1:] 

285 if not atoms_almost_equal(atoms, prev_atoms): 

286 raise RuntimeError( 

287 'mismatch between current atoms and ' 

288 'those read from checkpoint file' 

289 ) 

290 self.logfile.write( 

291 'retrieved results for {} from checkpoint\n'.format(properties) 

292 ) 

293 # save results in calculator for next time 

294 if isinstance(self.calculator, Calculator): 

295 if not hasattr(self.calculator, 'results'): 

296 self.calculator.results = {} 

297 self.calculator.results.update(dict(zip(properties, results))) 

298 except NoCheckpoint: 

299 if isinstance(self.calculator, Calculator): 

300 self.logfile.write( 

301 'doing calculation of {} with new-style ' 

302 'calculator interface\n'.format(properties) 

303 ) 

304 self.calculator.calculate(atoms, properties, system_changes) 

305 results = [self.calculator.results[prop] for prop in properties] 

306 else: 

307 self.logfile.write( 

308 'doing calculation of {} with old-style ' 

309 'calculator interface\n'.format(properties) 

310 ) 

311 results = [] 

312 for prop in properties: 

313 method_name = self.property_to_method_name[prop] 

314 method = getattr(self.calculator, method_name) 

315 results.append(method(atoms)) 

316 _calculator = atoms.calc 

317 try: 

318 atoms.calc = self.calculator 

319 self.checkpoint.save(atoms, *results) 

320 finally: 

321 atoms.calc = _calculator 

322 

323 self.results = dict(zip(properties, results))