Skip to content

Commit 267963e

Browse files
authored
Add fix for SFAC writer (#3779)
* Add fix for SFAC writer * Test for numbers
1 parent ad6eafe commit 267963e

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

pymatgen/io/res.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def __str__(self) -> str:
8787

8888
@dataclass(frozen=True)
8989
class ResSFAC:
90-
species: set[str]
90+
species: list[str]
9191
ions: list[Ion]
9292

9393
def __str__(self) -> str:
@@ -180,7 +180,7 @@ def _parse_ion(self, line: str) -> Ion:
180180

181181
def _parse_sfac(self, line: str, it: Iterator[str]) -> ResSFAC:
182182
"""Parses the SFAC block."""
183-
species = set(line.split())
183+
species = list(line.split())
184184
ions = []
185185
try:
186186
while True:
@@ -256,24 +256,24 @@ def _cell_from_lattice(cls, lattice: Lattice) -> ResCELL:
256256
return ResCELL(1.0, lattice.a, lattice.b, lattice.c, lattice.alpha, lattice.beta, lattice.gamma)
257257

258258
@classmethod
259-
def _ions_from_sites(cls, sites: list[PeriodicSite]) -> list[Ion]:
260-
"""Produce a list of entries for a SFAC block from a list of pymatgen PeriodicSite."""
259+
def _sfac_from_sites(cls, sites: list[PeriodicSite]) -> ResSFAC:
260+
"""Produce a SFAC block from a list of pymatgen PeriodicSite."""
261261
ions: list[Ion] = []
262-
i = 0
262+
species: list[str] = list()
263+
263264
for site in sites:
264265
for specie, occ in site.species.items():
265-
i += 1
266+
try:
267+
i = species.index(specie) + 1
268+
except ValueError:
269+
species.append(specie)
270+
i = len(species)
271+
266272
x, y, z = map(float, site.frac_coords)
267273
spin = site.properties.get("magmom")
268274
spin = spin and float(spin)
269275
ions.append(Ion(specie, i, (x, y, z), occ, spin))
270-
return ions
271276

272-
@classmethod
273-
def _sfac_from_sites(cls, sites: list[PeriodicSite]) -> ResSFAC:
274-
"""Produce a SFAC block from a list of pymatgen PeriodicSite."""
275-
ions = cls._ions_from_sites(sites)
276-
species = {ion.specie for ion in ions}
277277
return ResSFAC(species, ions)
278278

279279
@classmethod

tests/io/test_res.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,14 @@ def test_as_dict(self, provider: AirssProvider):
131131
assert dct["pressure"] == approx(15.0252)
132132
assert dct["volume"] == approx(57.051984)
133133

134+
def test_sfac_writer(self, provider: AirssProvider):
135+
"""https://github.com/materialsproject/pymatgen/issues/3677"""
136+
sfac = ResWriter._sfac_from_sites(provider.structure)
137+
specie_nums = [ion.specie_num for ion in sfac.ions]
138+
assert set(specie_nums) == {1, 2}
139+
assert len(sfac.species) == max(specie_nums)
140+
assert [str(sp) for sp in sfac.species] == ["C", "Co"]
141+
134142

135143
class TestSpin:
136144
def test_read_spin(self):

0 commit comments

Comments
 (0)