Fix Composition
for mixed species & element compositions
#4256
+13
−5
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Composition
objects initialised as e.g.Composition({"Cd2+": 1, "Cd": 1, "Te2-": 2})
do not behave as expected, giving e.g.Composition.formula = "Cd3 Te2"
instead ofCd2 Te2
. This is due toComposition.__getitem__()
matching all species and elements/non-species of a given input string; so thatComposition["Cd"]
here would return2
(as desired), but thanComposition.items()
(which is use forget_el_amt_dict
,formula
and more) gives("Cd2+", 1), ("Cd", 2), ("Te", 2)
which is incorrect.In the end, it's an easy fix to just define the
items()
method to avoid theComposition.__getitem__()
(which is only needed when the user doesComposition[...]
).Test added, which failed with previous code and passes now.
Context: Took a while to find what was going on here. Was originally flagged by this
ValueError
withComputedStructureEntry
: https://github.com/materialsproject/pymatgen/blob/master/src/pymatgen/entries/computed_entries.py#L588With original

pymatgen
code:With fixed code:

Flagged by tests in ShakeNBreak, because defect generation in
pymatgen-analysis-defects
mixes species with just element symbols; e.g. converting to just element symbol withget_element
here: https://github.com/materialsproject/pymatgen-analysis-defects/blob/main/pymatgen/analysis/defects/core.py#L566-L576