How to apply periodic boundary conditions in molecular dynamics

I’m tying to apply periodic boundary condition in molecular dynamics.
I set atoms.set_pbc((True, True, True)) , but atoms move out of the cell.

Could you please tell me how to solve it?

source code is here.

from ase.lattice.cubic import FaceCenteredCubic
from import MaxwellBoltzmannDistribution
from import VelocityVerlet
from ase import units
from import Trajectory
from import read, write

from ase.calculators.emt import EMT
size = 2

atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                          size=(size, size, size),
atoms.set_pbc((True, True, True))


MaxwellBoltzmannDistribution(atoms, 5000 * units.kB)

test1= aaa+ ".traj"

dyn = VelocityVerlet(atoms, 5 * units.fs, trajectory = test1)  # 5 fs time step.

for i in range(1000):

ff= Trajectory("x123.traj")
write("", ff)

As long as the ASE calculator is implemented correctly, the PBC should be applied just fine in the energy/force calculation.

Wrapping the positions in the saved trajectory is often undesirable as it makes it more difficult to correctly calculate velocities, correlation functions, diffusion etc. I would recommend that if you want to wrap the positions afterwards (e.g. for visualisation) you could do something like

for atoms in traj:

If it is really important to wrap the positions during the simulation (perhaps to work around a bug in the atomistic code?) then you can use an ASE feature to attach a callback function to the dynamics driver.

dyn = VelocityVerlet(atoms, 5 * units.fs, trajectory=test1)

def wrap_atoms(a=atoms):
dyn.attach(wrap_atoms, interval=1)

But this will come with some computational overhead!

Dear Ajjackson.

Thank you for the advice !
I was able to solve the problem.

I would like to ask an additional question.
How can I convert a trajectory to a xyz file?