Coverage for ase/io/pickletrajectory.py: 76.87%

268 statements  

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

1import collections 

2import errno 

3import os 

4import pickle 

5import sys 

6import warnings 

7 

8import numpy as np 

9 

10from ase.atoms import Atoms 

11from ase.calculators.calculator import PropertyNotImplementedError 

12from ase.calculators.singlepoint import SinglePointCalculator 

13from ase.constraints import FixAtoms 

14from ase.parallel import barrier, world 

15 

16 

17class PickleTrajectory: 

18 """Reads/writes Atoms objects into a .traj file.""" 

19 

20 # Per default, write these quantities 

21 write_energy = True 

22 write_forces = True 

23 write_stress = True 

24 write_charges = True 

25 write_magmoms = True 

26 write_momenta = True 

27 write_info = True 

28 

29 def __init__( 

30 self, 

31 filename, 

32 mode='r', 

33 atoms=None, 

34 master=None, 

35 backup=True, 

36 _warn=True, 

37 ): 

38 """A PickleTrajectory can be created in read, write or append mode. 

39 

40 Parameters 

41 ---------- 

42 

43 filename: 

44 The name of the parameter file. Should end in .traj. 

45 

46 mode='r': 

47 The mode. 

48 

49 'r' is read mode, the file should already exist, and 

50 no atoms argument should be specified. 

51 

52 'w' is write mode. If the file already exists, it is 

53 renamed by appending .bak to the file name. The atoms 

54 argument specifies the Atoms object to be written to the 

55 file, if not given it must instead be given as an argument 

56 to the write() method. 

57 

58 'a' is append mode. It acts a write mode, except that 

59 data is appended to a preexisting file. 

60 

61 atoms=None: 

62 The Atoms object to be written in write or append mode. 

63 

64 master=None: 

65 Controls which process does the actual writing. The 

66 default is that process number 0 does this. If this 

67 argument is given, processes where it is True will write. 

68 

69 backup=True: 

70 Use backup=False to disable renaming of an existing file. 

71 """ 

72 

73 if _warn: 

74 msg = 'Please stop using old trajectory files!' 

75 if mode == 'r': 

76 msg += ( 

77 '\nConvert to the new future-proof format like this:\n' 

78 '\n $ python3 -m ase.io.trajectory ' + filename + '\n' 

79 ) 

80 

81 raise RuntimeError(msg) 

82 

83 self.numbers = None 

84 self.pbc = None 

85 self.sanitycheck = True 

86 self.pre_observers = [] # Callback functions before write 

87 self.post_observers = [] # Callback functions after write 

88 

89 # Counter used to determine when callbacks are called: 

90 self.write_counter = 0 

91 

92 self.offsets = [] 

93 if master is None: 

94 master = world.rank == 0 

95 self.master = master 

96 self.backup = backup 

97 self.set_atoms(atoms) 

98 self.open(filename, mode) 

99 

100 def open(self, filename, mode): 

101 """Opens the file. 

102 

103 For internal use only. 

104 """ 

105 self.fd = filename 

106 if mode == 'r': 

107 if isinstance(filename, str): 

108 self.fd = open(filename, 'rb') 

109 self.read_header() 

110 elif mode == 'a': 

111 exists = True 

112 if isinstance(filename, str): 

113 exists = os.path.isfile(filename) 

114 if exists: 

115 exists = os.path.getsize(filename) > 0 

116 if exists: 

117 self.fd = open(filename, 'rb') 

118 self.read_header() 

119 self.fd.close() 

120 barrier() 

121 if self.master: 

122 self.fd = open(filename, 'ab+') 

123 else: 

124 self.fd = open(os.devnull, 'ab+') 

125 elif mode == 'w': 

126 if self.master: 

127 if isinstance(filename, str): 

128 if self.backup and os.path.isfile(filename): 

129 try: 

130 os.rename(filename, filename + '.bak') 

131 except OSError as e: 

132 # this must run on Win only! Not atomic! 

133 if e.errno != errno.EEXIST: 

134 raise 

135 os.unlink(filename + '.bak') 

136 os.rename(filename, filename + '.bak') 

137 self.fd = open(filename, 'wb') 

138 else: 

139 self.fd = open(os.devnull, 'wb') 

140 else: 

141 raise ValueError('mode must be "r", "w" or "a".') 

142 

143 def set_atoms(self, atoms=None): 

144 """Associate an Atoms object with the trajectory. 

145 

146 Mostly for internal use. 

147 """ 

148 if atoms is not None and not hasattr(atoms, 'get_positions'): 

149 raise TypeError('"atoms" argument is not an Atoms object.') 

150 self.atoms = atoms 

151 

152 def read_header(self): 

153 if hasattr(self.fd, 'name'): 

154 if os.path.isfile(self.fd.name): 

155 if os.path.getsize(self.fd.name) == 0: 

156 return 

157 self.fd.seek(0) 

158 try: 

159 if self.fd.read(len('PickleTrajectory')) != b'PickleTrajectory': 

160 raise OSError('This is not a trajectory file!') 

161 d = pickle.load(self.fd) 

162 except EOFError: 

163 raise EOFError('Bad trajectory file.') 

164 

165 self.pbc = d['pbc'] 

166 self.numbers = d['numbers'] 

167 self.tags = d.get('tags') 

168 self.masses = d.get('masses') 

169 self.constraints = dict2constraints(d) 

170 self.offsets.append(self.fd.tell()) 

171 

172 def write(self, atoms=None): 

173 if atoms is None: 

174 atoms = self.atoms 

175 

176 for image in atoms.iterimages(): 

177 self._write_atoms(image) 

178 

179 def _write_atoms(self, atoms): 

180 """Write the atoms to the file. 

181 

182 If the atoms argument is not given, the atoms object specified 

183 when creating the trajectory object is used. 

184 """ 

185 self._call_observers(self.pre_observers) 

186 

187 if len(self.offsets) == 0: 

188 self.write_header(atoms) 

189 else: 

190 if (atoms.pbc != self.pbc).any(): 

191 raise ValueError('Bad periodic boundary conditions!') 

192 elif self.sanitycheck and len(atoms) != len(self.numbers): 

193 raise ValueError('Bad number of atoms!') 

194 elif self.sanitycheck and (atoms.numbers != self.numbers).any(): 

195 raise ValueError('Bad atomic numbers!') 

196 

197 if atoms.has('momenta'): 

198 momenta = atoms.get_momenta() 

199 else: 

200 momenta = None 

201 

202 d = { 

203 'positions': atoms.get_positions(), 

204 'cell': atoms.get_cell(), 

205 'momenta': momenta, 

206 } 

207 

208 if atoms.calc is not None: 

209 if self.write_energy: 

210 d['energy'] = atoms.get_potential_energy() 

211 if self.write_forces: 

212 assert self.write_energy 

213 try: 

214 d['forces'] = atoms.get_forces(apply_constraint=False) 

215 except PropertyNotImplementedError: 

216 pass 

217 if self.write_stress: 

218 assert self.write_energy 

219 try: 

220 d['stress'] = atoms.get_stress() 

221 except PropertyNotImplementedError: 

222 pass 

223 if self.write_charges: 

224 try: 

225 d['charges'] = atoms.get_charges() 

226 except PropertyNotImplementedError: 

227 pass 

228 if self.write_magmoms: 

229 try: 

230 magmoms = atoms.get_magnetic_moments() 

231 if any(np.asarray(magmoms).flat): 

232 d['magmoms'] = magmoms 

233 except (PropertyNotImplementedError, AttributeError): 

234 pass 

235 

236 if 'magmoms' not in d and atoms.has('initial_magmoms'): 

237 d['magmoms'] = atoms.get_initial_magnetic_moments() 

238 if 'charges' not in d and atoms.has('initial_charges'): 

239 charges = atoms.get_initial_charges() 

240 if (charges != 0).any(): 

241 d['charges'] = charges 

242 

243 if self.write_info: 

244 d['info'] = stringnify_info(atoms.info) 

245 

246 if self.master: 

247 pickle.dump(d, self.fd, protocol=2) 

248 self.fd.flush() 

249 self.offsets.append(self.fd.tell()) 

250 self._call_observers(self.post_observers) 

251 self.write_counter += 1 

252 

253 def write_header(self, atoms): 

254 self.fd.write(b'PickleTrajectory') 

255 if atoms.has('tags'): 

256 tags = atoms.get_tags() 

257 else: 

258 tags = None 

259 if atoms.has('masses'): 

260 masses = atoms.get_masses() 

261 else: 

262 masses = None 

263 d = { 

264 'version': 3, 

265 'pbc': atoms.get_pbc(), 

266 'numbers': atoms.get_atomic_numbers(), 

267 'tags': tags, 

268 'masses': masses, 

269 'constraints': [], # backwards compatibility 

270 'constraints_string': pickle.dumps(atoms.constraints, protocol=0), 

271 } 

272 pickle.dump(d, self.fd, protocol=2) 

273 self.header_written = True 

274 self.offsets.append(self.fd.tell()) 

275 

276 # Atomic numbers and periodic boundary conditions are only 

277 # written once - in the header. Store them here so that we can 

278 # check that they are the same for all images: 

279 self.numbers = atoms.get_atomic_numbers() 

280 self.pbc = atoms.get_pbc() 

281 

282 def close(self): 

283 """Close the trajectory file.""" 

284 self.fd.close() 

285 

286 def __getitem__(self, i=-1): 

287 if isinstance(i, slice): 

288 return [self[j] for j in range(*i.indices(len(self)))] 

289 

290 N = len(self.offsets) 

291 if 0 <= i < N: 

292 self.fd.seek(self.offsets[i]) 

293 try: 

294 d = pickle.load(self.fd, encoding='bytes') 

295 d = { 

296 k.decode() if isinstance(k, bytes) else k: v 

297 for k, v in d.items() 

298 } 

299 except EOFError: 

300 raise IndexError 

301 if i == N - 1: 

302 self.offsets.append(self.fd.tell()) 

303 charges = d.get('charges') 

304 magmoms = d.get('magmoms') 

305 try: 

306 constraints = [c.copy() for c in self.constraints] 

307 except Exception: 

308 constraints = [] 

309 warnings.warn('Constraints did not unpickle correctly.') 

310 atoms = Atoms( 

311 positions=d['positions'], 

312 numbers=self.numbers, 

313 cell=d['cell'], 

314 momenta=d['momenta'], 

315 magmoms=magmoms, 

316 charges=charges, 

317 tags=self.tags, 

318 masses=self.masses, 

319 pbc=self.pbc, 

320 info=unstringnify_info(d.get('info', {})), 

321 constraint=constraints, 

322 ) 

323 if 'energy' in d: 

324 calc = SinglePointCalculator( 

325 atoms, 

326 energy=d.get('energy', None), 

327 forces=d.get('forces', None), 

328 stress=d.get('stress', None), 

329 magmoms=magmoms, 

330 ) 

331 atoms.calc = calc 

332 return atoms 

333 

334 if i >= N: 

335 for j in range(N - 1, i + 1): 

336 atoms = self[j] 

337 return atoms 

338 

339 i = len(self) + i 

340 if i < 0: 

341 raise IndexError('Trajectory index out of range.') 

342 return self[i] 

343 

344 def __len__(self): 

345 if len(self.offsets) == 0: 

346 return 0 

347 N = len(self.offsets) - 1 

348 while True: 

349 self.fd.seek(self.offsets[N]) 

350 try: 

351 pickle.load(self.fd) 

352 except EOFError: 

353 return N 

354 self.offsets.append(self.fd.tell()) 

355 N += 1 

356 

357 def pre_write_attach(self, function, interval=1, *args, **kwargs): 

358 """Attach a function to be called before writing begins. 

359 

360 function: The function or callable object to be called. 

361 

362 interval: How often the function is called. Default: every time (1). 

363 

364 All other arguments are stored, and passed to the function. 

365 """ 

366 if not isinstance(function, collections.abc.Callable): 

367 raise ValueError('Callback object must be callable.') 

368 self.pre_observers.append((function, interval, args, kwargs)) 

369 

370 def post_write_attach(self, function, interval=1, *args, **kwargs): 

371 """Attach a function to be called after writing ends. 

372 

373 function: The function or callable object to be called. 

374 

375 interval: How often the function is called. Default: every time (1). 

376 

377 All other arguments are stored, and passed to the function. 

378 """ 

379 if not isinstance(function, collections.abc.Callable): 

380 raise ValueError('Callback object must be callable.') 

381 self.post_observers.append((function, interval, args, kwargs)) 

382 

383 def _call_observers(self, obs): 

384 """Call pre/post write observers.""" 

385 for function, interval, args, kwargs in obs: 

386 if self.write_counter % interval == 0: 

387 function(*args, **kwargs) 

388 

389 def __enter__(self): 

390 return self 

391 

392 def __exit__(self, *args): 

393 self.close() 

394 

395 

396def stringnify_info(info): 

397 """Return a stringnified version of the dict *info* that is 

398 ensured to be picklable. Items with non-string keys or 

399 unpicklable values are dropped and a warning is issued.""" 

400 stringnified = {} 

401 for k, v in info.items(): 

402 if not isinstance(k, str): 

403 warnings.warn( 

404 'Non-string info-dict key is not stored in ' 

405 + 'trajectory: ' 

406 + repr(k), 

407 UserWarning, 

408 ) 

409 continue 

410 try: 

411 # Should highest protocol be used here for efficiency? 

412 # Protocol 2 seems not to raise an exception when one 

413 # tries to pickle a file object, so by using that, we 

414 # might end up with file objects in inconsistent states. 

415 s = pickle.dumps(v, protocol=0) 

416 except pickle.PicklingError: 

417 warnings.warn( 

418 'Skipping not picklable info-dict item: ' 

419 + f'"{k}" ({sys.exc_info()[1]})', 

420 UserWarning, 

421 ) 

422 else: 

423 stringnified[k] = s 

424 return stringnified 

425 

426 

427def unstringnify_info(stringnified): 

428 """Convert the dict *stringnified* to a dict with unstringnified 

429 objects and return it. Objects that cannot be unpickled will be 

430 skipped and a warning will be issued.""" 

431 info = {} 

432 for k, s in stringnified.items(): 

433 try: 

434 v = pickle.loads(s) 

435 except pickle.UnpicklingError: 

436 warnings.warn( 

437 'Skipping not unpicklable info-dict item: ' 

438 + f'"{k}" ({sys.exc_info()[1]})', 

439 UserWarning, 

440 ) 

441 else: 

442 info[k] = v 

443 return info 

444 

445 

446def dict2constraints(d): 

447 """Convert dict unpickled from trajectory file to list of constraints.""" 

448 

449 version = d.get('version', 1) 

450 

451 if version == 1: 

452 return d['constraints'] 

453 elif version in (2, 3): 

454 try: 

455 constraints = pickle.loads(d['constraints_string']) 

456 for c in constraints: 

457 if isinstance(c, FixAtoms) and c.index.dtype == bool: 

458 # Special handling of old pickles: 

459 c.index = np.arange(len(c.index))[c.index] 

460 return constraints 

461 except (AttributeError, KeyError, EOFError, ImportError, TypeError): 

462 warnings.warn('Could not unpickle constraints!') 

463 return [] 

464 else: 

465 return []