Skip to content

Commit

Permalink
Add a from_ase_atoms() method to Structure (#3812)
Browse files Browse the repository at this point in the history
* Add a `from_ase_atoms()` to `Structure`

* pre-commit auto-fixes

* tweak doc str, add more tests, fix possibly unbound vars in test_structure.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Janosh Riebesell <[email protected]>
  • Loading branch information
3 people authored May 7, 2024
1 parent 46b018d commit d9e9ef6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
13 changes: 13 additions & 0 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,19 @@ def to_ase_atoms(self, **kwargs) -> Atoms:

return AseAtomsAdaptor.get_atoms(self, **kwargs)

def from_ase_atoms(self, **kwargs) -> Structure:
"""Convert ase.Atoms to pymatgen Structure.
Args:
kwargs: Passed to AseAtomsAdaptor.get_structure.
Returns:
Structure
"""
from pymatgen.io.ase import AseAtomsAdaptor

return AseAtomsAdaptor.get_structure(self, **kwargs)


class IStructure(SiteCollection, MSONable):
"""Basic immutable Structure object with periodicity. Essentially a sequence
Expand Down
9 changes: 8 additions & 1 deletion tests/core/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from ase.calculators.calculator import Calculator
from ase.calculators.emt import EMT
except ImportError:
ase = None
ase = Atoms = Calculator = EMT = None


enum_cmd = which("enum.x") or which("multienum.x")
Expand Down Expand Up @@ -1848,6 +1848,13 @@ def test_to_ase_atoms(self):
assert isinstance(atoms, Atoms)
assert len(atoms) == len(self.struct)
assert AseAtomsAdaptor.get_structure(atoms) == self.struct
assert Structure.from_ase_atoms(atoms) == self.struct

labeled_atoms = self.labeled_structure.to_ase_atoms()
assert Structure.from_ase_atoms(labeled_atoms) == self.labeled_structure

with pytest.raises(ValueError, match="ASE Atoms only supports ordered structures"):
self.disordered.to_ase_atoms()

def test_struct_with_isotope(self):
struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_LiFePO4")
Expand Down

0 comments on commit d9e9ef6

Please sign in to comment.