Skip to content

Commit 32d9beb

Browse files
authored
Bugfix: Preserve PBC info in AseAtomsAdaptor (#4121)
- get_atoms() and get_structure() methods now preserve PBC
1 parent 9933f45 commit 32d9beb

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/pymatgen/io/ase.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import numpy as np
1414
from monty.json import MontyDecoder, MSONable, jsanitize
1515

16-
from pymatgen.core.structure import Molecule, Structure
16+
from pymatgen.core.structure import Lattice, Molecule, Structure
1717

1818
try:
1919
from ase.atoms import Atoms
@@ -103,7 +103,7 @@ def get_atoms(structure: SiteCollection, msonable: bool = True, **kwargs) -> MSO
103103
symbols = [str(site.specie.symbol) for site in structure]
104104
positions = [site.coords for site in structure]
105105
if hasattr(structure, "lattice"):
106-
pbc = True
106+
pbc = getattr(structure.lattice, "pbc", True)
107107
cell = structure.lattice.matrix
108108
else: # Molecule without lattice
109109
pbc = False
@@ -284,7 +284,7 @@ def get_structure(atoms: Atoms, cls: type[Structure] = Structure, **cls_kwargs)
284284
structure = cls(symbols, positions, properties=properties, **cls_kwargs)
285285
else:
286286
structure = cls(
287-
lattice,
287+
Lattice(lattice, pbc=atoms.pbc),
288288
symbols,
289289
positions,
290290
coords_are_cartesian=True,

tests/io/test_ase.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,20 @@ def test_back_forth_v4():
317317
MontyDecoder().process_decoded(dct)
318318

319319

320+
@skip_if_no_ase
321+
def test_back_forth_v5():
322+
# Structure --> Atoms --> Structure --> Atoms
323+
structure = Structure.from_file(f"{VASP_IN_DIR}/POSCAR")
324+
# 2D structure; test if PBC is preserved in all conversions
325+
structure.lattice.pbc = (True, True, False)
326+
atoms = AseAtomsAdaptor.get_atoms(structure)
327+
structure_back = AseAtomsAdaptor.get_structure(atoms)
328+
atoms_back = AseAtomsAdaptor.get_atoms(structure_back)
329+
assert structure_back == structure
330+
for key, val in atoms.todict().items():
331+
assert str(atoms_back.todict()[key]) == str(val)
332+
333+
320334
@skip_if_no_ase
321335
def test_msonable_atoms():
322336
structure = Structure.from_file(f"{VASP_IN_DIR}/POSCAR")

0 commit comments

Comments
 (0)