Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better Composition repr #3182

Merged
merged 4 commits into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 12 additions & 22 deletions pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,7 @@ def __iter__(self) -> Iterator[Species | Element | DummySpecies]:
def __contains__(self, key) -> bool:
try:
sp = get_el_sp(key)
# First check for species
if sp in self._data:
return True
# If not found, check for parent element (if it's a species)
if isinstance(sp, Species):
return sp.element in self._data
return False
return sp in self._data
except ValueError as exc:
raise TypeError(f"Invalid {key=} for Composition") from exc

Expand Down Expand Up @@ -405,14 +399,14 @@ def get_integer_formula_and_factor(
Li0.5O0.25 returns (Li2O, 0.25). O0.25 returns (O2, 0.125)
"""
el_amt = self.get_el_amt_dict()
g = gcd_float(list(el_amt.values()), 1 / max_denominator)
gcd = gcd_float(list(el_amt.values()), 1 / max_denominator)

d = {k: round(v / g) for k, v in el_amt.items()}
formula, factor = reduce_formula(d, iupac_ordering=iupac_ordering)
dct = {k: round(v / gcd) for k, v in el_amt.items()}
formula, factor = reduce_formula(dct, iupac_ordering=iupac_ordering)
if formula in Composition.special_formulas:
formula = Composition.special_formulas[formula]
factor /= 2
return formula, factor * g
return formula, factor * gcd

@property
def reduced_formula(self) -> str:
Expand All @@ -434,8 +428,8 @@ def hill_formula(self) -> str:
no carbon, all the elements, including hydrogen, are listed
alphabetically.
"""
c = self.element_composition
elements = sorted(el.symbol for el in c)
elem_comp = self.element_composition
elements = sorted(el.symbol for el in elem_comp)
hill_elements = []
if "C" in elements:
hill_elements.append("C")
Expand All @@ -445,7 +439,7 @@ def hill_formula(self) -> str:
elements.remove("H")
hill_elements += elements

formula = [f"{el}{formula_double_format(c[el]) if c[el] != 1 else ''}" for el in hill_elements]
formula = [f"{el}{formula_double_format(elem_comp[el]) if elem_comp[el] != 1 else ''}" for el in hill_elements]
return " ".join(formula)

@property
Expand Down Expand Up @@ -621,8 +615,10 @@ def valid(self) -> bool:
"""
return not any(isinstance(el, DummySpecies) for el in self.elements)

def __repr__(self) -> str:
return "Comp: " + self.formula
def __repr__(self):
formula = " ".join(f"{k}{':' if hasattr(k, 'oxi_state') else ''}{v:g}" for k, v in self.items())
cls_name = type(self).__name__
return f"{cls_name}({formula!r})"

@classmethod
def from_dict(cls, d) -> Composition:
Expand Down Expand Up @@ -1299,9 +1295,3 @@ def __repr__(self):

class CompositionError(Exception):
"""Exception class for composition errors."""


if __name__ == "__main__":
import doctest

doctest.testmod()
12 changes: 12 additions & 0 deletions pymatgen/core/tests/test_composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,18 @@ def test_init(self):
c = Composition({"S": Composition.amount_tolerance / 2})
assert len(c.elements) == 0

def test_str_and_repr(self):
test_cases = [
({"Li+": 2, "Mn3+": 2, "O2-": 4}, {"str": "Li+2 Mn3+2 O2-4", "repr": "Composition('Li+:2 Mn3+:2 O2-:4')"}),
("H2O", {"str": "H2 O1", "repr": "Composition('H2 O1')"}),
({"Fe3+": 2, "O2-": 3}, {"str": "Fe3+2 O2-3", "repr": "Composition('Fe3+:2 O2-:3')"}),
("C6H6", {"str": "C6 H6", "repr": "Composition('C6 H6')"}),
]

for comp, expected in test_cases:
assert str(Composition(comp)) == expected["str"]
assert repr(Composition(comp)) == expected["repr"]

def test_average_electroneg(self):
electro_negs = (2.7224999999999997, 2.4160000000000004, 2.5485714285714285, 2.21, 2.718, 3.08, 1.21, 2.43)
for elem, val in zip(self.comps, electro_negs):
Expand Down
10 changes: 2 additions & 8 deletions pymatgen/core/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -789,9 +789,9 @@ def get_mass():

"""

def wrap(f):
def wrap(func):
def wrapped_f(*args, **kwargs):
val = f(*args, **kwargs)
val = func(*args, **kwargs)
unit_type = _UNAME2UTYPE[unit]

if isinstance(val, (FloatWithUnit, ArrayWithUnit)):
Expand All @@ -816,9 +816,3 @@ def wrapped_f(*args, **kwargs):
return wrapped_f

return wrap


if __name__ == "__main__":
import doctest

doctest.testmod()