How to write multiple Atoms objects to a traj format file?

I have the following variables:

nframe: int # the number of frames
force: numpy.ndarray # shape: (nframe,231,3)
coord: numpy.ndarray # shape: (nframe,231,3)
box: numpy.ndarray # shape: (nframe,9)
energy: numpy.ndarray # shape: (nframe,)
chemical_symbol: str # "C60O57H114"

Now I want to use the above information to construct “atom” objects iteratively and then write them to a traj format file. Here is the code:

for idx in range(nframe):
    curr_atoms = Atoms(
        positions = coord[idx],
        cell = box[idx].reshape(3,3), 
        symbols = chemical_symbol,
        pbc= True
    )
    calculator = SinglePointCalculator(curr_atoms,energy=ener[idx],forces=force[idx])
    curr_atoms.calc = calculator
    write("test.traj",curr_atoms,format="traj",append=True)

Although I can get the “test.traj” file, I can’t read it correctly using the code below:

data =  read("test.traj",index=":",format="traj")
len(data) # equal 0

I don’t understand why that is, and I want to know how to write multiple Atoms objects to a traj format file. Looking forward to your help!

Hi,

I think the problem is that the append=True parameter to ase.io.write is not particularly format-aware: it will simply append fresh data to the file. This is not going to be valid for many formats, and the ASE .traj format is one format that does not allow the same output format to be written repeatedly. (Specifically, there is a header that should not be repeated…)

You can append atoms to a Trajectory file by using a Trajectory object, though!

from ase.io.trajectory import Trajectory
with Trajectory('test.traj', mode='a') as traj:
    traj.write(atoms)

should safely append a single Atoms to an (existing or new) .traj file.

Thank you, ajjackson! The code you provided is very helpful. Now I can write multiple atoms into one .traj file.

1 Like