Skip to content

Commit 347fc77

Browse files
Merge remote-tracking branch 'upstream/master' into fstar
2 parents 3c22459 + 387dbf4 commit 347fc77

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+608
-561
lines changed

.github/workflows/lint.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ jobs:
3131
- name: ruff
3232
run: |
3333
ruff --version
34-
ruff . --ignore D
34+
ruff .
3535
3636
- name: black
3737
run: |

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ ci:
88

99
repos:
1010
- repo: https://github.com/astral-sh/ruff-pre-commit
11-
rev: v0.0.286
11+
rev: v0.0.287
1212
hooks:
1313
- id: ruff
1414
args: [--fix]

dev_scripts/update_pt_data.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -78,16 +78,16 @@ def parse_ionic_radii():
7878
header = radii_data[0].split(",")
7979
for idx in range(1, len(radii_data)):
8080
line = radii_data[idx]
81-
toks = line.strip().split(",")
81+
tokens = line.strip().split(",")
8282
suffix = ""
83-
name = toks[1]
83+
name = tokens[1]
8484
if len(name.split(" ")) > 1:
8585
suffix = "_" + name.split(" ")[1]
86-
el = toks[2]
86+
el = tokens[2]
8787

8888
ionic_radii = {}
89-
for j in range(3, len(toks)):
90-
m = re.match(r"^\s*([0-9\.]+)", toks[j])
89+
for j in range(3, len(tokens)):
90+
m = re.match(r"^\s*([0-9\.]+)", tokens[j])
9191
if m:
9292
ionic_radii[int(header[j])] = float(m.group(1))
9393

@@ -109,22 +109,22 @@ def parse_radii():
109109
radii_data = radii_data.split("\r")
110110

111111
for line in radii_data:
112-
toks = line.strip().split(",")
113-
el = toks[1]
112+
tokens = line.strip().split(",")
113+
el = tokens[1]
114114
try:
115-
atomic_radii = float(toks[3]) / 100
115+
atomic_radii = float(tokens[3]) / 100
116116
except Exception:
117-
atomic_radii = toks[3]
117+
atomic_radii = tokens[3]
118118

119119
try:
120-
atomic_radii_calc = float(toks[4]) / 100
120+
atomic_radii_calc = float(tokens[4]) / 100
121121
except Exception:
122-
atomic_radii_calc = toks[4]
122+
atomic_radii_calc = tokens[4]
123123

124124
try:
125-
vdw_radii = float(toks[5]) / 100
125+
vdw_radii = float(tokens[5]) / 100
126126
except Exception:
127-
vdw_radii = toks[5]
127+
vdw_radii = tokens[5]
128128

129129
if el in data:
130130
data[el]["Atomic radius"] = atomic_radii

pymatgen/alchemy/materials.py

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from typing import TYPE_CHECKING, Any
1212
from warnings import warn
1313

14+
import numpy as np
1415
from monty.json import MSONable, jsanitize
1516

1617
from pymatgen.core.structure import Structure
@@ -244,8 +245,14 @@ def structures(self) -> list[Structure]:
244245
h_structs = [Structure.from_dict(s["input_structure"]) for s in self.history if "input_structure" in s]
245246
return [*h_structs, self.final_structure]
246247

247-
@staticmethod
248-
def from_cif_string(
248+
@classmethod
249+
@np.deprecate(message="Use from_cif_str instead")
250+
def from_cif_string(cls, *args, **kwargs): # noqa: D102
251+
return cls.from_cif_str(*args, **kwargs)
252+
253+
@classmethod
254+
def from_cif_str(
255+
cls,
249256
cif_string: str,
250257
transformations: list[AbstractTransformation] | None = None,
251258
primitive: bool = True,
@@ -287,11 +294,16 @@ def from_cif_string(
287294
"original_file": raw_string,
288295
"cif_data": cif_dict[cif_keys[0]],
289296
}
290-
return TransformedStructure(struct, transformations, history=[source_info])
297+
return cls(struct, transformations, history=[source_info])
291298

292-
@staticmethod
293-
def from_poscar_string(
294-
poscar_string: str, transformations: list[AbstractTransformation] | None = None
299+
@classmethod
300+
@np.deprecate(message="Use from_poscar_str instead")
301+
def from_poscar_string(cls, *args, **kwargs): # noqa: D102
302+
return cls.from_poscar_str(*args, **kwargs)
303+
304+
@classmethod
305+
def from_poscar_str(
306+
cls, poscar_string: str, transformations: list[AbstractTransformation] | None = None
295307
) -> TransformedStructure:
296308
"""Generates TransformedStructure from a poscar string.
297309
@@ -300,29 +312,29 @@ def from_poscar_string(
300312
transformations (list[Transformation]): Sequence of transformations
301313
to be applied to the input structure.
302314
"""
303-
p = Poscar.from_str(poscar_string)
304-
if not p.true_names:
315+
poscar = Poscar.from_str(poscar_string)
316+
if not poscar.true_names:
305317
raise ValueError(
306318
"Transformation can be created only from POSCAR strings with proper VASP5 element symbols."
307319
)
308320
raw_string = re.sub(r"'", '"', poscar_string)
309-
struct = p.structure
321+
struct = poscar.structure
310322
source_info = {
311323
"source": "POSCAR",
312324
"datetime": str(datetime.datetime.now()),
313325
"original_file": raw_string,
314326
}
315-
return TransformedStructure(struct, transformations, history=[source_info])
327+
return cls(struct, transformations, history=[source_info])
316328

317329
def as_dict(self) -> dict[str, Any]:
318330
"""Dict representation of the TransformedStructure."""
319-
d = self.final_structure.as_dict()
320-
d["@module"] = type(self).__module__
321-
d["@class"] = type(self).__name__
322-
d["history"] = jsanitize(self.history)
323-
d["last_modified"] = str(datetime.datetime.utcnow())
324-
d["other_parameters"] = jsanitize(self.other_parameters)
325-
return d
331+
dct = self.final_structure.as_dict()
332+
dct["@module"] = type(self).__module__
333+
dct["@class"] = type(self).__name__
334+
dct["history"] = jsanitize(self.history)
335+
dct["last_modified"] = str(datetime.datetime.utcnow())
336+
dct["other_parameters"] = jsanitize(self.other_parameters)
337+
return dct
326338

327339
@classmethod
328340
def from_dict(cls, d) -> TransformedStructure:

pymatgen/alchemy/transmuters.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,9 @@ def append_transformation(self, transformation, extend_collection=False, clear_r
117117
with Pool(self.ncores) as p:
118118
# need to condense arguments into single tuple to use map
119119
z = ((x, transformation, extend_collection, clear_redo) for x in self.transformed_structures)
120-
new_tstructs = p.map(_apply_transformation, z, 1)
120+
nrafo_ew_tstructs = p.map(_apply_transformation, z, 1)
121121
self.transformed_structures = []
122-
for ts in new_tstructs:
122+
for ts in nrafo_ew_tstructs:
123123
self.transformed_structures.extend(ts)
124124
else:
125125
new_structures = []
@@ -188,21 +188,21 @@ def __str__(self):
188188
output.append(str(x.final_structure))
189189
return "\n".join(output)
190190

191-
def append_transformed_structures(self, tstructs_or_transmuter):
191+
def append_transformed_structures(self, trafo_structs_or_transmuter):
192192
"""Method is overloaded to accept either a list of transformed structures
193193
or transmuter, it which case it appends the second transmuter"s
194194
structures.
195195
196196
Args:
197-
tstructs_or_transmuter: A list of transformed structures or a
197+
trafo_structs_or_transmuter: A list of transformed structures or a
198198
transmuter.
199199
"""
200-
if isinstance(tstructs_or_transmuter, self.__class__):
201-
self.transformed_structures.extend(tstructs_or_transmuter.transformed_structures)
200+
if isinstance(trafo_structs_or_transmuter, self.__class__):
201+
self.transformed_structures.extend(trafo_structs_or_transmuter.transformed_structures)
202202
else:
203-
for ts in tstructs_or_transmuter:
203+
for ts in trafo_structs_or_transmuter:
204204
assert isinstance(ts, TransformedStructure)
205-
self.transformed_structures.extend(tstructs_or_transmuter)
205+
self.transformed_structures.extend(trafo_structs_or_transmuter)
206206

207207
@staticmethod
208208
def from_structures(structures, transformations=None, extend_collection=0):
@@ -221,8 +221,8 @@ def from_structures(structures, transformations=None, extend_collection=0):
221221
Returns:
222222
StandardTransmuter
223223
"""
224-
tstruct = [TransformedStructure(s, []) for s in structures]
225-
return StandardTransmuter(tstruct, transformations, extend_collection)
224+
trafo_struct = [TransformedStructure(s, []) for s in structures]
225+
return StandardTransmuter(trafo_struct, transformations, extend_collection)
226226

227227

228228
class CifTransmuter(StandardTransmuter):
@@ -255,8 +255,8 @@ def __init__(self, cif_string, transformations=None, primitive=True, extend_coll
255255
if read_data:
256256
structure_data[-1].append(line)
257257
for data in structure_data:
258-
tstruct = TransformedStructure.from_cif_string("\n".join(data), [], primitive)
259-
transformed_structures.append(tstruct)
258+
trafo_struct = TransformedStructure.from_cif_string("\n".join(data), [], primitive)
259+
transformed_structures.append(trafo_struct)
260260
super().__init__(transformed_structures, transformations, extend_collection)
261261

262262
@staticmethod
@@ -295,8 +295,8 @@ def __init__(self, poscar_string, transformations=None, extend_collection=False)
295295
extend_collection: Whether to use more than one output structure
296296
from one-to-many transformations.
297297
"""
298-
tstruct = TransformedStructure.from_poscar_string(poscar_string, [])
299-
super().__init__([tstruct], transformations, extend_collection=extend_collection)
298+
trafo_struct = TransformedStructure.from_poscar_string(poscar_string, [])
299+
super().__init__([trafo_struct], transformations, extend_collection=extend_collection)
300300

301301
@staticmethod
302302
def from_filenames(poscar_filenames, transformations=None, extend_collection=False):
@@ -310,11 +310,11 @@ def from_filenames(poscar_filenames, transformations=None, extend_collection=Fal
310310
extend_collection:
311311
Same meaning as in __init__.
312312
"""
313-
tstructs = []
313+
trafo_structs = []
314314
for filename in poscar_filenames:
315315
with open(filename) as f:
316-
tstructs.append(TransformedStructure.from_poscar_string(f.read(), []))
317-
return StandardTransmuter(tstructs, transformations, extend_collection=extend_collection)
316+
trafo_structs.append(TransformedStructure.from_poscar_string(f.read(), []))
317+
return StandardTransmuter(trafo_structs, transformations, extend_collection=extend_collection)
318318

319319

320320
def batch_write_vasp_input(

pymatgen/analysis/chemenv/connectivity/environment_nodes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def isite(self):
4242

4343
def __hash__(self) -> int:
4444
"""Simple hash function based on the hash function of the central site."""
45-
return self.central_site.__hash__()
45+
return hash(self.central_site)
4646

4747
def __eq__(self, other: object) -> bool:
4848
if not isinstance(other, AbstractEnvironmentNode):

pymatgen/analysis/graphs.py

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,8 +1151,8 @@ def __mul__(self, scaling_matrix):
11511151
# this could probably be a lot smaller
11521152
tol = 0.05
11531153

1154-
for u, v, k, d in new_g.edges(keys=True, data=True):
1155-
to_jimage = d["to_jimage"] # for node v
1154+
for u, v, k, dct in new_g.edges(keys=True, data=True):
1155+
to_jimage = dct["to_jimage"] # for node v
11561156

11571157
# reduce unnecessary checking
11581158
if to_jimage != (0, 0, 0):
@@ -1191,7 +1191,7 @@ def __mul__(self, scaling_matrix):
11911191
if v_present is not None:
11921192
new_u = u
11931193
new_v = v_present
1194-
new_d = d.copy()
1194+
new_d = dct.copy()
11951195

11961196
# node now inside supercell
11971197
new_d["to_jimage"] = (0, 0, 0)
@@ -1229,13 +1229,13 @@ def __mul__(self, scaling_matrix):
12291229
if v_present is not None:
12301230
new_u = u
12311231
new_v = v_present
1232-
new_d = d.copy()
1232+
new_d = dct.copy()
12331233
new_to_jimage = tuple(map(int, v_expec_image))
12341234

12351235
# normalize direction
12361236
if new_v < new_u:
12371237
new_u, new_v = new_v, new_u
1238-
new_to_jimage = tuple(np.multiply(-1, d["to_jimage"]).astype(int))
1238+
new_to_jimage = tuple(np.multiply(-1, dct["to_jimage"]).astype(int))
12391239

12401240
new_d["to_jimage"] = new_to_jimage
12411241

@@ -1250,18 +1250,18 @@ def __mul__(self, scaling_matrix):
12501250
# add/delete marked edges
12511251
for edge in edges_to_remove:
12521252
new_g.remove_edge(*edge)
1253-
for u, v, d in edges_to_add:
1254-
new_g.add_edge(u, v, **d)
1253+
for u, v, dct in edges_to_add:
1254+
new_g.add_edge(u, v, **dct)
12551255

12561256
# return new instance of StructureGraph with supercell
1257-
d = {
1257+
dct = {
12581258
"@module": type(self).__module__,
12591259
"@class": type(self).__name__,
12601260
"structure": new_structure.as_dict(),
12611261
"graphs": json_graph.adjacency_data(new_g),
12621262
}
12631263

1264-
return StructureGraph.from_dict(d)
1264+
return StructureGraph.from_dict(dct)
12651265

12661266
def __rmul__(self, other):
12671267
return self.__mul__(other)
@@ -1307,7 +1307,7 @@ def __str__(self):
13071307

13081308
def __repr__(self):
13091309
s = "Structure Graph"
1310-
s += f"\nStructure: \n{self.structure.__repr__()}"
1310+
s += f"\nStructure: \n{self.structure!r}"
13111311
s += f"\nGraph: {self.name}\n"
13121312
s += self._edges_to_string(self.graph)
13131313
return s
@@ -1363,8 +1363,7 @@ def __eq__(self, other: object) -> bool:
13631363
if not isinstance(other, StructureGraph):
13641364
return NotImplemented
13651365
# sort for consistent node indices
1366-
# PeriodicSite should have a proper __hash__() value,
1367-
# using its frac_coords as a convenient key
1366+
# PeriodicSite should have a proper __hash__() value, using its frac_coords as a convenient key
13681367
mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure}
13691368
other_sorted = other.__copy__()
13701369
other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])
@@ -1406,8 +1405,7 @@ def diff(self, other, strict=True):
14061405

14071406
if strict:
14081407
# sort for consistent node indices
1409-
# PeriodicSite should have a proper __hash__() value,
1410-
# using its frac_coords as a convenient key
1408+
# PeriodicSite should have a proper __hash__() value, using its frac_coords as a convenient key
14111409
mapping = {tuple(site.frac_coords): self.structure.index(site) for site in other.structure}
14121410
other_sorted = copy.copy(other)
14131411
other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])
@@ -2668,7 +2666,7 @@ def __str__(self) -> str:
26682666

26692667
def __repr__(self) -> str:
26702668
out = "Molecule Graph"
2671-
out += f"\nMolecule: \n{self.molecule.__repr__()}"
2669+
out += f"\nMolecule: \n{self.molecule!r}"
26722670
out += f"\nGraph: {self.name}\n"
26732671
out += self._edges_to_string(self.graph)
26742672
return out
@@ -2725,8 +2723,7 @@ def __eq__(self, other: object) -> bool:
27252723
return NotImplemented
27262724

27272725
# sort for consistent node indices
2728-
# PeriodicSite should have a proper __hash__() value,
2729-
# using its frac_coords as a convenient key
2726+
# PeriodicSite should have a proper __hash__() value, using its frac_coords as a convenient key
27302727
try:
27312728
mapping = {tuple(site.coords): self.molecule.index(site) for site in other.molecule}
27322729
except ValueError:
@@ -2789,8 +2786,7 @@ def diff(self, other, strict=True):
27892786

27902787
if strict:
27912788
# sort for consistent node indices
2792-
# PeriodicSite should have a proper __hash__() value,
2793-
# using its frac_coords as a convenient key
2789+
# PeriodicSite should have a proper __hash__() value, using its frac_coords as a convenient key
27942790
mapping = {tuple(site.frac_coords): self.molecule.index(site) for site in other.molecule}
27952791
other_sorted = copy.copy(other)
27962792
other_sorted.sort(key=lambda site: mapping[tuple(site.frac_coords)])

pymatgen/apps/battery/battery_abc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def __contains__(self, obj):
142142
return obj in self.voltage_pairs
143143

144144
def __iter__(self):
145-
return self.voltage_pairs.__iter__()
145+
return iter(self.voltage_pairs)
146146

147147
def __len__(self):
148148
return len(self.voltage_pairs)

pymatgen/cli/pmg_structure.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,9 @@ def analyze_localenv(args):
5454
"""
5555
bonds = {}
5656
for bond in args.localenv:
57-
toks = bond.split("=")
58-
species = toks[0].split("-")
59-
bonds[(species[0], species[1])] = float(toks[1])
57+
tokens = bond.split("=")
58+
species = tokens[0].split("-")
59+
bonds[(species[0], species[1])] = float(tokens[1])
6060
for filename in args.filenames:
6161
print(f"Analyzing {filename}...")
6262
data = []

0 commit comments

Comments
 (0)