Skip to content

Commit c91949e

Browse files
authored
Merge pull request #2814 from devitocodes/JDBetteridge/ruff_manual_changes_part2
misc: ruff manual changes part2
2 parents 74243a7 + 540a43f commit c91949e

218 files changed

Lines changed: 4424 additions & 3794 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.

.pre-commit-config.yaml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,18 @@ repos:
1313
hooks:
1414
# Run isort to check only (don't modify files)
1515
- id: isort
16-
args: [ --check-only ]
16+
args: [--check-only, --filter-files]
1717
- repo: https://github.com/astral-sh/ruff-pre-commit
1818
# Ruff version.
1919
rev: v0.14.4
2020
hooks:
2121
# Run the linter to check only (don't modify files)
2222
- id: ruff-check
23+
- repo: https://github.com/PyCQA/flake8
24+
rev: 7.3.0
25+
hooks:
26+
- id: flake8
27+
additional_dependencies: [flake8-pyproject]
2328
- repo: https://github.com/crate-ci/typos
2429
rev: v1.39.1
2530
hooks:

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/advisor_logging.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,18 @@ def check(cond, msg):
99

1010

1111
def err(msg):
12-
print('\033[1;37;31m%s\033[0m' % msg) # print in RED
12+
print(f'\033[1;37;31m{msg}\033[0m') # print in RED
1313

1414

1515
def log(msg):
16-
print('\033[1;37;32m%s\033[0m' % msg) # print in GREEN
16+
print(f'\033[1;37;32m{msg}\033[0m') # print in GREEN
1717

1818

1919
@contextmanager
2020
def progress(msg):
21-
print('\033[1;37;32m%s ... \033[0m' % msg, end='', flush=True) # print in GREEN
21+
print(f'\033[1;37;32m{msg} ... \033[0m', end='', flush=True) # print in GREEN
2222
yield
23-
print('\033[1;37;32m%s\033[0m' % 'Done!')
23+
print('\033[1;37;32m{}\033[0m'.format('Done!'))
2424

2525

2626
def log_process(process, logger):

benchmarks/user/advisor/roofline.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def roofline(name, project, scale, precision, mode, th):
205205
log(f'\nFigure saved in {figpath}{name}.pdf.')
206206

207207
# Save the JSON file
208-
with open('%s.json' % name, 'w') as f:
208+
with open(f'{name}.json', 'w') as f:
209209
f.write(json.dumps(roofline_data))
210210

211211
log(f'\nJSON file saved as {name}.json.')

benchmarks/user/advisor/run_advisor.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -132,17 +132,16 @@ def run_with_advisor(path, output, name, exec_args):
132132
# Before collecting the `survey` and `tripcounts` a "pure" python run
133133
# to warmup the jit cache is preceded
134134

135-
log('Starting Intel Advisor\'s `roofline` analysis for `%s`' % name)
135+
log(f'Starting Intel Advisor\'s `roofline` analysis for `{name}`')
136136
dt = datetime.datetime.now()
137137

138138
# Set up a file logger that will track the output of the advisor profiling
139139
advixe_logger = logging.getLogger('run_advisor_logger')
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)
145-
advixe_handler = logging.FileHandler('%s/%s_%s.log' % (output, name, logger_datetime))
143+
logger_datetime = f'{dt.year}.{dt.month}.{dt.day}.{dt.hour}.{dt.minute}.{dt.second}'
144+
advixe_handler = logging.FileHandler(f'{output}/{name}_{logger_datetime}.log')
146145
advixe_handler.setFormatter(advixe_formatter)
147146
advixe_logger.addHandler(advixe_handler)
148147

benchmarks/user/benchmark.py

Lines changed: 34 additions & 28 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("Operator %s not implemented for %s" % (operator, 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":
@@ -95,7 +98,7 @@ def run_op(solver, operator, **options):
9598
args = args[:-1]
9699
return op(*args, **options)
97100
else:
98-
raise ValueError("Unrecognized operator %s" % operator)
101+
raise ValueError(f"Unrecognized operator {operator}")
99102

100103

101104
@click.group()
@@ -157,15 +160,17 @@ def from_opt(ctx, param, value):
157160
# E.g., `('advanced', {'par-tile': True})`
158161
value = eval(value)
159162
if not isinstance(value, tuple) and len(value) >= 1:
160-
raise click.BadParameter("Invalid choice `%s` (`opt` must be "
161-
"either str or tuple)" % str(value))
163+
raise click.BadParameter(f"Invalid choice `{str(value)}` (`opt` must be "
164+
"either str or tuple)")
162165
opt = value[0]
163166
except NameError:
164167
# E.g. `'advanced'`
165168
opt = value
166169
if opt not in configuration._accepted['opt']:
167-
raise click.BadParameter("Invalid choice `%s` (choose from %s)"
168-
% (opt, str(configuration._accepted['opt'])))
170+
raise click.BadParameter(
171+
f'Invalid choice `{opt} '
172+
f'(choose from {str(configuration._accepted["opt"])})'
173+
)
169174
return value
170175

171176
def config_blockshape(ctx, param, value):
@@ -181,18 +186,18 @@ def config_blockshape(ctx, param, value):
181186
# 1. integers, not strings
182187
# 2. sanity check the (hierarchical) blocking shape
183188
normalized_value = []
184-
for i, block_shape in enumerate(value):
189+
for block_shape in value:
185190
# If hierarchical blocking is activated, say with N levels, here in
186191
# `bs` we expect to see 3*N entries
187192
bs = [int(x) for x in block_shape.split()]
188193
levels = [bs[x:x+3] for x in range(0, len(bs), 3)]
189194
if any(len(level) != 3 for level in levels):
190195
raise ValueError("Expected 3 entries per block shape level, but got "
191-
"one level with less than 3 entries (`%s`)" % levels)
196+
f"one level with less than 3 entries (`{levels}`)")
192197
normalized_value.append(levels)
193198
if not all_equal(len(i) for i in normalized_value):
194199
raise ValueError("Found different block shapes with incompatible "
195-
"number of levels (`%s`)" % normalized_value)
200+
f"number of levels (`{normalized_value}`)")
196201
configuration['opt-options']['blocklevels'] = len(normalized_value[0])
197202
else:
198203
normalized_value = []
@@ -205,8 +210,10 @@ def config_autotuning(ctx, param, value):
205210
elif value != 'off':
206211
# Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off
207212
if ctx.params['block_shape']:
208-
warning("Skipping autotuning (using explicit block-shape `%s`)"
209-
% str(ctx.params['block_shape']))
213+
warning(
214+
'Skipping autotuning'
215+
f'(using explicit block-shape `{str(ctx.params["block_shape"])}`)'
216+
)
210217
level = False
211218
else:
212219
# Make sure to always run in preemptive mode
@@ -274,8 +281,8 @@ def run(problem, **kwargs):
274281
# Note: the following piece of code is horribly *hacky*, but it works for now
275282
for i, block_shape in enumerate(block_shapes):
276283
for n, level in enumerate(block_shape):
277-
for d, s in zip(['x', 'y', 'z'], level):
278-
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
279286

280287
solver = setup(space_order=space_order, time_order=time_order, **kwargs)
281288
if warmup:
@@ -305,11 +312,11 @@ def run(problem, **kwargs):
305312

306313
dumpfile = kwargs.pop('dump_norms')
307314
if dumpfile:
308-
norms = ["'%s': %f" % (i.name, norm(i)) for i in retval[:-1]
315+
norms = [f"'{i.name}': {norm(i):f}" for i in retval[:-1]
309316
if isinstance(i, DiscreteFunction)]
310317
if rank == 0:
311318
with open(dumpfile, 'w') as f:
312-
f.write("{%s}" % ', '.join(norms))
319+
f.write("{{{}}}".format(', '.join(norms)))
313320

314321
return retval
315322

@@ -343,13 +350,13 @@ def run_jit_backdoor(problem, **kwargs):
343350
op = solver.op_fwd()
344351

345352
# Get the filename in the JIT cache
346-
cfile = "%s.c" % str(op._compiler.get_jit_dir().joinpath(op._soname))
353+
cfile = f"{str(op._compiler.get_jit_dir().joinpath(op._soname))}.c"
347354

348355
if not os.path.exists(cfile):
349356
# First time we run this problem, let's generate and jit-compile code
350-
op.cfunction
351-
info("You may now edit the generated code in `%s`. "
352-
"Then save the file, and re-run this benchmark." % cfile)
357+
_ = op.cfunction
358+
info(f"You may now edit the generated code in `{cfile}`. "
359+
"Then save the file, and re-run this benchmark.")
353360
return
354361

355362
info("Running wave propagation Operator...")
@@ -364,7 +371,7 @@ def _run_jit_backdoor():
364371
if dumpnorms:
365372
for i in retval[:-1]:
366373
if isinstance(i, DiscreteFunction):
367-
info("'%s': %f" % (i.name, norm(i)))
374+
info(f"'{i.name}': {norm(i):f}")
368375

369376
return retval
370377

@@ -405,9 +412,10 @@ def test(problem, **kwargs):
405412
set_log_level('DEBUG', comm=MPI.COMM_WORLD)
406413

407414
if MPI.COMM_WORLD.size > 1 and not configuration['mpi']:
408-
warning("It seems that you're running over MPI with %d processes, but "
409-
"DEVITO_MPI is unset. Setting `DEVITO_MPI=basic`..."
410-
% 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+
)
411419
configuration['mpi'] = 'basic'
412420
except (TypeError, ModuleNotFoundError):
413421
# MPI not available
@@ -419,8 +427,6 @@ def test(problem, **kwargs):
419427

420428
benchmark(standalone_mode=False)
421429

422-
try:
430+
# In case MPI not available
431+
with suppress(TypeError):
423432
MPI.Finalize()
424-
except TypeError:
425-
# MPI not available
426-
pass

conftest.py

Lines changed: 19 additions & 20 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
@@ -40,29 +41,29 @@ def skipif(items, whole_module=False):
4041
accepted.update({'nodevice', 'noomp'})
4142
unknown = sorted(set(items) - accepted)
4243
if unknown:
43-
raise ValueError("Illegal skipif argument(s) `%s`" % unknown)
44+
raise ValueError(f"Illegal skipif argument(s) `{unknown}`")
4445
skipit = False
4546
for i in items:
4647
# Skip if won't run on GPUs
4748
if i == 'device' and isinstance(configuration['platform'], Device):
48-
skipit = "device `%s` unsupported" % configuration['platform'].name
49+
skipit = "device `{}` unsupported".format(configuration['platform'].name)
4950
break
5051
# Skip if won't run on a specific GPU backend
5152
langs = configuration._accepted['language']
52-
if any(i == 'device-%s' % l and configuration['language'] == l for l in langs)\
53+
if any(i == f'device-{l}' and configuration['language'] == l for l in langs)\
5354
and isinstance(configuration['platform'], Device):
54-
skipit = "language `%s` for device unsupported" % configuration['language']
55+
skipit = f'language `{configuration["language"]}` for device unsupported'
5556
break
56-
if any(i == 'device-%s' % k and isinstance(configuration['compiler'], v)
57+
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 `%s` for device unsupported" % 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 `%s`" %
65-
configuration['platform'].name)
65+
skipit = 'must run on device, but currently on '
66+
skipit += f'`{configuration["platform"].name}`'
6667
break
6768
# Skip if it won't run with nvc on CPU backend
6869
if i == 'cpu64-nvc' and \
@@ -137,9 +138,9 @@ def EVAL(exprs, *args):
137138

138139
def get_testname(item):
139140
if item.cls is not None:
140-
return "%s::%s::%s" % (item.fspath, item.cls.__name__, item.name)
141+
return f"{item.fspath}::{item.cls.__name__}::{item.name}"
141142
else:
142-
return "%s::%s" % (item.fspath, item.name)
143+
return f"{item.fspath}::{item.name}"
143144

144145

145146
def set_run_reset(env_vars, call):
@@ -179,7 +180,7 @@ def parallel(item, m):
179180
if len(m) == 2:
180181
nprocs, scheme = m
181182
else:
182-
raise ValueError("Can't run test: unexpected mode `%s`" % m)
183+
raise ValueError(f"Can't run test: unexpected mode `{m}`")
183184

184185
env_vars = {'DEVITO_MPI': scheme}
185186

@@ -189,8 +190,10 @@ def parallel(item, m):
189190
# Run xfailing tests to ensure that errors are reported to calling process
190191
args = ["-n", "1", pyversion, "-m", "pytest", "-s", "--runxfail", "-qq", testname]
191192
if nprocs > 1:
192-
args.extend([":", "-n", "%d" % (nprocs - 1), pyversion, "-m", "pytest",
193-
"-s", "--runxfail", "--tb=no", "-qq", "--no-summary", testname])
193+
args.extend([
194+
":", "-n", str(nprocs - 1), pyversion, "-m", "pytest",
195+
"-s", "--runxfail", "-v", "--no-summary", testname
196+
])
194197
# OpenMPI requires an explicit flag for oversubscription. We need it as some
195198
# of the MPI tests will spawn lots of processes
196199
if mpi_distro == 'OpenMPI':
@@ -247,10 +250,8 @@ def pytest_generate_tests(metafunc):
247250
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
248251
def pytest_runtest_call(item):
249252
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
250-
try:
253+
with suppress(ValueError):
251254
inside_pytest_marker = int(inside_pytest_marker)
252-
except ValueError:
253-
pass
254255

255256
if inside_pytest_marker:
256257
outcome = yield
@@ -281,15 +282,13 @@ def pytest_runtest_makereport(item, call):
281282
result = outcome.get_result()
282283

283284
inside_pytest_marker = os.environ.get('DEVITO_PYTEST_FLAG', 0)
284-
try:
285+
with suppress(ValueError):
285286
inside_pytest_marker = int(inside_pytest_marker)
286-
except ValueError:
287-
pass
288287
if inside_pytest_marker:
289288
return
290289

291290
if item.get_closest_marker("parallel") or \
292-
item.get_closest_marker("decoupler"):
291+
item.get_closest_marker("decoupler"): # noqa: SIM102
293292
if call.when == 'call' and result.outcome == 'skipped':
294293
result.outcome = 'passed'
295294

0 commit comments

Comments
 (0)