Skip to content

Commit c56a25a

Browse files
authored
Fix nelectrons not updating when replacing species in Molecule (#3269)
* make property Molecule.nelectrons dynamic * add test to check nelectrons is updated when replacing species
1 parent 1cf05e0 commit c56a25a

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

pymatgen/core/structure.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2902,22 +2902,16 @@ def __init__(
29022902
raise StructureError("Molecule contains sites that are less than 0.01 Angstrom apart!")
29032903

29042904
self._charge = charge
2905-
nelectrons = 0.0
2906-
for site in sites:
2907-
for sp, amt in site.species.items():
2908-
if not isinstance(sp, DummySpecies):
2909-
nelectrons += sp.Z * amt
2910-
nelectrons -= charge
2911-
self._nelectrons = nelectrons
2905+
n_electrons = self.nelectrons
29122906
if spin_multiplicity:
2913-
if charge_spin_check and (nelectrons + spin_multiplicity) % 2 != 1:
2907+
if charge_spin_check and (n_electrons + spin_multiplicity) % 2 != 1:
29142908
raise ValueError(
29152909
f"Charge of {self._charge} and spin multiplicity of {spin_multiplicity} "
29162910
"is not possible for this molecule!"
29172911
)
29182912
self._spin_multiplicity = spin_multiplicity
29192913
else:
2920-
self._spin_multiplicity = 1 if nelectrons % 2 == 0 else 2
2914+
self._spin_multiplicity = 1 if n_electrons % 2 == 0 else 2
29212915

29222916
@property
29232917
def charge(self) -> float:
@@ -2932,7 +2926,13 @@ def spin_multiplicity(self) -> float:
29322926
@property
29332927
def nelectrons(self) -> float:
29342928
"""Number of electrons in the molecule."""
2935-
return self._nelectrons
2929+
n_electrons = 0.0
2930+
for site in self:
2931+
for sp, amt in site.species.items():
2932+
if not isinstance(sp, DummySpecies):
2933+
n_electrons += sp.Z * amt
2934+
n_electrons -= self.charge
2935+
return n_electrons
29362936

29372937
@property
29382938
def center_of_mass(self) -> np.ndarray:

tests/core/test_structure.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1779,6 +1779,10 @@ def test_prop(self):
17791779
mol = Molecule(["C", "H", "H", "H", "H"], self.coords, charge=1)
17801780
assert mol.spin_multiplicity == 2
17811781
assert mol.nelectrons == 9
1782+
# https://github.com/materialsproject/pymatgen/issues/3265
1783+
# replace species and ensure nelectrons is updated
1784+
mol[0] = "N"
1785+
assert mol.nelectrons == 10
17821786

17831787
# Triplet O2
17841788
mol = IMolecule(["O"] * 2, [[0, 0, 0], [0, 0, 1.2]], spin_multiplicity=3)

0 commit comments

Comments
 (0)