Skip to content

Commit 0ab3cb1

Browse files
committed
misc: Manually lint examples, tests, scripts, etc
1 parent 5306fb9 commit 0ab3cb1

93 files changed

Lines changed: 1239 additions & 835 deletions

File tree

Some content is hidden

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

benchmarks/regression/benchmarks/arguments.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ class Processing:
1010
def setup(self):
1111
grid = Grid(shape=(5, 5, 5))
1212

13-
funcs = [Function(name='f%d' % n, grid=grid) for n in range(30)]
14-
tfuncs = [TimeFunction(name='u%d' % n, grid=grid) for n in range(30)]
15-
stfuncs = [SparseTimeFunction(name='su%d' % n, grid=grid, npoint=1, nt=100)
13+
funcs = [Function(name=f'f{n}', grid=grid) for n in range(30)]
14+
tfuncs = [TimeFunction(name=f'u{n}', grid=grid) for n in range(30)]
15+
stfuncs = [SparseTimeFunction(name=f'su{n}', grid=grid, npoint=1, nt=100)
1616
for n in range(30)]
1717
v = TimeFunction(name='v', grid=grid, space_order=2)
1818

benchmarks/user/advisor/run_advisor.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,7 @@ def run_with_advisor(path, output, name, exec_args):
140140
advixe_logger.setLevel(logging.INFO)
141141

142142
advixe_formatter = logging.Formatter('%(asctime)s: %(message)s')
143-
logger_datetime = '%d.%d.%d.%d.%d.%d' % (dt.year, dt.month,
144-
dt.day, dt.hour, dt.minute, dt.second)
143+
logger_datetime = f'{dt.year}.{dt.month}.{dt.day}.{dt.hour}.{dt.minute}.{dt.second}'
145144
advixe_handler = logging.FileHandler(f'{output}/{name}_{logger_datetime}.log')
146145
advixe_handler.setFormatter(advixe_formatter)
147146
advixe_logger.addHandler(advixe_handler)

benchmarks/user/benchmark.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
from contextlib import suppress
23

34
import click
45
import numpy as np
@@ -73,8 +74,10 @@ def run_op(solver, operator, **options):
7374
# Get the operator if exist
7475
try:
7576
op = getattr(solver, operator)
76-
except AttributeError:
77-
raise AttributeError(f"Operator {operator} not implemented for {solver}")
77+
except AttributeError as e:
78+
raise AttributeError(
79+
f"Operator {operator} not implemented for {solver}"
80+
) from e
7881

7982
# This is a bit ugly but not sure how to make clean input creation for different op
8083
if operator == "forward":
@@ -164,7 +167,10 @@ def from_opt(ctx, param, value):
164167
# E.g. `'advanced'`
165168
opt = value
166169
if opt not in configuration._accepted['opt']:
167-
raise click.BadParameter("Invalid choice `{}` (choose from {})".format(opt, str(configuration._accepted['opt'])))
170+
raise click.BadParameter(
171+
f'Invalid choice `{opt} '
172+
f'(choose from {str(configuration._accepted["opt"])})'
173+
)
168174
return value
169175

170176
def config_blockshape(ctx, param, value):
@@ -180,7 +186,7 @@ def config_blockshape(ctx, param, value):
180186
# 1. integers, not strings
181187
# 2. sanity check the (hierarchical) blocking shape
182188
normalized_value = []
183-
for i, block_shape in enumerate(value):
189+
for block_shape in value:
184190
# If hierarchical blocking is activated, say with N levels, here in
185191
# `bs` we expect to see 3*N entries
186192
bs = [int(x) for x in block_shape.split()]
@@ -204,7 +210,10 @@ def config_autotuning(ctx, param, value):
204210
elif value != 'off':
205211
# Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off
206212
if ctx.params['block_shape']:
207-
warning("Skipping autotuning (using explicit block-shape `{}`)".format(str(ctx.params['block_shape'])))
213+
warning(
214+
'Skipping autotuning'
215+
f'(using explicit block-shape `{str(ctx.params["block_shape"])}`)'
216+
)
208217
level = False
209218
else:
210219
# Make sure to always run in preemptive mode
@@ -272,8 +281,8 @@ def run(problem, **kwargs):
272281
# Note: the following piece of code is horribly *hacky*, but it works for now
273282
for i, block_shape in enumerate(block_shapes):
274283
for n, level in enumerate(block_shape):
275-
for d, s in zip(['x', 'y', 'z'], level):
276-
options['%s%d_blk%d_size' % (d, i, n)] = s
284+
for d, s in zip(['x', 'y', 'z'], level, strict=True):
285+
options[f'{d}{i}_blk{n}_size'] = s
277286

278287
solver = setup(space_order=space_order, time_order=time_order, **kwargs)
279288
if warmup:
@@ -345,7 +354,7 @@ def run_jit_backdoor(problem, **kwargs):
345354

346355
if not os.path.exists(cfile):
347356
# First time we run this problem, let's generate and jit-compile code
348-
op.cfunction
357+
_ = op.cfunction
349358
info(f"You may now edit the generated code in `{cfile}`. "
350359
"Then save the file, and re-run this benchmark.")
351360
return
@@ -403,9 +412,10 @@ def test(problem, **kwargs):
403412
set_log_level('DEBUG', comm=MPI.COMM_WORLD)
404413

405414
if MPI.COMM_WORLD.size > 1 and not configuration['mpi']:
406-
warning("It seems that you're running over MPI with %d processes, but "
407-
"DEVITO_MPI is unset. Setting `DEVITO_MPI=basic`..."
408-
% MPI.COMM_WORLD.size)
415+
warning(
416+
f'It seems that you are running over MPI with {MPI.COMM_WORLD.size} '
417+
'processes, but DEVITO_MPI is unset. Setting `DEVITO_MPI=basic`...'
418+
)
409419
configuration['mpi'] = 'basic'
410420
except (TypeError, ModuleNotFoundError):
411421
# MPI not available
@@ -417,8 +427,6 @@ def test(problem, **kwargs):
417427

418428
benchmark(standalone_mode=False)
419429

420-
try:
430+
# In case MPI not available
431+
with suppress(TypeError):
421432
MPI.Finalize()
422-
except TypeError:
423-
# MPI not available
424-
pass

conftest.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import sys
3+
from contextlib import suppress
34
from subprocess import check_call
45

56
import pytest
@@ -51,17 +52,18 @@ def skipif(items, whole_module=False):
5152
langs = configuration._accepted['language']
5253
if any(i == f'device-{l}' and configuration['language'] == l for l in langs)\
5354
and isinstance(configuration['platform'], Device):
54-
skipit = "language `{}` for device unsupported".format(configuration['language'])
55+
skipit = f'language `{configuration["language"]}` for device unsupported'
5556
break
5657
if any(i == f'device-{k}' and isinstance(configuration['compiler'], v)
5758
for k, v in compiler_registry.items()) and\
5859
isinstance(configuration['platform'], Device):
59-
skipit = "compiler `{}` for device unsupported".format(configuration['compiler'])
60+
skipit = f'compiler `{configuration["compiler"]}` for device unsupported'
6061
break
6162
# Skip if must run on GPUs but not currently on a GPU
6263
if i in ('nodevice', 'nodevice-omp', 'nodevice-acc') and\
6364
not isinstance(configuration['platform'], Device):
64-
skipit = ("must run on device, but currently on `{}`".format(configuration['platform'].name))
65+
skipit = 'must run on device, but currently on '
66+
skipit += f'`{configuration["platform"].name}`'
6567
break
6668
# Skip if it won't run with nvc on CPU backend
6769
if i == 'cpu64-nvc' and \
@@ -186,16 +188,11 @@ def parallel(item, m):
186188
testname = get_testname(item)
187189
# Only spew tracebacks on rank 0.
188190
# Run xfailing tests to ensure that errors are reported to calling process
189-
args = [
190-
"-n", "1", pyversion, "-m", "pytest", "-s", "--runxfail", "-v",
191-
"--timeout=600", "--timeout-method=thread", "-o faulthandler_timeout=660",
192-
testname
193-
]
191+
args = ["-n", "1", pyversion, "-m", "pytest", "-s", "--runxfail", "-qq", testname]
194192
if nprocs > 1:
195193
args.extend([
196-
":", "-n", "%d" % (nprocs - 1), pyversion, "-m", "pytest",
197-
"-s", "--runxfail", "-v", "--timeout=600", "--timeout-method=thread",
198-
"-o faulthandler_timeout=660", testname
194+
":", "-n", str(nprocs - 1), pyversion, "-m", "pytest",
195+
"-s", "--runxfail", "-v", "--no-summary", testname
199196
])
200197
# OpenMPI requires an explicit flag for oversubscription. We need it as some
201198
# of the MPI tests will spawn lots of processes
@@ -253,10 +250,8 @@ def pytest_generate_tests(metafunc):
253250
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
254251
def pytest_runtest_call(item):
255252
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
256-
try:
253+
with suppress(ValueError):
257254
inside_pytest_marker = int(inside_pytest_marker)
258-
except ValueError:
259-
pass
260255

261256
if inside_pytest_marker:
262257
outcome = yield
@@ -287,15 +282,13 @@ def pytest_runtest_makereport(item, call):
287282
result = outcome.get_result()
288283

289284
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
290-
try:
285+
with suppress(ValueError):
291286
inside_pytest_marker = int(inside_pytest_marker)
292-
except ValueError:
293-
pass
294287
if inside_pytest_marker:
295288
return
296289

297290
if item.get_closest_marker("parallel") or \
298-
item.get_closest_marker("decoupler"):
291+
item.get_closest_marker("decoupler"): # noqa: SIM102
299292
if call.when == 'call' and result.outcome == 'skipped':
300293
result.outcome = 'passed'
301294

examples/.ruff.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Extend the `pyproject.toml` file in the parent directory
2+
extend = "../pyproject.toml"
3+
4+
# Use a different line length for examples only
5+
# TODO: Shorten line lengths in examples
6+
line-length = 120

examples/cfd/01_convection.ipynb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@
109109
"# Repeat initialisation, so we can re-run the cell\n",
110110
"init_hat(field=u, dx=dx, dy=dy, value=2.)\n",
111111
"\n",
112-
"for n in range(nt + 1):\n",
112+
"for _ in range(nt + 1):\n",
113113
" # Copy previous result into a new buffer\n",
114114
" un = u.copy()\n",
115115
"\n",
@@ -122,7 +122,8 @@
122122
" u[-1, :] = 1. # right\n",
123123
" u[:, 0] = 1. # bottom\n",
124124
" u[:, -1] = 1. # top\n",
125-
" # Note that in the above expressions the NumPy index -1 corresponds to the final point of the array along the indexed dimension,\n",
125+
" # Note that in the above expressions the NumPy index -1 corresponds to the\n",
126+
" # final point of the array along the indexed dimension,\n",
126127
" # i.e. here u[-1, :] is equivalent to u[80, :].\n"
127128
]
128129
},

examples/cfd/01_convection_revisited.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@
103103
"# Repeat initialisation, so we can re-run the cell\n",
104104
"init_smooth(field=u, dx=dx, dy=dy)\n",
105105
"\n",
106-
"for n in range(nt + 1):\n",
106+
"for _ in range(nt + 1):\n",
107107
" # Copy previous result into a new buffer\n",
108108
" un = u.copy()\n",
109109
"\n",

examples/cfd/02_convection_nonlinear.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
],
111111
"source": [
112112
"# NBVAL_IGNORE_OUTPUT\n",
113-
"for n in range(nt + 1): # loop across number of time steps\n",
113+
"for _ in range(nt + 1): # loop across number of time steps\n",
114114
" un = u.copy()\n",
115115
" vn = v.copy()\n",
116116
" u[1:, 1:] = (un[1:, 1:] -\n",

examples/cfd/03_diffusion.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
"outputs": [],
5858
"source": [
5959
"def diffuse(u, nt):\n",
60-
" for n in range(nt + 1):\n",
60+
" for _ in range(nt + 1):\n",
6161
" un = u.copy()\n",
6262
" u[1:-1, 1:-1] = (un[1:-1, 1:-1] +\n",
6363
" nu * dt / dy**2 * (un[1:-1, 2:] - 2 * un[1:-1, 1:-1] + un[1:-1, 0:-2]) +\n",

examples/cfd/03_diffusion_nonuniform.ipynb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@
8080
"outputs": [],
8181
"source": [
8282
"def diffuse(u, nt, visc):\n",
83-
" for n in range(nt + 1):\n",
83+
" for _ in range(nt + 1):\n",
8484
" un = u.copy()\n",
8585
" u[1:-1, 1:-1] = (un[1:-1, 1:-1] +\n",
8686
" visc*dt / dy**2 * (un[1:-1, 2:] - 2 * un[1:-1, 1:-1] + un[1:-1, 0:-2]) +\n",
@@ -257,7 +257,6 @@
257257
],
258258
"source": [
259259
"from devito import Grid, TimeFunction, Eq, solve, Function\n",
260-
"from sympy.abc import a\n",
261260
"\n",
262261
"# Initialize `u` for space order 2\n",
263262
"grid = Grid(shape=(nx, ny), extent=(2., 2.))\n",

0 commit comments

Comments
 (0)