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

Reset label for sites changed by Structure.replace_species() #3672

Merged
merged 5 commits into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion pymatgen/core/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def label(self) -> str:
return self._label if self._label is not None else self.species_string

@label.setter
def label(self, label: str) -> None:
def label(self, label: str | None) -> None:
self._label = label

@property
Expand Down
5 changes: 4 additions & 1 deletion pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,11 +528,13 @@ def replace_species(
) -> SiteCollection:
"""Swap species.

Note that this clears the label of any affected site.

Args:
species_mapping (dict): Species to swap. Species can be elements too. E.g.,
{Element("Li"): Element("Na")} performs a Li for Na substitution. The second species can
be a sp_and_occu dict. For example, a site with 0.5 Si that is passed the mapping
{Element('Si): {Element('Ge'): 0.75, Element('C'): 0.25} } will have .375 Ge and .125 C.
{Element('Si'): {Element('Ge'): 0.75, Element('C'): 0.25} } will have .375 Ge and .125 C.
in_place (bool): Whether to perform the substitution in place or modify a copy.
Defaults to True.

Expand All @@ -559,6 +561,7 @@ def replace_species(
except Exception:
comp += {new_sp: amt}
site.species = comp
site.label = None # type: ignore

return site_coll

Expand Down
6 changes: 6 additions & 0 deletions tests/core/test_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,12 @@ def test_replace_species(self):
assert struct.formula == "K1.5 P0.5"
assert new_struct.formula == "Li1.5 P0.5"

def test_replace_species_labels(self):
"""https://github.com/materialsproject/pymatgen/issues/3658"""
struct = self.labeled_structure
struct.replace_species({"Si": "Ge"})
assert struct.labels == ["Ge", "Ge"]
stefsmeets marked this conversation as resolved.
Show resolved Hide resolved

def test_append_insert_remove_replace_substitute(self):
struct = self.struct
struct.insert(1, "O", [0.5, 0.5, 0.5])
Expand Down