Skip to content

Commit 1b44fea

Browse files
committed
Some cleanup.
1 parent 4a237b4 commit 1b44fea

File tree

5 files changed

+21
-20
lines changed

5 files changed

+21
-20
lines changed

src/pymatgen/core/composition.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -712,8 +712,8 @@ def from_weight_dict(cls, weight_dict: dict[SpeciesLike, float], strict: bool =
712712
>>> Composition.from_weights({"Ti": 60, "Ni": 40})
713713
Composition('Ti0.647796 Ni0.352204')
714714
"""
715-
weight_sum = sum(val / Element(el).atomic_mass for el, val in weight_dict.items())
716-
comp_dict = {el: val / Element(el).atomic_mass / weight_sum for el, val in weight_dict.items()}
715+
weight_sum = sum(val / Element(str(el)).atomic_mass for el, val in weight_dict.items())
716+
comp_dict = {el: val / Element(str(el)).atomic_mass / weight_sum for el, val in weight_dict.items()}
717717

718718
return cls(comp_dict, strict=strict, **kwargs)
719719

@@ -1004,7 +1004,7 @@ def add_charges_from_oxi_state_guesses(
10041004

10051005
# Special case: No charged compound is possible
10061006
if not oxidation_states:
1007-
return type(self)({Species(e, 0): f for e, f in self.items()})
1007+
return type(self)({Species(str(e), 0): f for e, f in self.items()})
10081008

10091009
# Generate the species
10101010
species = []

src/pymatgen/core/operations.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,9 @@ def are_symmetrically_related_vectors(
225225
from_c = self.operate(from_a)
226226
to_c = self.operate(to_a)
227227

228-
floored = np.floor([from_c, to_c])
229-
is_too_close = np.abs([from_c, to_c] - floored) > 1 - tol
228+
vec = np.array([from_c, to_c])
229+
floored = np.floor(vec)
230+
is_too_close = np.abs(vec - floored) > 1 - tol
230231
floored[is_too_close] += 1
231232

232233
r_c = self.apply_rotation_only(r_a) - floored[0] + floored[1]

src/pymatgen/core/periodic_table.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@
7070
class ElementBase(Enum):
7171
"""Element class defined without any enum values so it can be subclassed."""
7272

73-
def __init__(self, symbol: SpeciesLike) -> None:
73+
def __init__(self, symbol: str) -> None:
7474
"""
7575
This class provides a basic, immutable representation of an element, including
7676
all relevant chemical and physical properties. It ensures that elements are
@@ -139,7 +139,7 @@ def __init__(self, symbol: SpeciesLike) -> None:
139139
- Mendeleev number: D. G. Pettifor, "A chemical scale for crystal-structure maps,"
140140
Solid State Communications, 1984.
141141
"""
142-
self.symbol = str(symbol)
142+
self.symbol = symbol
143143
data = _PT_DATA[symbol]
144144

145145
# Store key variables for quick access
@@ -568,8 +568,8 @@ def term_symbols(self) -> list[list[str]]:
568568
for ML in range(-L, L - 1, -1):
569569
for MS in np.arange(S, -S + 1, 1):
570570
if (ML, MS) in comb_counter:
571-
comb_counter[ML, MS] -= 1
572-
if comb_counter[ML, MS] == 0:
571+
comb_counter[ML, MS] -= 1 # type:ignore[index]
572+
if comb_counter[ML, MS] == 0: # type:ignore[index]
573573
del comb_counter[ML, MS]
574574
return term_symbols
575575

@@ -849,7 +849,7 @@ def iupac_ordering(self) -> int:
849849
"""
850850
return self._data["IUPAC ordering"]
851851

852-
def as_dict(self) -> dict[Literal["element", "@module", "@class"], str]:
852+
def as_dict(self) -> dict[str, Any]:
853853
"""Serialize to MSONable dict representation e.g. to write to disk as JSON."""
854854
return {
855855
"@module": type(self).__module__,
@@ -1041,7 +1041,7 @@ class Species(MSONable, Stringify):
10411041

10421042
def __init__(
10431043
self,
1044-
symbol: SpeciesLike,
1044+
symbol: str,
10451045
oxidation_state: float | None = None,
10461046
spin: float | None = None,
10471047
) -> None:
@@ -1056,11 +1056,11 @@ def __init__(
10561056
ValueError: If oxidation state passed both in symbol string and via
10571057
oxidation_state kwarg.
10581058
"""
1059-
if oxidation_state is not None and isinstance(symbol, str) and symbol.endswith(("+", "-")):
1059+
if oxidation_state is not None and symbol.endswith(("+", "-")):
10601060
raise ValueError(
10611061
f"Oxidation state should be specified either in {symbol=} or as {oxidation_state=}, not both."
10621062
)
1063-
if isinstance(symbol, str) and symbol.endswith(("+", "-")):
1063+
if symbol.endswith(("+", "-")):
10641064
# Extract oxidation state from symbol
10651065
try:
10661066
symbol, oxi = re.match(r"([A-Za-z]+)([0-9\.0-9]*[\+\-])", symbol).groups() # type: ignore[union-attr]
@@ -1130,7 +1130,7 @@ def __str__(self) -> str:
11301130
if self.oxi_state is not None:
11311131
abs_charge = formula_double_format(abs(self.oxi_state))
11321132
if isinstance(abs_charge, float):
1133-
abs_charge = f"{abs_charge:.2f}"
1133+
abs_charge = f"{abs_charge:.2f}" # type: ignore[assignment]
11341134
output += f"{abs_charge}{'+' if self.oxi_state >= 0 else '-'}"
11351135

11361136
if self._spin is not None:
@@ -1319,7 +1319,7 @@ def to_pretty_string(self) -> str:
13191319
if self.oxi_state is not None:
13201320
abs_charge = formula_double_format(abs(self.oxi_state))
13211321
if isinstance(abs_charge, float):
1322-
abs_charge = f"{abs_charge:.2f}"
1322+
abs_charge = f"{abs_charge:.2f}" # type: ignore[assignment]
13231323
output += f"{abs_charge}{'+' if self.oxi_state >= 0 else '-'}"
13241324
return output
13251325

src/pymatgen/core/structure.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ def elements(self) -> list[Element | Species | DummySpecies]:
430430
@property
431431
def composition(self) -> Composition:
432432
"""The structure's corresponding Composition object."""
433-
elem_map: dict[Species, float] = defaultdict(float)
433+
elem_map: dict[SpeciesLike, float] = defaultdict(float)
434434
for site in self:
435435
for species, occu in site.species.items():
436436
elem_map[species] += occu
@@ -453,7 +453,7 @@ def charge(self) -> float:
453453
"""The net charge of the structure based on oxidation states. If
454454
Elements are found, a charge of 0 is assumed.
455455
"""
456-
charge = 0
456+
charge = 0.0
457457
for site in self:
458458
for specie, amt in site.species.items():
459459
charge += (getattr(specie, "oxi_state", 0) or 0) * amt
@@ -3442,7 +3442,7 @@ class IMolecule(SiteCollection, MSONable):
34423442
def __init__(
34433443
self,
34443444
species: Sequence[CompositionLike],
3445-
coords: Sequence[ArrayLike],
3445+
coords: Sequence[np.ndarray] | np.ndarray,
34463446
charge: float = 0.0,
34473447
spin_multiplicity: int | None = None,
34483448
validate_proximity: bool = False,
@@ -5062,7 +5062,7 @@ class Molecule(IMolecule, collections.abc.MutableSequence):
50625062
def __init__(
50635063
self,
50645064
species: Sequence[SpeciesLike],
5065-
coords: Sequence[ArrayLike],
5065+
coords: Sequence[NDArray] | NDArray,
50665066
charge: float = 0.0,
50675067
spin_multiplicity: int | None = None,
50685068
validate_proximity: bool = False,

src/pymatgen/util/string.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ def stream_has_colors(stream: TextIO) -> bool:
322322

323323
def transformation_to_string(
324324
matrix: NDArray,
325-
translation_vec: tuple[float, float, float] = (0, 0, 0),
325+
translation_vec: tuple[float, float, float] | NDArray = (0, 0, 0),
326326
components: tuple[str, str, str] = ("x", "y", "z"),
327327
c: str = "",
328328
delim: str = ",",

0 commit comments

Comments
 (0)