Coverage for ase/io/trajectory.py: 89.78%
274 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Trajectory"""
3import contextlib
4import io
5import warnings
7import numpy as np
9from ase import __version__
10from ase.atoms import Atoms
11from ase.calculators.calculator import PropertyNotImplementedError
12from ase.calculators.singlepoint import SinglePointCalculator, all_properties
13from ase.io.formats import is_compressed
14from ase.io.jsonio import decode, encode
15from ase.io.pickletrajectory import PickleTrajectory
16from ase.parallel import world
17from ase.utils import tokenize_version
19__all__ = ['Trajectory', 'PickleTrajectory']
22def Trajectory(
23 filename, mode='r', atoms=None, properties=None, master=None, comm=world
24):
25 """A Trajectory can be created in read, write or append mode.
27 Parameters
28 ----------
30 filename: str | Path
31 The name/path of the file. Traditionally ends in .traj.
32 mode: str
33 The mode. 'r' is read mode, the file should already exist, and
34 no atoms argument should be specified.
35 'w' is write mode. The atoms argument specifies the Atoms
36 object to be written to the file, if not given it must instead
37 be given as an argument to the write() method.
38 'a' is append mode. It acts as write mode, except that
39 data is appended to a preexisting file.
40 atoms: Atoms object
41 The Atoms object to be written in write or append mode.
42 properties: list of str
43 If specified, these calculator properties are saved in the
44 trajectory. If not specified, all supported quantities are
45 saved. Possible values: energy, forces, stress, dipole,
46 charges, magmom and magmoms.
47 master: bool
48 Controls which process does the actual writing. The
49 default is that process number 0 does this. If this
50 argument is given, processes where it is True will write.
51 comm: Communicator object
52 Communicator to handle parallel file reading and writing.
54 The atoms, properties and master arguments are ignored in read mode.
56 Examples
57 --------
59 >>> from ase import Atoms
60 >>> atoms = Atoms('H2', positions=[(0, 0, 0), (0, 0, 0.74)])
62 Writing a configuration:
64 >>> from ase.io.trajectory import Trajectory
65 >>> with Trajectory('example.traj', 'w') as traj:
66 ... traj.write(atoms)
68 Reading all configurations:
70 >>> with Trajectory('example.traj') as traj:
71 ... for atoms in traj:
72 ... pass
74 Writing every 10th time step in a molecular dynamics simulation:
76 >>> from ase.md.verlet import VelocityVerlet
77 >>> from ase.calculators.emt import EMT
78 >>> atoms.calc = EMT()
79 >>> dyn = VelocityVerlet(atoms, timestep=1.0)
80 >>> with Trajectory('md.traj', 'w', atoms) as traj:
81 ... dyn.attach(traj.write, interval=10)
82 ... converged = dyn.run(20)
83 >>> converged
84 True
86 """
87 if mode == 'r':
88 return TrajectoryReader(filename)
89 return TrajectoryWriter(
90 filename, mode, atoms, properties, master=master, comm=comm
91 )
94class TrajectoryWriter:
95 """Writes Atoms objects to a .traj file."""
97 def __init__(
98 self,
99 filename,
100 mode='w',
101 atoms=None,
102 properties=None,
103 master=None,
104 comm=world,
105 ):
106 """A Trajectory writer, in write or append mode.
108 Parameters
109 ----------
111 filename: str | Path
112 The name of the file. Traditionally ends in .traj.
113 mode: str
114 The mode. 'r' is read mode, the file should already exist, and
115 no atoms argument should be specified.
116 'w' is write mode. The atoms argument specifies the Atoms
117 object to be written to the file, if not given it must instead
118 be given as an argument to the write() method.
119 'a' is append mode. It acts as write mode, except that
120 data is appended to a preexisting file.
121 atoms: Atoms object
122 The Atoms object to be written in write or append mode.
123 properties: list of str
124 If specified, these calculator properties are saved in the
125 trajectory. If not specified, all supported quantities are
126 saved. Possible values: energy, forces, stress, dipole,
127 charges, magmom and magmoms.
128 master: bool
129 Controls which process does the actual writing. The
130 default is that process number 0 does this. If this
131 argument is given, processes where it is True will write.
132 comm: MPI communicator
133 MPI communicator for this trajectory writer, by default world.
134 Passing a different communicator facilitates writing of
135 different trajectories on different MPI ranks.
136 """
137 if master is None:
138 master = comm.rank == 0
140 self.filename = filename
141 self.mode = mode
142 self.atoms = atoms
143 self.properties = properties
144 self.master = master
145 self.comm = comm
147 self.description = {}
148 self.header_data = None
149 self.multiple_headers = False
151 self._open(filename, mode)
153 def __enter__(self):
154 return self
156 def __exit__(self, exc_type, exc_value, tb):
157 self.close()
159 def set_description(self, description):
160 self.description.update(description)
162 def _open(self, filename, mode):
163 import ase.io.ulm as ulm
165 if mode not in 'aw':
166 raise ValueError('mode must be "w" or "a".')
167 if self.master:
168 self.backend = ulm.open(filename, mode, tag='ASE-Trajectory')
169 if len(self.backend) > 0 and mode == 'a':
170 with Trajectory(filename) as traj:
171 atoms = traj[0]
172 self.header_data = get_header_data(atoms)
173 else:
174 self.backend = ulm.DummyWriter()
176 def write(self, atoms=None, **kwargs):
177 """Write the atoms to the file.
179 If the atoms argument is not given, the atoms object specified
180 when creating the trajectory object is used.
182 Use keyword arguments to add extra properties:
184 writer.write(atoms, energy=117, dipole=[0, 0, 1.0])
185 """
186 if atoms is None:
187 atoms = self.atoms
189 for image in atoms.iterimages():
190 self._write_atoms(image, **kwargs)
192 def _write_atoms(self, atoms, **kwargs):
193 b = self.backend
195 if self.header_data is None:
196 b.write(version=1, ase_version=__version__)
197 if self.description:
198 b.write(description=self.description)
199 # Atomic numbers and periodic boundary conditions are written
200 # in the header in the beginning.
201 #
202 # If an image later on has other numbers/pbc, we write a new
203 # header. All subsequent images will then have their own header
204 # whether or not their numbers/pbc change.
205 self.header_data = get_header_data(atoms)
206 write_header = True
207 else:
208 if not self.multiple_headers:
209 header_data = get_header_data(atoms)
210 self.multiple_headers = not headers_equal(
211 self.header_data, header_data
212 )
213 write_header = self.multiple_headers
215 write_atoms(b, atoms, write_header=write_header)
217 calc = atoms.calc
219 if calc is None and len(kwargs) > 0:
220 calc = SinglePointCalculator(atoms)
222 if calc is not None:
223 if not hasattr(calc, 'get_property'):
224 calc = OldCalculatorWrapper(calc)
225 c = b.child('calculator')
226 c.write(name=calc.name)
227 if hasattr(calc, 'todict'):
228 c.write(parameters=calc.todict())
229 for prop in all_properties:
230 if prop in kwargs:
231 x = kwargs[prop]
232 else:
233 if self.properties is not None:
234 if prop in self.properties:
235 x = calc.get_property(prop, atoms)
236 else:
237 x = None
238 else:
239 try:
240 x = calc.get_property(
241 prop, atoms, allow_calculation=False
242 )
243 except (PropertyNotImplementedError, KeyError):
244 # KeyError is needed for Jacapo.
245 # XXX We can perhaps remove this.
246 x = None
247 if x is not None:
248 if prop in ['stress', 'dipole']:
249 x = x.tolist()
250 c.write(prop, x)
252 info = {}
253 for key, value in atoms.info.items():
254 try:
255 encode(value)
256 except TypeError:
257 warnings.warn(f'Skipping "{key}" info.')
258 else:
259 info[key] = value
260 if info:
261 b.write(info=info)
263 b.sync()
265 def close(self):
266 """Close the trajectory file."""
267 self.backend.close()
269 def __len__(self):
270 return self.comm.sum_scalar(len(self.backend))
273class TrajectoryReader:
274 """Reads Atoms objects from a .traj file."""
276 def __init__(self, filename):
277 """A Trajectory in read mode.
279 The filename traditionally ends in .traj.
280 """
281 self.filename = filename
282 self.numbers = None
283 self.pbc = None
284 self.masses = None
286 self._open(filename)
288 def __enter__(self):
289 return self
291 def __exit__(self, exc_type, exc_value, tb):
292 self.close()
294 def _open(self, filename):
295 import ase.io.ulm as ulm
297 self.backend = ulm.open(filename, 'r')
298 self._read_header()
300 def _read_header(self):
301 b = self.backend
302 if b.get_tag() != 'ASE-Trajectory':
303 raise OSError('This is not a trajectory file!')
305 if len(b) > 0:
306 self.pbc = b.pbc
307 self.numbers = b.numbers
308 self.masses = b.get('masses')
309 self.constraints = b.get('constraints', '[]')
310 self.description = b.get('description')
311 self.version = b.version
312 self.ase_version = b.get('ase_version')
314 def close(self):
315 """Close the trajectory file."""
316 self.backend.close()
318 def __getitem__(self, i=-1):
319 if isinstance(i, slice):
320 return SlicedTrajectory(self, i)
321 b = self.backend[i]
322 if 'numbers' in b:
323 # numbers and other header info was written alongside the image:
324 atoms = read_atoms(b, traj=self)
325 else:
326 # header info was not written because they are the same:
327 atoms = read_atoms(
328 b,
329 header=[self.pbc, self.numbers, self.masses, self.constraints],
330 traj=self,
331 )
332 if 'calculator' in b:
333 results = {}
334 implemented_properties = []
335 c = b.calculator
336 for prop in all_properties:
337 if prop in c:
338 results[prop] = c.get(prop)
339 implemented_properties.append(prop)
340 calc = SinglePointCalculator(atoms, **results)
341 calc.name = b.calculator.name
342 calc.implemented_properties = implemented_properties
344 if 'parameters' in c:
345 calc.parameters.update(c.parameters)
346 atoms.calc = calc
348 return atoms
350 def __len__(self):
351 return len(self.backend)
353 def __iter__(self):
354 for i in range(len(self)):
355 yield self[i]
358class SlicedTrajectory:
359 """Wrapper to return a slice from a trajectory without loading
360 from disk. Initialize with a trajectory (in read mode) and the
361 desired slice object."""
363 def __init__(self, trajectory, sliced):
364 self.trajectory = trajectory
365 self.map = range(len(self.trajectory))[sliced]
367 def __getitem__(self, i):
368 if isinstance(i, slice):
369 # Map directly to the original traj, not recursively.
370 traj = SlicedTrajectory(self.trajectory, slice(0, None))
371 traj.map = self.map[i]
372 return traj
373 return self.trajectory[self.map[i]]
375 def __len__(self):
376 return len(self.map)
379def get_header_data(atoms):
380 return {
381 'pbc': atoms.pbc.copy(),
382 'numbers': atoms.get_atomic_numbers(),
383 'masses': atoms.get_masses() if atoms.has('masses') else None,
384 'constraints': list(atoms.constraints),
385 }
388def headers_equal(headers1, headers2):
389 assert len(headers1) == len(headers2)
390 eq = True
391 for key in headers1:
392 eq &= np.array_equal(headers1[key], headers2[key])
393 return eq
396class VersionTooOldError(Exception):
397 pass
400def read_atoms(
401 backend,
402 header: tuple | None = None,
403 traj: TrajectoryReader | None = None,
404 _try_except: bool = True,
405) -> Atoms:
406 from ase.constraints import dict2constraint
408 if _try_except:
409 try:
410 return read_atoms(backend, header, traj, False)
411 except Exception as ex:
412 if traj is not None and tokenize_version(
413 __version__
414 ) < tokenize_version(traj.ase_version):
415 msg = (
416 'You are trying to read a trajectory file written '
417 f'by ASE-{traj.ase_version} from ASE-{__version__}. '
418 'It might help to update your ASE'
419 )
420 raise VersionTooOldError(msg) from ex
421 else:
422 raise
424 b = backend
425 if header:
426 pbc, numbers, masses, constraints = header
427 else:
428 pbc = b.pbc
429 numbers = b.numbers
430 masses = b.get('masses')
431 constraints = b.get('constraints', '[]')
433 atoms = Atoms(
434 positions=b.positions,
435 numbers=numbers,
436 cell=b.cell,
437 masses=masses,
438 pbc=pbc,
439 info=b.get('info'),
440 constraint=[dict2constraint(d) for d in decode(constraints)],
441 momenta=b.get('momenta'),
442 magmoms=b.get('magmoms'),
443 charges=b.get('charges'),
444 tags=b.get('tags'),
445 )
446 return atoms
449def write_atoms(backend, atoms, write_header=True):
450 b = backend
452 if write_header:
453 b.write(pbc=atoms.pbc.tolist(), numbers=atoms.numbers)
454 if atoms.constraints:
455 if all(hasattr(c, 'todict') for c in atoms.constraints):
456 b.write(constraints=encode(atoms.constraints))
458 if atoms.has('masses'):
459 b.write(masses=atoms.get_masses())
461 b.write(positions=atoms.get_positions(), cell=atoms.get_cell().tolist())
463 if atoms.has('tags'):
464 b.write(tags=atoms.get_tags())
465 if atoms.has('momenta'):
466 b.write(momenta=atoms.get_momenta())
467 if atoms.has('initial_magmoms'):
468 b.write(magmoms=atoms.get_initial_magnetic_moments())
469 if atoms.has('initial_charges'):
470 b.write(charges=atoms.get_initial_charges())
473def read_traj(fd, index):
474 trj = TrajectoryReader(fd)
475 for i in range(*index.indices(len(trj))):
476 yield trj[i]
479@contextlib.contextmanager
480def defer_compression(fd):
481 """Defer the file compression until all the configurations are read."""
482 # We do this because the trajectory and compressed-file
483 # internals do not play well together.
484 # Be advised not to defer compression of very long trajectories
485 # as they use a lot of memory.
486 if is_compressed(fd):
487 with io.BytesIO() as bytes_io:
488 try:
489 # write the uncompressed data to the buffer
490 yield bytes_io
491 finally:
492 # write the buffered data to the compressed file
493 bytes_io.seek(0)
494 fd.write(bytes_io.read())
495 else:
496 yield fd
499def write_traj(fd, images):
500 """Write image(s) to trajectory."""
501 if isinstance(images, Atoms):
502 images = [images]
503 with defer_compression(fd) as fd_uncompressed:
504 trj = TrajectoryWriter(fd_uncompressed)
505 for atoms in images:
506 trj.write(atoms)
509class OldCalculatorWrapper:
510 def __init__(self, calc):
511 self.calc = calc
512 try:
513 self.name = calc.name
514 except AttributeError:
515 self.name = calc.__class__.__name__.lower()
517 def get_property(self, prop, atoms, allow_calculation=True):
518 try:
519 if not allow_calculation and self.calc.calculation_required(
520 atoms, [prop]
521 ):
522 return None
523 except AttributeError:
524 pass
526 method = 'get_' + {
527 'energy': 'potential_energy',
528 'magmom': 'magnetic_moment',
529 'magmoms': 'magnetic_moments',
530 'dipole': 'dipole_moment',
531 }.get(prop, prop)
532 try:
533 result = getattr(self.calc, method)(atoms)
534 except AttributeError:
535 raise PropertyNotImplementedError
536 return result
539def convert(name):
540 import os
542 t = TrajectoryWriter(name + '.new')
543 for atoms in PickleTrajectory(name, _warn=False):
544 t.write(atoms)
545 t.close()
546 os.rename(name, name + '.old')
547 os.rename(name + '.new', name)
550def main():
551 import optparse
553 parser = optparse.OptionParser(
554 usage='python -m ase.io.trajectory a1.traj [a2.traj ...]',
555 description='Convert old trajectory '
556 'file(s) to new format. '
557 'The old file is kept as a1.traj.old.',
558 )
559 _opts, args = parser.parse_args()
560 for name in args:
561 convert(name)
564if __name__ == '__main__':
565 main()