Skip to content

Commit

Permalink
Add strict parameter to _parse_formula method and raise ValueError if…
Browse files Browse the repository at this point in the history
… formula str is only numbers and spaces (#3517)
  • Loading branch information
janosh authored Dec 15, 2023
1 parent 4a94f9c commit d5d750f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 6 additions & 1 deletion pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,10 +522,12 @@ def contains_element_type(self, category: str) -> bool:
return any(category[0] in el.block for el in self.elements)
return any(getattr(el, f"is_{category}") for el in self.elements)

def _parse_formula(self, formula: str) -> dict[str, float]:
def _parse_formula(self, formula: str, strict: bool = True) -> dict[str, float]:
"""
Args:
formula (str): A string formula, e.g. Fe2O3, Li3Fe2(PO4)3.
strict (bool): Whether to throw an error if formula string is invalid (e.g. empty).
Defaults to True.
Returns:
Composition with that formula.
Expand All @@ -534,6 +536,9 @@ def _parse_formula(self, formula: str) -> dict[str, float]:
In the case of Metallofullerene formula (e.g. Y3N@C80),
the @ mark will be dropped and passed to parser.
"""
# throw if formula contains special characters or only spaces and/or numbers
if strict and re.match(r"[\s\d.*/]*$", formula):
raise ValueError(f"Invalid {formula=}")
# for Metallofullerene like "Y3N@C80"
formula = formula.replace("@", "")

Expand Down
5 changes: 5 additions & 0 deletions tests/core/test_composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,11 @@ def test_formula(self):

assert Composition("Na 3 Zr (PO 4) 3").reduced_formula == "Na3Zr(PO4)3"

# test bad formulas raise ValueError
for bad_formula in ("", " ", " 2", "4 2", "6123", "1.2", "1/2", "1.2.3"):
with pytest.raises(ValueError, match=f"Invalid formula={bad_formula!r}"):
Composition(bad_formula)

def test_to_latex_html_unicode(self):
assert self.comps[0].to_latex_string() == "Li$_{3}$Fe$_{2}$P$_{3}$O$_{12}$"
assert self.comps[0].to_html_string() == "Li<sub>3</sub>Fe<sub>2</sub>P<sub>3</sub>O<sub>12</sub>"
Expand Down

0 comments on commit d5d750f

Please sign in to comment.