index | modules | gitlab | page source

# Trajectory files

The `ase.io.trajectory` module defines Trajectory objects, that is objects storing the temporal evolution of a simulation or the path taken during an optimization. A Trajectory file contains one or more `Atoms` objects, usually to be interpreted as a time series, although that is not a requirement.

The main Trajectory object writes in a file format, which is compatible across Python version.

The `ase.io.trajectory` additionally defines two specialized kinds of Trajectory files, the PickleTrajectory and the BundleTrajectory.

PickleTrajectory is the old (pre 2015) Trajectory format, its use is no longer recommended as compatibility between Python versions (and to a lesser degree between ASE vesions) cannot be guaranteed. You must convert your old PickleTrajectory files as soon as possible.

BundleTrajectory is only intended for large molecular dynamics simulations (large meaning millions of atoms).

Typically, trajectories are used to store different configurations of the same system (i.e. the same atoms). If you need to store configurations of different systems, the `ASE Database module` may be more appropriate.

## Trajectory

The Trajectory function returns a Trajectory reading or writing object, depending on the mode.

ase.io.Trajectory(filename, mode='r', atoms=None, properties=None, master=None)

  A Trajectory can be created in read, write or append mode.

  Parameters:

  filename: str

    The name of the file. Traditionally ends in .traj.

  mode: str

    The mode. ‘r’ is read mode, the file should already exist, and no atoms argument should be specified. ‘w’ is write mode. The atoms argument specifies the Atoms object to be written to the file, if not given it must instead be given as an argument to the write() method. ‘a’ is append mode. It acts as write mode, except that data is appended to a preexisting file.

  atoms: Atoms object

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

  properties: list of str

    If specified, these calculator properties are saved in the trajectory. If not specified, all supported quantities are saved. Possible values: energy, forces, stress, dipole, charges, magmom and magmoms.

  master: bool

    Controls which process does the actual writing. The default is that process number 0 does this. If this argument is given, processes where it is True will write.

  The atoms, properties and master arguments are ignores in read mode.

The function returns a TrajectoryReader or a TrajectoryWriter object.

Reading a trajectory file is done by indexing the TrajectoryReader object, i.e. traj[0] reads the first configuration, traj[-1] reads the last, traj[3:8] returns a list of the third through seventh, etc.

Writing a trajectory file is done by calling the `write` method. If no atoms object was given when creating the object, it must be given as an argument to the `write` method.

### Examples

Reading a configuration:

    from ase.io.trajectory import Trajectory
    traj = Trajectory('example.traj')
    atoms = traj[-1]

Reading all configurations:

    traj = Trajectory('example.traj')
    for atoms in traj:
        # Analyze atoms

Writing every 100th time step in a molecular dynamics simulation:

    # dyn is the dynamics (e.g. VelocityVerlet, Langevin or similar)
    traj = Trajectory('example.traj', 'w', atoms)
    dyn.attach(traj.write, interval=100)
    dyn.run(10000)
    traj.close()

### The TrajectoryReader and TrajectoryWriter objects

Usually, you only need the interface given above, but the reader and writer have a few additional methods, that can be useful.

class ase.io.trajectory.TrajectoryReader(filename)

  Reads Atoms objects from a .traj file.

  A Trajectory in read mode.

  The filename traditionally ends in .traj.

  close()

    Close the trajectory file.

Note that there is apparently no methods for reading the trajectory. Reading is instead done by indexing the trajectory, or by iterating over the trajectory: `traj[0]` and `traj[-1]` return the first and last `Atoms` object in the trajectory.

class ase.io.trajectory.TrajectoryWriter(filename, mode='w', atoms=None, properties=None, extra=[], master=None)

  Writes Atoms objects to a .traj file.

  A Trajectory writer, in write or append mode.

  Parameters:

  filename: str

    The name of the file. Traditionally ends in .traj.

  mode: str

    The mode. ‘r’ is read mode, the file should already exist, and no atoms argument should be specified. ‘w’ is write mode. The atoms argument specifies the Atoms object to be written to the file, if not given it must instead be given as an argument to the write() method. ‘a’ is append mode. It acts as write mode, except that data is appended to a preexisting file.

  atoms: Atoms object

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

  properties: list of str

    If specified, these calculator properties are saved in the trajectory. If not specified, all supported quantities are saved. Possible values: energy, forces, stress, dipole, charges, magmom and magmoms.

  master: bool

    Controls which process does the actual writing. The default is that process number 0 does this. If this argument is given, processes where it is True will write.

  close()

    Close the trajectory file.

  write(atoms=None, **kwargs)

    Write the atoms to the file.

    If the atoms argument is not given, the atoms object specified when creating the trajectory object is used.

    Use keyword arguments to add extra properties:

        writer.write(atoms, energy=117, dipole=[0, 0, 1.0])

## PickleTrajectory

The obsolete PickleTrajectory uses the same object for reading and writing.

WARNING 1: If your Atoms objects contains constraints, the constraint object is pickled and stored in the file. Unfortunately, this means that if the object definition in ASE changes, you cannot read the trajectory file. In the new Trajectory format the contraint is stored in an implementation-independent format.

WARNING 2: It is possible to write a malicious pickle file (and thus a malicious PickleTrajectory) that executes arbitrary code when reading the file. The new Trajectory format cannot contain code.

For the reasons above, version 3.10 of ASE will not be able to read and write PickleTrajectory files, and you need to convert existing files to the new format.

### Converting old PickleTrajectory files to new Trajectory files

Please convert your old PickleTrajectory files before it is too late:

    $ python -m ase.io.trajectory file1.traj [file2.traj ...]

this will convert one or more files. The original files are kept with extension `.traj.old`

You can identify old trajectory files like this:

    $ python -m ase.io.formats hmmm.traj
    hmmm.traj: Old ASE pickle trajectory (trj+)
    $ python -m ase.io.trajectory hmmm.traj  # convert
    $ python -m ase.io.formats hmmm.traj hmmm.traj.old
    hmmm.traj:     ASE trajectory (traj+)
    hmmm.traj.old: Old ASE pickle trajectory (trj+)

## BundleTrajectory

The BundleTrajectory has the interface

class ase.io.bundletrajectory.BundleTrajectory(filename, mode='r', atoms=None, backup=True, backend='ulm', singleprecision=False)

  Reads and writes atoms into a .bundle directory.

  The BundleTrajectory is an alternative way of storing trajectories, intended for large-scale molecular dynamics simulations, where a single flat file becomes unwieldy. Instead, the data is stored in directory, a ‘bundle’ (the name bundle is inspired from bundles in Mac OS, which are really just directories the user is supposed to think of as a single file-like unit).

  Parameters:

  filename:

    The name of the directory. Preferably ending in .bundle.

  mode (optional):

    The file opening mode. ‘r’ means open for reading, ‘w’ for writing and ‘a’ for appending. Default: ‘r’. If opening in write mode, and the filename already exists, the old file is renamed to .bak (any old .bak file is deleted), except if the existing file is empty.

  atoms (optional):

    The atoms that will be written. Can only be specified in write or append mode. If not specified, the atoms must be given as an argument to the .write() method instead.

  backup=True:

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

  backend=’ulm’:

    Request a backend. Currently only ‘ulm’ is supported. Only honored when writing.

  singleprecision=False:

    Store floating point data in single precision (ulm backend only).

  close()

    Closes the trajectory.

  classmethod delete_bundle(filename)

    Deletes a bundle.

  static is_bundle(filename, allowempty=False)

    Check if a filename exists and is a BundleTrajectory.

    If allowempty=True, an empty folder is regarded as an empty BundleTrajectory.

  static is_empty_bundle(filename)

    Check if a filename is an empty bundle.

    Assumes that it is a bundle.

  log(text)

    Write to the log file in the bundle.

    Logging is only possible in write/append mode.

    This function is mainly for internal use, but can also be called by the user.

  post_write_attach(function, interval=1, *args, **kwargs)

    Attach a function to be called after writing ends.

    function: The function or callable object to be called.

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

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

  pre_write_attach(function, interval=1, *args, **kwargs)

    Attach a function to be called before writing begins.

    function: The function or callable object to be called.

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

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

  read_extra_data(name, n=0)

    Read extra data stored alongside the atoms.

    Currently only used to read data stored by an NPT dynamics object. The data is not associated with individual atoms.

  select_data(data, value)

    Selects if a given data type should be written.

    Data can be written in every frame (specify True), in the first frame only (specify ‘only’) or not at all (specify False). Not all data types support the ‘only’ keyword, if not supported it is interpreted as True.

    The following data types are supported, the letter in parenthesis indicates the default:

    positions (T), numbers (O), tags (O), masses (O), momenta (T), forces (T), energy (T), energies (F), stress (F), magmoms (T)

    If a given property is not present during the first write, it will be not be saved at all.

  set_extra_data(name, source=None, once=False)

    Adds extra data to be written.

    Parameters: name: The name of the data.

    source (optional): If specified, a callable object returning the data to be written. If not specified it is instead assumed that the atoms contains the data as an array of the same name.

    once (optional): If specified and True, the data will only be written to the first frame.

  write(atoms=None)

    Write the atoms to the file.

    If the atoms argument is not given, the atoms object specified when creating the trajectory object is used.

## See also

- The function `ase.io.write()` can write a single `Atoms` object to a Trajectory file.

- The function `ase.io.read()` can read an `Atoms` object from a Trajectory file, per default it reads the last one.

- The database modue `ase.db`.