Skip to content

Commit b74a5df

Browse files
authored
Ruff fixes (#3564)
* fix ruff SIM300 Yoda asserts ruff ignore ANN101 COM812 NPY002 PTH PLC1901 PLW1514 ruff ignore ANN201 S101 for tests/ rename f->file * fix ruff F841 local var assigned but never used * fix ruff SIM113 use enumerate() for index variable * fix ruff RUF021 parenthesize `a and b` when chaining `and` and `or` together * fix likely unintentional operator precedence in LobsterEnv._find_relevant_atoms_additional_condition() (val1 < 0.0 < val2) or (val2 < 0.0 < val1) was not evaluated together * fix ruff E226 missing whitespace around arithmetic op * fix super.__init__() call missing parens * fix ZeroDivisionError in > self.logger.debug(f"Average time per combi = {(now - start_time) / idx} seconds")
1 parent e502e33 commit b74a5df

Some content is hidden

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

52 files changed

+241
-257
lines changed

.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.1.13
11+
rev: v0.1.14
1212
hooks:
1313
- id: ruff
1414
args: [--fix, --unsafe-fixes]

dev_scripts/chemenv/strategies/multi_weights_strategy_parameters.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,8 +269,8 @@ def get_weights(self, weights_options):
269269
"+-------------------------------------------------------------+\n"
270270
)
271271

272-
with open("ce_pairs.json") as f:
273-
ce_pairs = json.load(f)
272+
with open("ce_pairs.json") as file:
273+
ce_pairs = json.load(file)
274274
self_weight_max_csms: dict[str, list[float]] = {}
275275
self_weight_max_csms_per_cn: dict[str, list[float]] = {}
276276
all_self_max_csms = []

pymatgen/alchemy/filters.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -265,9 +265,11 @@ def get_sg(s):
265265

266266
for s in self.existing_structures:
267267
if (
268-
self.structure_matcher._comparator.get_hash(structure.composition)
269-
== self.structure_matcher._comparator.get_hash(s.composition)
270-
and self.symprec is None
268+
(
269+
self.structure_matcher._comparator.get_hash(structure.composition)
270+
== self.structure_matcher._comparator.get_hash(s.composition)
271+
and self.symprec is None
272+
)
271273
or get_sg(s) == get_sg(structure)
272274
) and self.structure_matcher.fit(s, structure):
273275
return False

pymatgen/analysis/adsorption.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,7 @@ def substitute(site, i):
582582

583583
for idx, site in enumerate(sym_slab):
584584
if dist - range_tol < site.frac_coords[2] < dist + range_tol and (
585-
target_species and site.species_string in target_species or not target_species
585+
(target_species and site.species_string in target_species) or not target_species
586586
):
587587
substituted_slabs.append(substitute(site, idx))
588588

pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1062,7 +1062,7 @@ def __init__(
10621062
:param max_csm:
10631063
:param symmetry_measure_type:
10641064
"""
1065-
super.__init__(
1065+
super().__init__(
10661066
self,
10671067
structure_environments,
10681068
additional_condition=additional_condition,

pymatgen/analysis/chemenv/coordination_environments/structure_environments.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1763,10 +1763,8 @@ def get_site_info_for_specie_allces(self, specie, min_fraction=0):
17631763
oxi_state = specie.oxi_state
17641764
for isite, site in enumerate(self.structure):
17651765
if (
1766-
element in [sp.symbol for sp in site.species]
1767-
and self.valences == "undefined"
1768-
or oxi_state == self.valences[isite]
1769-
):
1766+
element in [sp.symbol for sp in site.species] and self.valences == "undefined"
1767+
) or oxi_state == self.valences[isite]:
17701768
if self.coordination_environments[isite] is None:
17711769
continue
17721770
for ce_dict in self.coordination_environments[isite]:

pymatgen/analysis/diffraction/tem.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,6 @@
2020
if TYPE_CHECKING:
2121
from pymatgen.core import Structure
2222

23-
with open(os.path.join(os.path.dirname(__file__), "atomic_scattering_params.json")) as f:
24-
ATOMIC_SCATTERING_PARAMS = json.load(f)
25-
2623
__author__ = "Frank Wan, Jason Liang"
2724
__copyright__ = "Copyright 2020, The Materials Project"
2825
__version__ = "0.22"
@@ -31,13 +28,18 @@
3128
__date__ = "03/31/2020"
3229

3330

31+
module_dir = os.path.dirname(__file__)
32+
with open(f"{module_dir}/atomic_scattering_params.json") as file:
33+
ATOMIC_SCATTERING_PARAMS = json.load(file)
34+
35+
3436
class TEMCalculator(AbstractDiffractionPatternCalculator):
3537
"""
3638
Computes the TEM pattern of a crystal structure for multiple Laue zones.
3739
Code partially inspired from XRD calculation implementation. X-ray factor to electron factor
3840
conversion based on the International Table of Crystallography.
3941
#TODO: Could add "number of iterations", "magnification", "critical value of beam",
40-
"twin direction" for certain materials, "sample thickness", and "excitation error s".
42+
"twin direction" for certain materials, "sample thickness", and "excitation error s".
4143
"""
4244

4345
def __init__(

pymatgen/analysis/local_env.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1211,9 +1211,9 @@ def __init__(
12111211

12121212
# Load elemental radii table
12131213
bonds_file = f"{module_dir}/bonds_jmol_ob.yaml"
1214-
with open(bonds_file) as f:
1214+
with open(bonds_file) as file:
12151215
yaml = YAML()
1216-
self.el_radius = yaml.load(f)
1216+
self.el_radius = yaml.load(file)
12171217

12181218
# Update any user preference elemental radii
12191219
if el_radius_updates:

pymatgen/analysis/magnetism/heisenberg.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,9 @@ def _get_unique_sites(structure):
146146
unique_site_ids = {}
147147
wyckoff_ids = {}
148148

149-
i = 0
150-
for indices, symbol in zip(equivalent_indices, wyckoff_symbols):
151-
unique_site_ids[tuple(indices)] = i
152-
wyckoff_ids[i] = symbol
153-
i += 1
149+
for idx, (indices, symbol) in enumerate(zip(equivalent_indices, wyckoff_symbols)):
150+
unique_site_ids[tuple(indices)] = idx
151+
wyckoff_ids[idx] = symbol
154152
for index in indices:
155153
wyckoff[index] = symbol
156154

pymatgen/apps/borg/hive.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def assimilate(self, path):
224224
else:
225225
for filename in filenames:
226226
files = sorted(glob(os.path.join(path, filename + "*")))
227-
if len(files) == 1 or filename in ("INCAR", "POTCAR") or len(files) == 1 and filename == "DYNMAT":
227+
if len(files) == 1 or filename in ("INCAR", "POTCAR") or (len(files) == 1 and filename == "DYNMAT"):
228228
files_to_parse[filename] = files[0]
229229
elif len(files) > 1:
230230
# Since multiple files are ambiguous, we will always

pymatgen/apps/borg/queen.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,11 @@ def serial_assimilate(self, rootpath):
7474
for parent, subdirs, files in os.walk(rootpath):
7575
valid_paths.extend(self._drone.get_valid_paths((parent, subdirs, files)))
7676
data = []
77-
count = 0
7877
total = len(valid_paths)
79-
for path in valid_paths:
78+
for idx, path in enumerate(valid_paths, 1):
8079
new_data = self._drone.assimilate(path)
8180
self._data.append(new_data)
82-
count += 1
83-
logger.info(f"{count}/{total} ({count / total:.2%}) done")
81+
logger.info(f"{idx}/{total} ({idx / total:.2%}) done")
8482
for json_str in data:
8583
self._data.append(json.loads(json_str, cls=MontyDecoder))
8684

pymatgen/cli/pmg_potcar.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@
1010
from pymatgen.io.vasp import Potcar
1111

1212

13-
def proc_dir(dirname, procfilefunction):
13+
def proc_dir(dirname, proc_file_function):
1414
"""Process a directory.
1515
1616
Args:
1717
dirname (str): Directory name.
18-
procfilefunction (callable): Callable to execute on directory.
18+
proc_file_function (callable): Callable to execute on directory.
1919
"""
2020
for f in os.listdir(dirname):
2121
if os.path.isdir(os.path.join(dirname, f)):
22-
proc_dir(os.path.join(dirname, f), procfilefunction)
22+
proc_dir(os.path.join(dirname, f), proc_file_function)
2323
else:
24-
procfilefunction(dirname, f)
24+
proc_file_function(dirname, f)
2525

2626

2727
def gen_potcar(dirname, filename):

pymatgen/command_line/critic2_caller.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,8 +93,8 @@ def __init__(self, input_script):
9393
# not otherwise used
9494
self._input_script = input_script
9595

96-
with open("input_script.cri", mode="w") as f:
97-
f.write(input_script)
96+
with open("input_script.cri", mode="w") as file:
97+
file.write(input_script)
9898

9999
args = ["critic2", "input_script.cri"]
100100
with subprocess.Popen(args, stdout=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True) as rs:

pymatgen/command_line/gulp_caller.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,9 @@ def get_energy(gout: str):
526526
"""
527527
energy = None
528528
for line in gout.split("\n"):
529-
if "Total lattice energy" in line and "eV" in line or "Non-primitive unit cell" in line and "eV" in line:
529+
if ("Total lattice energy" in line and "eV" in line) or (
530+
"Non-primitive unit cell" in line and "eV" in line
531+
):
530532
energy = line.split()
531533
if energy:
532534
return float(energy[4])
@@ -863,9 +865,9 @@ class TersoffPotential:
863865

864866
def __init__(self):
865867
"""Init TersoffPotential."""
866-
with open(f"{module_dir}/OxideTersoffPotentials") as f:
868+
with open(f"{module_dir}/OxideTersoffPotentials") as file:
867869
data = {}
868-
for row in f:
870+
for row in file:
869871
metaloxi = row.split()[0]
870872
line = row.split(")")
871873
data[metaloxi] = line[1]

pymatgen/command_line/vampire_caller.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,8 @@ def _create_mat(self):
225225

226226
self.mat_id_dict = mat_id_dict
227227

228-
with open(mat_file_name, mode="w") as f:
229-
f.write(mat_file)
228+
with open(mat_file_name, mode="w") as file:
229+
file.write(mat_file)
230230

231231
def _create_input(self):
232232
structure = self.structure
@@ -330,12 +330,12 @@ def _create_ucf(self):
330330

331331
# J_ij exchange interaction matrix
332332
sgraph = self.sgraph
333-
ninter = 0
333+
n_inter = 0
334334
for idx in range(len(sgraph.graph.nodes)):
335-
ninter += sgraph.get_coordination_of_site(idx)
335+
n_inter += sgraph.get_coordination_of_site(idx)
336336

337337
ucf += ["# Interactions"]
338-
ucf += [f"{ninter} isotropic"]
338+
ucf += [f"{n_inter} isotropic"]
339339

340340
iid = 0 # counts number of interaction
341341
for idx in range(len(sgraph.graph.nodes)):
@@ -363,8 +363,8 @@ def _create_ucf(self):
363363
ucf = "\n".join(ucf)
364364
ucf_file_name = mat_name + ".ucf"
365365

366-
with open(ucf_file_name, mode="w") as f:
367-
f.write(ucf)
366+
with open(ucf_file_name, mode="w") as file:
367+
file.write(ucf)
368368

369369
@staticmethod
370370
def parse_stdout(vamp_stdout, n_mats: int) -> tuple:

pymatgen/core/bonds.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@
1919

2020
def _load_bond_length_data():
2121
"""Loads bond length data from json file."""
22-
with open(os.path.join(os.path.dirname(__file__), "bond_lengths.json")) as f:
22+
with open(os.path.join(os.path.dirname(__file__), "bond_lengths.json")) as file:
2323
data = collections.defaultdict(dict)
24-
for row in json.load(f):
24+
for row in json.load(file):
2525
els = sorted(row["elements"])
2626
data[tuple(els)][row["bond_order"]] = row["length"]
2727
return data

pymatgen/core/structure.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3621,8 +3621,8 @@ def from_file(cls, filename):
36213621
filename = str(filename)
36223622
from pymatgen.io.gaussian import GaussianOutput
36233623

3624-
with zopen(filename) as f:
3625-
contents = f.read()
3624+
with zopen(filename) as file:
3625+
contents = file.read()
36263626
fname = filename.lower()
36273627
if fnmatch(fname, "*.xyz*"):
36283628
return cls.from_str(contents, fmt="xyz")

pymatgen/core/trajectory.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,8 @@ def extend(self, trajectory: Trajectory) -> None:
239239
if (
240240
self.lattice is None # is molecules
241241
and trajectory.lattice is not None # is structures
242-
or self.lattice is not None # is structures
242+
) or (
243+
self.lattice is not None # is structures
243244
and trajectory.lattice is None # is molecules
244245
):
245246
raise ValueError("Cannot combine `Molecule`- and `Structure`-based `Trajectory`. objects.")
@@ -442,8 +443,8 @@ def write_Xdatcar(
442443

443444
xdatcar_string = "\n".join(lines) + "\n"
444445

445-
with zopen(filename, mode="wt") as f:
446-
f.write(xdatcar_string)
446+
with zopen(filename, mode="wt") as file:
447+
file.write(xdatcar_string)
447448

448449
def as_dict(self) -> dict:
449450
"""Return the trajectory as a MSONable dict."""

pymatgen/electronic_structure/boltztrap.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2139,29 +2139,26 @@ def read_cube_file(filename):
21392139
"""
21402140
with open(filename) as file:
21412141
natoms = 0
2142-
count_line = 0
2143-
for line in file:
2142+
for idx, line in enumerate(file):
21442143
line = line.rstrip("\n")
2145-
if count_line == 0 and "CUBE" not in line:
2144+
if idx == 0 and "CUBE" not in line:
21462145
raise ValueError("CUBE file format not recognized")
21472146

2148-
if count_line == 2:
2147+
if idx == 2:
21492148
tokens = line.split()
21502149
natoms = int(tokens[0])
2151-
if count_line == 3:
2150+
if idx == 3:
21522151
tokens = line.split()
21532152
n1 = int(tokens[0])
2154-
elif count_line == 4:
2153+
elif idx == 4:
21552154
tokens = line.split()
21562155
n2 = int(tokens[0])
2157-
elif count_line == 5:
2156+
elif idx == 5:
21582157
tokens = line.split()
21592158
n3 = int(tokens[0])
2160-
elif count_line > 5:
2159+
elif idx > 5:
21612160
break
21622161

2163-
count_line += 1
2164-
21652162
if "fort.30" in filename:
21662163
energy_data = np.genfromtxt(filename, skip_header=natoms + 6, skip_footer=1)
21672164
nlines_data = len(energy_data)

pymatgen/io/abinit/abiobjects.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def structure_from_abivars(cls=None, *args, **kwargs) -> Structure:
112112
znucl=13,
113113
)
114114
115-
`xred` can be replaced with `xcart` or `xangst`.
115+
xred can be replaced with xcart or xangst.
116116
"""
117117
kwargs.update(dict(*args))
118118
cls = cls or Structure
@@ -307,8 +307,7 @@ def contract(string):
307307

308308
class AbivarAble(metaclass=abc.ABCMeta):
309309
"""
310-
An `AbivarAble` object provides a method `to_abivars`
311-
that returns a dictionary with the abinit variables.
310+
An AbivarAble object provides a method to_abivars that returns a dictionary with the abinit variables.
312311
"""
313312

314313
@abc.abstractmethod
@@ -369,17 +368,13 @@ def as_spinmode(cls, obj):
369368

370369
# Assume a string with mode
371370
try:
372-
return _mode2spinvars[obj]
371+
return _mode_to_spin_vars[obj]
373372
except KeyError:
374373
raise KeyError(f"Wrong value for spin_mode: {obj}")
375374

376375
def to_abivars(self):
377376
"""Dictionary with Abinit input variables."""
378-
return {
379-
"nsppol": self.nsppol,
380-
"nspinor": self.nspinor,
381-
"nspden": self.nspden,
382-
}
377+
return {"nsppol": self.nsppol, "nspinor": self.nspinor, "nspden": self.nspden}
383378

384379
def as_dict(self):
385380
"""Convert object to dict."""
@@ -394,7 +389,7 @@ def from_dict(cls, d):
394389

395390

396391
# An handy Multiton
397-
_mode2spinvars = {
392+
_mode_to_spin_vars = {
398393
"unpolarized": SpinMode("unpolarized", 1, 1, 1),
399394
"polarized": SpinMode("polarized", 2, 1, 2),
400395
"afm": SpinMode("afm", 1, 1, 2),

0 commit comments

Comments
 (0)