Skip to content

Commit fd0acd4

Browse files
authored
Fix hill_formula Composition property (#3086)
* Added a test showing unexpected Hill formula behavior in a case with both C and H present, but not one after another (mp-1228185). * Adjusted the hill_formula property to fit the specification / docstring.
1 parent 44c7b0a commit fd0acd4

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

pymatgen/core/composition.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -440,10 +440,16 @@ def hill_formula(self) -> str:
440440
"""
441441
c = self.element_composition
442442
elements = sorted(el.symbol for el in c)
443+
hill_elements = []
443444
if "C" in elements:
444-
elements = ["C"] + [el for el in elements if el != "C"]
445-
446-
formula = [f"{el}{formula_double_format(c[el]) if c[el] != 1 else ''}" for el in elements]
445+
hill_elements.append("C")
446+
elements.remove("C")
447+
if "H" in elements:
448+
hill_elements.append("H")
449+
elements.remove("H")
450+
hill_elements += elements
451+
452+
formula = [f"{el}{formula_double_format(c[el]) if c[el] != 1 else ''}" for el in hill_elements]
447453
return " ".join(formula)
448454

449455
@property

pymatgen/core/tests/test_composition.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,12 @@ def test_hill_formula(self):
6767
assert c.hill_formula == "C Ca O3"
6868
c = Composition("C2H5OH")
6969
assert c.hill_formula == "C2 H6 O"
70+
# A test case with both C and H, but not one after another (mp-1228185)
71+
c = Composition("Ga8 As16 H102 C32 S36 O3")
72+
assert c.hill_formula == "C32 H102 As16 Ga8 O3 S36"
73+
# A test case with H but no C
74+
c = Composition("Ga8 As16 H102 S36 O3")
75+
assert c.hill_formula == "As16 Ga8 H102 O3 S36"
7076

7177
def test_init_(self):
7278
with pytest.raises(ValueError):

0 commit comments

Comments
 (0)