Skip to content

Commit 25effb6

Browse files
authored
Update ruff lint select rules (#82)
1 parent 8157b8a commit 25effb6

38 files changed

+418
-299
lines changed

pyproject.toml

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,32 +73,39 @@ isort.lines-after-imports = 2
7373
select = [
7474
"C", # Complexity checks (e.g., McCabe complexity, comprehensions)
7575
# "ANN001", "ANN201", "ANN401", # flake8-annotations (required strict type annotations for public functions)
76-
# "S", # flake8-bandit (checks basic security issues in code)
76+
"S", # flake8-bandit (checks basic security issues in code)
7777
# "BLE", # flake8-blind-except (checks the except blocks that do not specify exception)
7878
# "FBT", # flake8-boolean-trap (ensure that boolean args can be used with kw only)
79-
# "E", # pycodestyle errors (PEP 8 style guide violations)
79+
"E", # pycodestyle errors (PEP 8 style guide violations)
8080
"W", # pycodestyle warnings (e.g., extra spaces, indentation issues)
8181
# "DOC", # pydoclint issues (e.g., extra or missing return, yield, warnings)
82-
# "A", # flake8-buitins (check variable and function names to not shadow builtins)
83-
# "N", # Naming convention checks (e.g., PEP 8 variable and function names)
82+
"A", # flake8-buitins (check variable and function names to not shadow builtins)
83+
"N", # Naming convention checks (e.g., PEP 8 variable and function names)
8484
"F", # Pyflakes errors (e.g., unused imports, undefined variables)
85-
# "I", # isort (Ensures imports are sorted properly)
86-
# "B", # flake8-bugbear (Detects likely bugs and bad practices)
85+
"I", # isort (Ensures imports are sorted properly)
86+
"B", # flake8-bugbear (Detects likely bugs and bad practices)
8787
"TID", # flake8-tidy-imports (Checks for banned or misplaced imports)
8888
"UP", # pyupgrade (Automatically updates old Python syntax)
89-
# "YTT", # flake8-2020 (Detects outdated Python 2/3 compatibility issues)
90-
# "FLY", # flynt (Converts old-style string formatting to f-strings)
91-
# "PIE", # flake8-pie
89+
"YTT", # flake8-2020 (Detects outdated Python 2/3 compatibility issues)
90+
"FLY", # flynt (Converts old-style string formatting to f-strings)
91+
"PIE", # flake8-pie
9292
# "PL", # pylint
9393
# "RUF", # Ruff-specific rules (Additional optimizations and best practices)
9494
]
9595

9696
ignore = [
97-
"PLR2004", # [magic-value-comparision](https://docs.astral.sh/ruff/rules/magic-value-comparison)
9897
"C90", # [mccabe](https://docs.astral.sh/ruff/rules/#mccabe-c90)
98+
"PLR2004", # [magic-value-comparision](https://docs.astral.sh/ruff/rules/magic-value-comparison)
99+
"S311", # [suspicious-non-cryptographic-random-usage](https://docs.astral.sh/ruff/rules/suspicious-non-cryptographic-random-usage/)
100+
"S404", # [suspicious-subprocess-import](https://docs.astral.sh/ruff/rules/suspicious-subprocess-import/)
101+
"S603", # [subprocess-without-shell-equals-true](https://docs.astral.sh/ruff/rules/subprocess-without-shell-equals-true/)
99102
]
100103

101104
[tool.ruff.lint.per-file-ignores]
105+
# non-lowercase-variable-in-function (N806)
106+
"{femzip_api,femzip_mapper,d3plot,}.py" = ["N806"]
107+
# error-suffix-on-exception-name (N818)
108+
"{femzip_api}.py" = ["N818"]
102109

103110
[tool.ruff.format]
104111
docstring-code-format = true

src/lasso/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from importlib.metadata import version, PackageNotFoundError
1+
from importlib.metadata import PackageNotFoundError, version
2+
23

34
try:
45
__version__ = version("lasso-python")

src/lasso/diffcrash/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
from .diffcrash_run import DiffcrashRun
22

3+
34
__all__ = ["DiffcrashRun"]

src/lasso/diffcrash/diffcrash_run.py

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,14 @@
1010
import time
1111
import typing
1212
from concurrent import futures
13-
from typing import Union
1413
from pathlib import Path
14+
from typing import Union
15+
1516
import psutil
1617

17-
# from ..logging import str_error, str_info, str_running, str_success, str_warn
1818
from lasso.logging import str_error, str_info, str_running, str_success, str_warn
1919

20+
2021
# pylint: disable = too-many-lines
2122

2223
DC_STAGE_SETUP = "SETUP"
@@ -337,9 +338,7 @@ def _parse_crash_code(self, crash_code) -> str:
337338
self.logger.info(self._msg_option.format("crash-code", crash_code))
338339

339340
if not crash_code_ok:
340-
err_msg = (
341-
f"Invalid crash code '{crash_code}'. Please use one of: {str(valid_crash_codes)}"
342-
)
341+
err_msg = f"Invalid crash code '{crash_code}'. Please use one of: {valid_crash_codes!s}"
343342
self.logger.error(err_msg)
344343
raise RuntimeError(str_error(err_msg))
345344

@@ -647,22 +646,21 @@ def run_import(self, pool: futures.ThreadPoolExecutor):
647646
str(i_filepath + counter_offset),
648647
]
649648
# indeed there is a parameter file
649+
elif self.use_id_mapping:
650+
args = [
651+
self.diffcrash_home / f"DFC_Import_{self.crash_code}",
652+
"-ID",
653+
self.simulation_runs[i_filepath],
654+
self.project_dir,
655+
str(i_filepath + counter_offset),
656+
]
650657
else:
651-
if self.use_id_mapping:
652-
args = [
653-
self.diffcrash_home / f"DFC_Import_{self.crash_code}",
654-
"-ID",
655-
self.simulation_runs[i_filepath],
656-
self.project_dir,
657-
str(i_filepath + counter_offset),
658-
]
659-
else:
660-
args = [
661-
self.diffcrash_home / f"DFC_Import_{self.crash_code}",
662-
self.simulation_runs[i_filepath],
663-
self.project_dir,
664-
str(i_filepath + counter_offset),
665-
]
658+
args = [
659+
self.diffcrash_home / f"DFC_Import_{self.crash_code}",
660+
self.simulation_runs[i_filepath],
661+
self.project_dir,
662+
str(i_filepath + counter_offset),
663+
]
666664

667665
# append args to list
668666
import_arguments.append(args)
@@ -689,7 +687,11 @@ def run_import(self, pool: futures.ThreadPoolExecutor):
689687

690688
if n_imports_finished != n_new_imports_finished:
691689
# pylint: disable = consider-using-f-string
692-
msg = f"Running Imports ... [{n_new_imports_finished}/{len(return_code_futures)}] - {percentage:3.2f}%\r"
690+
msg = (
691+
f"Running Imports ... [{n_new_imports_finished}/{len(return_code_futures)}] - "
692+
f"{percentage:3.2f}%\r"
693+
)
694+
693695
print(str_running(msg), end="", flush=True)
694696
self.logger.info(msg)
695697

@@ -1206,7 +1208,7 @@ def read_config_file(self, config_file: str) -> list[str]:
12061208
conf_lines = conf.readlines()
12071209
line = 0
12081210

1209-
for i in range(0, len(conf_lines)):
1211+
for i in range(len(conf_lines)):
12101212
if conf_lines[i].find("FUNCTION") >= 0:
12111213
line = i + 1
12121214
break
@@ -1216,7 +1218,7 @@ def read_config_file(self, config_file: str) -> list[str]:
12161218
if line != 0:
12171219
while 1:
12181220
while 1:
1219-
for i in range(0, len(conf_lines[line])):
1221+
for i in range(len(conf_lines[line])):
12201222
if conf_lines[line][i] == "<":
12211223
element_start = i + 1
12221224
if conf_lines[line][i] == ">":
@@ -1231,7 +1233,7 @@ def read_config_file(self, config_file: str) -> list[str]:
12311233
j += 1
12321234
items = check.split(" ")
12331235
pos = -1
1234-
for n in range(0, len(items)):
1236+
for n in range(len(items)):
12351237
if items[n].startswith("!"):
12361238
msg = f"FOUND at {n}"
12371239
print(msg)
@@ -1240,7 +1242,7 @@ def read_config_file(self, config_file: str) -> list[str]:
12401242
break
12411243
pos = len(items)
12421244

1243-
for n in range(0, pos):
1245+
for n in range(pos):
12441246
if items[n] == "PDMX" or items[n] == "pdmx":
12451247
break
12461248
if items[n] == "PDXMX" or items[n] == "pdxmx":
@@ -1262,7 +1264,7 @@ def read_config_file(self, config_file: str) -> list[str]:
12621264

12631265
for k in range(n, pos):
12641266
postval = None
1265-
for m in range(0, n):
1267+
for m in range(n):
12661268
if items[m] == "coordinates":
12671269
items[m] = "geometry"
12681270
if postval is None:

src/lasso/diffcrash/run.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
DiffcrashRun,
1313
parse_diffcrash_args,
1414
)
15-
1615
from lasso.logging import str_error
1716

1817

src/lasso/dimred/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
from .dimred_run import DimredRun, DimredStage
22

3+
34
__all__ = ["DimredRun", "DimredStage"]

src/lasso/dimred/dimred_run.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
import shutil
77
import sys
88
import time
9+
from collections.abc import Sequence
910
from concurrent.futures.process import ProcessPoolExecutor
1011
from typing import Union
11-
from collections.abc import Sequence
1212

1313
import h5py
1414
import numpy as np
@@ -18,7 +18,6 @@
1818
from rich.table import Table
1919
from rich.text import Text
2020

21-
from lasso.utils.rich_progress_bars import PlaceHolderBar, WorkingDots
2221
from lasso.dimred.svd.clustering_betas import (
2322
create_cluster_arg_dict,
2423
create_detector_arg_dict,
@@ -27,6 +26,8 @@
2726
from lasso.dimred.svd.plot_beta_clusters import plot_clusters_js
2827
from lasso.dimred.svd.pod_functions import calculate_v_and_betas
2928
from lasso.dimred.svd.subsampling_methods import create_reference_subsample, remap_random_subsample
29+
from lasso.utils.rich_progress_bars import PlaceHolderBar, WorkingDots
30+
3031

3132
# pylint: disable = too-many-lines
3233

@@ -505,7 +506,8 @@ def _parse_part_ids(self, part_ids: Union[Sequence[int], None]) -> Sequence[int]
505506
if not part_ids:
506507
return ()
507508

508-
assert all(isinstance(pid, int) for pid in part_ids), "All part ids must be of type 'int'"
509+
if not all(isinstance(pid, int) for pid in part_ids):
510+
raise TypeError("All part ids must be of type 'int'")
509511

510512
return part_ids
511513

@@ -583,14 +585,13 @@ def _parse_simulation_and_reference_runs(
583585
self.raise_error(err_msg)
584586

585587
reference_run = os.path.normpath(reference_run_pattern)
588+
# use first simulation run if no reference run was provided
589+
# check if enough simulation runs remain
590+
elif len(simulation_runs) > 1:
591+
reference_run = simulation_runs[0]
586592
else:
587-
# use first simulation run if no reference run was provided
588-
# check if enough simulation runs remain
589-
if len(simulation_runs) > 1:
590-
reference_run = simulation_runs[0]
591-
else:
592-
err_msg = "Number of Simulation runs after using first as reference run is zero."
593-
self.raise_error(err_msg)
593+
err_msg = "Number of Simulation runs after using first as reference run is zero."
594+
self.raise_error(err_msg)
594595

595596
# add to table
596597
table.add_row("reference-run", reference_run)
@@ -804,7 +805,10 @@ def subsample_to_reference_run(self):
804805
h5_sample.attrs[HDF5FileNames.SUBSAMPLE_PROCESS_TIME.value] = sub[
805806
1
806807
].result()[1]
807-
submitted_samples.pop(i)
808+
# FIXME: loop-iterator-mutation (B909)
809+
# Mutation to loop iterable `submitted_samples` during iteration
810+
# See: https://docs.astral.sh/ruff/rules/loop-iterator-mutation/
811+
submitted_samples.pop(i) # noqa B909
808812
prog.advance(task1) # type: ignore
809813
t_cum_io += sub[1].result()[2]
810814
t_cum += sub[1].result()[1]

src/lasso/dimred/graph_laplacian.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ def _laplacian_gauss_idw(
7676
L: array-like, shape (n_points, n_points)
7777
The laplacian matrix for manifold given by its sampling `points`.
7878
"""
79-
assert 2 == points.ndim
79+
if points.ndim != 2:
80+
raise TypeError("Only 2D arrays are supported.")
8081

8182
if min_neighbors is None:
8283
min_neighbors = points.shape[1]
@@ -110,7 +111,8 @@ def _laplacian_gauss_idw(
110111
graph[i, j] = d = np.exp(d)
111112
graph[j, i] = d[:, np.newaxis]
112113

113-
assert 0 == (graph != graph.T).sum()
114+
if not np.array_equal(graph, graph.T):
115+
raise RuntimeError("graph matrix is not symetric.")
114116

115117
return csgraph.laplacian(graph, normed=True)
116118

src/lasso/dimred/hashing.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import multiprocessing
22
import os
33
import time
4-
from typing import Union
54
from collections.abc import Sequence
5+
from typing import Union
66

77
import h5py
88
import numpy as np
@@ -83,7 +83,10 @@ def is_orientation_flip_required(eigenvectors1: np.ndarray, eigenvectors2: np.nd
8383
The eigenmodes require switching if the dot product of the knn-eigenfields yield
8484
a negative result.
8585
"""
86-
assert eigenvectors1.shape == eigenvectors2.shape
86+
if eigenvectors1.shape != eigenvectors2.shape:
87+
raise AssertionError(
88+
f"shape mismatch detected. {eigenvectors1.shape} not equal to {eigenvectors2.shape}"
89+
)
8790

8891
# one eigenmode only
8992
if eigenvectors1.ndim == 1:
@@ -133,7 +136,10 @@ def _compute_mode_similarities(
133136

134137
mode_similarities = []
135138
for i_hash, j_hash in matches:
136-
assert hashes1.shape[2] == hashes2.shape[2]
139+
if hashes1.shape[2] != hashes2.shape[2]:
140+
raise AssertionError(
141+
f"Unequal number of columns. {hashes1.shape[2]} is not equal to {hashes2.shape[2]}"
142+
)
137143

138144
field1 = eigenvectors_sub1[:, i_hash]
139145
field2 = eigenvectors_sub2[:, j_hash]
@@ -238,7 +244,8 @@ def run_hash_comparison(
238244

239245
# pylint: disable = too-many-locals, too-many-statements
240246

241-
assert n_threads > 0
247+
if n_threads <= 0:
248+
raise ValueError("Number of threads cannot be negative or zero.")
242249

243250
# fixed settings
244251
hdf5_dataset_compression = "gzip"
@@ -621,7 +628,11 @@ def compute_hashes(
621628
For comparison, only y is usually used.
622629
"""
623630

624-
assert eig_vecs.shape[0] == len(result_field), f"{eig_vecs.shape[0]} != {len(result_field)}"
631+
if eig_vecs.shape[0] != len(result_field):
632+
raise AssertionError(
633+
f"Unequal number of rows detected. {eig_vecs.shape[0]} "
634+
f"is not equal to {len(result_field)}"
635+
)
625636

626637
# Note: needs to be vectorized to speed it up
627638

src/lasso/dimred/hashing_sphere.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from scipy.stats import binned_statistic_2d
1212
from sklearn.preprocessing import normalize
1313

14+
1415
warnings.simplefilter(action="ignore", category=FutureWarning)
1516

1617

@@ -31,7 +32,8 @@ def _create_sphere_mesh(diameter: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
3132
beta bin boundaries
3233
"""
3334

34-
assert diameter.dtype == np.float32
35+
if diameter.dtype != np.float32:
36+
raise TypeError("diameter array must be of type `np.float32`.")
3537

3638
# partition latitude
3739
n_alpha = 145
@@ -59,8 +61,7 @@ def _create_sphere_mesh(diameter: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
5961
bin_beta = 1 - tmp
6062

6163
# In case of trailing floats (-1.00000004 for example)
62-
if bin_beta[-1] < -1:
63-
bin_beta[-1] = -1
64+
bin_beta[-1] = max(bin_beta[-1], -1)
6465

6566
bin_beta = np.arccos(bin_beta)
6667

@@ -139,10 +140,16 @@ def sphere_hashing(
139140
"""
140141
# bin_numbers holds the bin_number for its respective index and must have
141142
# same length as the number of points
142-
assert len(bin_numbers[0] == len(field))
143+
if not len(bin_numbers[0] == len(field)):
144+
raise AssertionError(
145+
"bin_numbers holds the bin_number for its respective index and"
146+
"must have same length as the number of points."
147+
)
143148
# check data types
144-
assert bin_numbers.dtype == np.int
145-
assert bin_counts.dtype == np.float32
149+
if not np.issubdtype(bin_numbers.dtype, np.integer):
150+
raise TypeError(f"Expected int dtype got {bin_numbers.dtype}")
151+
if not np.issubdtype(bin_counts.dtype, np.floating):
152+
raise TypeError(f"Expected float dtype got {bin_counts.dtype}.")
146153

147154
n_rows = bin_counts.shape[0]
148155
n_cols = bin_counts.shape[1]

0 commit comments

Comments
 (0)