Export "structure" class to .xyz file?

I would like to export a “structure” class object to an XYZ file.

Yes, I realize that .xyz files are normally used for molecules, not crystals. However, I need the actual atomic positions as inputs to a simulation program.

This is important because I might use this simulation program on structures that do not have high-symmetry, have defects, etc. So what would be ideal is if I could take an existing “high-symmetry” structure from Materials Project, and then export either just the unit cell, or a “slab” I’ve created where I alter just one atomic position, etc.

Here’s a simple way to do the conversion and retain lattice information as the comment line in the xyz file. For more context, take a look at this forum post.

from pymatgen.core import Molecule
from mp_api.client import MPRester
import json

mpid = "mp-1227591"
with MPRester() as mpr:
    structure = mpr.get_structure_by_material_id(mpid)

# perform operations on the structure here

lattice_comment = "# lattice = " + json.dumps(structure.lattice.matrix.tolist())

mol = Molecule(
    structure.species,
    structure.cart_coords,
    charge = structure.charge,
    site_properties=structure.site_properties,
)
xyz_str = mol.to(fmt="xyz")
xyz_lines = xyz_str.splitlines()
xyz_str = "\n".join([xyz_lines[0],lattice_comment,*xyz_lines[2:]])

with open(f"{mpid}.xyz","w") as f:
    f.write(xyz_str)
1 Like

I think this is exactly what I need… thanks!