Skip to content

Commit 5f27975

Browse files
janoshlbluque
authored andcommitted
* simplify: structure.sites -> structure * ruff unignore SIM115, fix pymatgen/io/qchem/tests/test_inputs.py * ruff unignore RET501 and fix unnecessary return none * ruff unignore and fix PLW3301 * ruff unignore PLW0603 and fix use of globals * improve TestCRESTOutput readability * ruff unignore PD002 (pandas don't use inplace) * fix LammpsDataTest.test_from_structure() > mol_ids.extend([i + 1] * len(topo)) E TypeError: object of type 'Topology' has no len() pymatgen/io/lammps/data.py:786: TypeError
1 parent 93938d9 commit 5f27975

34 files changed

+187
-272
lines changed

docs_rst/conf-normal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ def find_source():
348348
filename = f"pymatgen/core/{rel_path}#L{line_start}-L{line_end}"
349349
except Exception:
350350
# no need to be relative to core here as module includes full path.
351-
filename = info["module"].replace(".", "/") + ".py"
351+
filename = f"{info['module'].replace('.', '/')}.py"
352352

353353
tag = "v" + __version__
354354
return f"https://github.com/materialsproject/pymatgen/blob/{tag}/{filename}"

pymatgen/alchemy/tests/test_materials.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,10 @@ def test_final_structure(self):
6363
assert self.trans.final_structure.composition.reduced_formula == "NaFePO4"
6464

6565
def test_from_dict(self):
66-
d = json.load(open(os.path.join(PymatgenTest.TEST_FILES_DIR, "transformations.json")))
67-
d["other_parameters"] = {"tags": ["test"]}
68-
ts = TransformedStructure.from_dict(d)
66+
with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "transformations.json")) as file:
67+
dct = json.load(file)
68+
dct["other_parameters"] = {"tags": ["test"]}
69+
ts = TransformedStructure.from_dict(dct)
6970
ts.other_parameters["author"] = "Will"
7071
ts.append_transformation(SubstitutionTransformation({"Fe": "Mn"}))
7172
assert ts.final_structure.composition.reduced_formula == "MnPO4"

pymatgen/analysis/bond_valence.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ def _recurse(assigned=None):
295295
# recurses to find permutations of valences based on whether a
296296
# charge balanced assignment can still be found
297297
if self._n > self.max_permutations:
298-
return None
298+
return
299299
if assigned is None:
300300
assigned = []
301301

@@ -312,16 +312,16 @@ def _recurse(assigned=None):
312312

313313
if highest < 0 or lowest > 0:
314314
self._n += 1
315-
return None
315+
return
316316

317317
if i == len(valences):
318318
evaluate_assignment(assigned)
319319
self._n += 1
320-
return None
320+
return
321321
for v in valences[i]:
322322
new_assigned = list(assigned)
323323
_recurse([*new_assigned, v])
324-
return None
324+
return
325325

326326
else:
327327
n_sites = np.array([len(i) for i in equi_sites])
@@ -373,7 +373,7 @@ def _recurse(assigned=None):
373373
# recurses to find permutations of valences based on whether a
374374
# charge balanced assignment can still be found
375375
if self._n > self.max_permutations:
376-
return None
376+
return
377377
if assigned is None:
378378
assigned = []
379379

@@ -392,18 +392,18 @@ def _recurse(assigned=None):
392392

393393
if highest < -self.charge_neutrality_tolerance or lowest > self.charge_neutrality_tolerance:
394394
self._n += 1
395-
return None
395+
return
396396

397397
if i == len(new_valences):
398398
evaluate_assignment(assigned)
399399
self._n += 1
400-
return None
400+
return
401401

402402
for v in new_valences[i]:
403403
new_assigned = list(assigned)
404404
_recurse([*new_assigned, v])
405405

406-
return None
406+
return
407407

408408
_recurse()
409409

pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -254,57 +254,52 @@ def equivalent_site_index_and_transform(self, psite):
254254
isite = isite2
255255
break
256256
# Get the translation between psite and its corresponding site in the unit cell (Translation I)
257-
thissite = self.structure_environments.structure[isite]
258-
dthissite = psite.frac_coords - thissite.frac_coords
257+
this_site = self.structure_environments.structure[isite]
258+
dthis_site = psite.frac_coords - this_site.frac_coords
259259
# Get the translation between the equivalent site for which the neighbors have been computed and the site in
260260
# the unit cell that corresponds to psite (Translation II)
261-
equivsite = self.structure_environments.structure[self.structure_environments.sites_map[isite]].to_unit_cell()
261+
equiv_site = self.structure_environments.structure[self.structure_environments.sites_map[isite]].to_unit_cell()
262262
# equivsite = self.structure_environments.structure[self.structure_environments.sites_map[isite]]
263263
dequivsite = (
264264
self.structure_environments.structure[self.structure_environments.sites_map[isite]].frac_coords
265-
- equivsite.frac_coords
265+
- equiv_site.frac_coords
266266
)
267267
found = False
268268
# Find the symmetry that applies the site in the unit cell to the equivalent site, as well as the translation
269269
# that gets back the site to the unit cell (Translation III)
270270
# TODO: check that these tolerances are needed, now that the structures are refined before analyzing envs
271271
tolerances = [1e-8, 1e-7, 1e-6, 1e-5, 1e-4]
272272
for tolerance in tolerances:
273-
for symop in self.symops:
274-
newsite = PeriodicSite(
275-
equivsite._species,
276-
symop.operate(equivsite.frac_coords),
277-
equivsite._lattice,
273+
for sym_op in self.symops:
274+
new_site = PeriodicSite(
275+
equiv_site._species,
276+
sym_op.operate(equiv_site.frac_coords),
277+
equiv_site._lattice,
278278
)
279-
if newsite.is_periodic_image(thissite, tolerance=tolerance):
280-
mysym = symop
281-
dthissite2 = thissite.frac_coords - newsite.frac_coords
279+
if new_site.is_periodic_image(this_site, tolerance=tolerance):
280+
my_sym = sym_op
281+
dthissite2 = this_site.frac_coords - new_site.frac_coords
282282
found = True
283283
break
284284
if not found:
285-
symops = [SymmOp.from_rotation_and_translation()]
286-
for symop in symops:
287-
newsite = PeriodicSite(
288-
equivsite._species,
289-
symop.operate(equivsite.frac_coords),
290-
equivsite._lattice,
285+
sym_ops = [SymmOp.from_rotation_and_translation()]
286+
for sym_op in sym_ops:
287+
new_site = PeriodicSite(
288+
equiv_site._species,
289+
sym_op.operate(equiv_site.frac_coords),
290+
equiv_site._lattice,
291291
)
292292
# if newsite.is_periodic_image(thissite):
293-
if newsite.is_periodic_image(thissite, tolerance=tolerance):
294-
mysym = symop
295-
dthissite2 = thissite.frac_coords - newsite.frac_coords
293+
if new_site.is_periodic_image(this_site, tolerance=tolerance):
294+
my_sym = sym_op
295+
dthissite2 = this_site.frac_coords - new_site.frac_coords
296296
found = True
297297
break
298298
if found:
299299
break
300300
if not found:
301301
raise EquivalentSiteSearchError(psite)
302-
return [
303-
self.structure_environments.sites_map[isite],
304-
dequivsite,
305-
dthissite + dthissite2,
306-
mysym,
307-
]
302+
return [self.structure_environments.sites_map[isite], dequivsite, dthis_site + dthissite2, my_sym]
308303

309304
@abc.abstractmethod
310305
def get_site_neighbors(self, site):

pymatgen/analysis/chemenv/coordination_environments/structure_environments.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -677,12 +677,12 @@ def plot_csm_and_maps(self, isite, max_csm=8.0):
677677
import matplotlib.pyplot as plt
678678
except ImportError:
679679
print('Plotting Chemical Environments requires matplotlib ... exiting "plot" function')
680-
return None
680+
return
681681
fig = self.get_csm_and_maps(isite=isite, max_csm=max_csm)
682682
if fig is None:
683-
return None
683+
return
684684
plt.show()
685-
return None
685+
return
686686

687687
def get_csm_and_maps(self, isite, max_csm=8.0, figsize=None, symmetry_measure_type=None):
688688
"""
@@ -728,7 +728,7 @@ def get_csm_and_maps(self, isite, max_csm=8.0, figsize=None, symmetry_measure_ty
728728
if len(min_geoms) == 0:
729729
continue
730730
wds = nb_set.normalized_distances
731-
max_wd = max(max_wd, max(wds))
731+
max_wd = max(max_wd, *wds)
732732
all_wds.append(wds)
733733
all_was.append(nb_set.normalized_angles)
734734
for mp_symbol, cg_dict in min_geoms:

pymatgen/analysis/interfaces/substrate_analyzer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def from_zsl(
5252
if elasticity_tensor is not None:
5353
energy_density = elasticity_tensor.energy_density(strain)
5454

55-
elastic_energy = film.volume * energy_density / len(film.sites)
55+
elastic_energy = film.volume * energy_density / len(film)
5656
else:
5757
elastic_energy = 0
5858

pymatgen/analysis/local_env.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3310,7 +3310,7 @@ def get_order_parameters(
33103310
qsp_theta[i][j][k] = (
33113311
qsp_theta[i][j][k] / norms[i][j][k] if norms[i][j][k] > 1.0e-12 else 0.0
33123312
)
3313-
ops[i] = max(qsp_theta[i][j]) if j == 0 else max(ops[i], max(qsp_theta[i][j]))
3313+
ops[i] = max(qsp_theta[i][j]) if j == 0 else max(ops[i], *qsp_theta[i][j])
33143314
elif t == "bcc":
33153315
ops[i] = 0.0
33163316
for j in range(nneigh):
@@ -3327,7 +3327,7 @@ def get_order_parameters(
33273327
tmp = self._params[i][2] * (d - dmean)
33283328
acc = acc + exp(-0.5 * tmp * tmp)
33293329
for j in range(nneigh):
3330-
ops[i] = max(qsp_theta[i][j]) if j == 0 else max(ops[i], max(qsp_theta[i][j]))
3330+
ops[i] = max(qsp_theta[i][j]) if j == 0 else max(ops[i], *qsp_theta[i][j])
33313331
ops[i] = acc * ops[i] / float(nneigh)
33323332
# nneigh * (nneigh - 1))
33333333
else:

pymatgen/analysis/magnetism/analyzer.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -609,11 +609,7 @@ def __init__(
609609
self,
610610
structure: Structure,
611611
default_magmoms: dict[str, float] | None = None,
612-
strategies: list[str]
613-
| tuple[str, ...] = (
614-
"ferromagnetic",
615-
"antiferromagnetic",
616-
),
612+
strategies: list[str] | tuple[str, ...] = ("ferromagnetic", "antiferromagnetic"),
617613
automatic: bool = True,
618614
truncate_by_symmetry: bool = True,
619615
transformation_kwargs: dict | None = None,
@@ -706,7 +702,11 @@ def __init__(
706702
# we will first create a set of transformations
707703
# and then apply them to our input structure
708704
self.transformations = self._generate_transformations(self.sanitized_structure)
709-
self._generate_ordered_structures(self.sanitized_structure, self.transformations)
705+
ordered_structures, ordered_structures_origins = self._generate_ordered_structures(
706+
self.sanitized_structure, self.transformations
707+
)
708+
self.ordered_structures = ordered_structures
709+
self.ordered_structure_origins = ordered_structures_origins
710710

711711
@staticmethod
712712
def _sanitize_input_structure(input_structure: Structure) -> Structure:
@@ -934,7 +934,7 @@ def _generate_ordered_structures(
934934
self,
935935
sanitized_input_structure: Structure,
936936
transformations: dict[str, MagOrderingTransformation],
937-
):
937+
) -> tuple[list[Structure], list[str]]:
938938
"""Apply our input structure to our list of transformations and output a list
939939
of ordered structures that have been pruned for duplicates and for those
940940
with low symmetry (optional).
@@ -1056,9 +1056,7 @@ def _add_structures(ordered_structures, ordered_structures_origins, structures_t
10561056
self.logger.info(f"Input structure was found in enumerated structures at index {matches.index(True)}")
10571057
self.input_index = matches.index(True)
10581058
self.input_origin = ordered_structures_origins[self.input_index]
1059-
1060-
self.ordered_structures = ordered_structures
1061-
self.ordered_structure_origins = ordered_structures_origins
1059+
return ordered_structures, ordered_structures_origins
10621060

10631061

10641062
MagneticDeformation = namedtuple("MagneticDeformation", "type deformation")

pymatgen/analysis/tests/test_adsorption.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,15 +105,15 @@ def test_generate_adsorption_structures(self):
105105
# Check translation
106106
sites = self.asf_211.find_adsorption_sites()
107107
ads_site_coords = sites["all"][0]
108-
c_site = structures[0].sites[-2]
108+
c_site = structures[0][-2]
109109
assert str(c_site.specie) == "C"
110110
self.assertArrayAlmostEqual(c_site.coords, sites["all"][0])
111111
# Check no translation
112112
structures = self.asf_111.generate_adsorption_structures(co, translate=False)
113113
assert co == Molecule("CO", [[1.0, -0.5, 3], [0.8, 0.46, 3.75]])
114114
sites = self.asf_111.find_adsorption_sites()
115115
ads_site_coords = sites["all"][0]
116-
c_site = structures[0].sites[-2]
116+
c_site = structures[0][-2]
117117
self.assertArrayAlmostEqual(c_site.coords, ads_site_coords + np.array([1.0, -0.5, 3]))
118118

119119
def test_adsorb_both_surfaces(self):

pymatgen/command_line/enumlib_caller.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def get_sg_info(ss):
205205
finder = SpacegroupAnalyzer(Structure.from_sites(ss), self.symm_prec)
206206
return finder.get_space_group_number()
207207

208-
target_sgnum = get_sg_info(symmetrized_structure.sites)
208+
target_sgnum = get_sg_info(list(symmetrized_structure))
209209
curr_sites = list(itertools.chain.from_iterable(disordered_sites))
210210
sgnum = get_sg_info(curr_sites)
211211
ordered_sites = sorted(ordered_sites, key=lambda sites: len(sites))
@@ -250,12 +250,12 @@ def get_sg_info(ss):
250250
output.append(str(self.enum_precision_parameter))
251251
output.append("full")
252252

253-
ndisordered = sum(len(s) for s in disordered_sites)
253+
n_disordered = sum(len(s) for s in disordered_sites)
254254
base = int(
255-
ndisordered
255+
n_disordered
256256
* lcm(
257257
*(
258-
f.limit_denominator(ndisordered * self.max_cell_size).denominator
258+
f.limit_denominator(n_disordered * self.max_cell_size).denominator
259259
for f in map(fractions.Fraction, index_amounts)
260260
)
261261
)
@@ -268,7 +268,7 @@ def get_sg_info(ss):
268268
# enumeration. See Cu7Te5.cif test file.
269269
base *= 10
270270

271-
# base = ndisordered #10 ** int(math.ceil(math.log10(ndisordered)))
271+
# base = ndisordered # 10 ** int(math.ceil(math.log10(ndisordered)))
272272
# To get a reasonable number of structures, we fix concentrations to the
273273
# range expected in the original structure.
274274
total_amounts = sum(index_amounts)

pymatgen/command_line/tests/test_gulp_caller.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def test_get_energy_relax_structure_buckingham(self):
306306
assert isinstance(energy, float)
307307
assert isinstance(struct, Structure)
308308
site_len = len(struct)
309-
assert site_len == len(self.mgo_uc.sites)
309+
assert site_len == len(self.mgo_uc)
310310

311311

312312
@unittest.skipIf(not gulp_present, "gulp not present.")

pymatgen/core/structure.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -436,7 +436,7 @@ def is_valid(self, tol: float = DISTANCE_TOLERANCE) -> bool:
436436
(bool) True if SiteCollection does not contain atoms that are too
437437
close together.
438438
"""
439-
if len(self.sites) == 1:
439+
if len(self) == 1:
440440
return True
441441
all_dists = self.distance_matrix[np.triu_indices(len(self), 1)]
442442
return bool(np.min(all_dists) > tol)
@@ -480,7 +480,7 @@ def add_site_property(self, property_name: str, values: list):
480480
values (list): A sequence of values. Must be same length as
481481
number of sites.
482482
"""
483-
if len(values) != len(self.sites):
483+
if len(values) != len(self):
484484
raise ValueError("Values must be same length as sites.")
485485
for site, val in zip(self.sites, values):
486486
site.properties[property_name] = val
@@ -551,8 +551,11 @@ def add_oxidation_state_by_site(self, oxidation_states: list[float]):
551551
oxidation_states (list): List of oxidation states.
552552
E.g., [1, 1, 1, 1, 2, 2, 2, 2, 5, 5, 5, 5, -2, -2, -2, -2]
553553
"""
554-
if len(oxidation_states) != len(self.sites):
555-
raise ValueError("Oxidation states of all sites must be specified.")
554+
if len(oxidation_states) != len(self):
555+
raise ValueError(
556+
f"Oxidation states of all sites must be specified, expected {len(self)} values, "
557+
f"got {len(oxidation_states)}"
558+
)
556559
for site, ox in zip(self.sites, oxidation_states):
557560
new_sp = {}
558561
for el, occu in site.species.items():
@@ -613,8 +616,8 @@ def add_spin_by_site(self, spins: list[float]):
613616
spins (list): List of spins
614617
E.g., [+5, -5, 0, 0]
615618
"""
616-
if len(spins) != len(self.sites):
617-
raise ValueError("Spin of all sites must be specified in the dictionary.")
619+
if len(spins) != len(self):
620+
raise ValueError(f"Spins for all sites must be specified, expected {len(self)} spins, got {len(spins)}")
618621

619622
for site, spin in zip(self.sites, spins):
620623
new_sp = {}

pymatgen/core/tests/test_structure.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -998,14 +998,14 @@ def test_rotate_sites(self):
998998
self.structure.rotate_sites(
999999
indices=[1],
10001000
theta=2.0 * np.pi / 3.0,
1001-
anchor=self.structure.sites[0].coords,
1001+
anchor=self.structure[0].coords,
10021002
to_unit_cell=False,
10031003
)
10041004
self.assertArrayAlmostEqual(self.structure.frac_coords[1], [-1.25, 1.5, 0.75], decimal=6)
10051005
self.structure.rotate_sites(
10061006
indices=[1],
10071007
theta=2.0 * np.pi / 3.0,
1008-
anchor=self.structure.sites[0].coords,
1008+
anchor=self.structure[0].coords,
10091009
to_unit_cell=True,
10101010
)
10111011
self.assertArrayAlmostEqual(self.structure.frac_coords[1], [0.75, 0.5, 0.75], decimal=6)

0 commit comments

Comments
 (0)