Skip to content

Commit aa9925a

Browse files
committed
misc: Manual linting for Devito
1 parent 35f179c commit aa9925a

Some content is hidden

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

104 files changed

+1481
-1359
lines changed

devito/arch/archinfo.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from devito.logger import warning
1919
from devito.tools import all_equal, as_tuple, memoized_func
2020

21-
__all__ = [
21+
__all__ = [ # noqa: RUF022
2222
'platform_registry', 'get_cpu_info', 'get_gpu_info', 'get_visible_devices',
2323
'get_nvidia_cc', 'get_cuda_path', 'get_cuda_version', 'get_hip_path',
2424
'check_cuda_runtime', 'get_m1_llvm_path', 'get_advisor_path', 'Platform',
@@ -391,7 +391,7 @@ def cbk(deviceid=0):
391391
return None
392392
return cbk
393393

394-
gpu_info['mem.%s' % i] = make_cbk(i)
394+
gpu_info[f'mem.{i}'] = make_cbk(i)
395395

396396
gpu_info['architecture'] = 'unspecified'
397397
gpu_info['vendor'] = 'INTEL'
@@ -780,7 +780,7 @@ def __str__(self):
780780
return self.name
781781

782782
def __repr__(self):
783-
return "TargetPlatform[%s]" % self.name
783+
return f'TargetPlatform[{self.name}]'
784784

785785
def _detect_isa(self):
786786
return 'unknown'
@@ -1141,7 +1141,7 @@ def supports(self, query, language=None):
11411141
elif query == 'async-loads' and cc >= 80:
11421142
# Asynchronous pipeline loads -- introduced in Ampere
11431143
return True
1144-
elif query in ('tma', 'thread-block-cluster') and cc >= 90:
1144+
elif query in ('tma', 'thread-block-cluster') and cc >= 90: # noqa: SIM103
11451145
# Tensor Memory Accelerator -- introduced in Hopper
11461146
return True
11471147
else:
@@ -1202,10 +1202,8 @@ def march(cls):
12021202
try:
12031203
p1 = Popen(['offload-arch'], stdout=PIPE, stderr=PIPE)
12041204
except OSError:
1205-
try:
1205+
with suppress(OSError):
12061206
p1 = Popen(['mygpu', '-d', fallback], stdout=PIPE, stderr=PIPE)
1207-
except OSError:
1208-
pass
12091207
return fallback
12101208

12111209
output, _ = p1.communicate()
@@ -1248,7 +1246,7 @@ def node_max_mem_trans_nbytes(platform):
12481246
elif isinstance(platform, Device):
12491247
return max(Cpu64.max_mem_trans_nbytes, mmtb0)
12501248
else:
1251-
assert False, f"Unknown platform type: {type(platform)}"
1249+
raise AssertionError(f"Unknown platform type: {type(platform)}")
12521250

12531251

12541252
# CPUs

devito/arch/compiler.py

Lines changed: 33 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import platform
22
import time
33
import warnings
4+
from contextlib import suppress
45
from functools import partial
56
from hashlib import sha1
67
from itertools import filterfalse
@@ -43,16 +44,20 @@ def sniff_compiler_version(cc, allow_fail=False):
4344
return Version("0")
4445
except UnicodeDecodeError:
4546
return Version("0")
46-
except OSError:
47+
except OSError as e:
4748
if allow_fail:
4849
return Version("0")
4950
else:
50-
raise RuntimeError(f"The `{cc}` compiler isn't available on this system")
51+
raise RuntimeError(
52+
f"The `{cc}` compiler isn't available on this system"
53+
) from e
5154

5255
ver = ver.strip()
5356
if ver.startswith("gcc"):
5457
compiler = "gcc"
55-
elif ver.startswith("clang") or ver.startswith("Apple LLVM") or ver.startswith("Homebrew clang"):
58+
elif ver.startswith("clang") \
59+
or ver.startswith("Apple LLVM") \
60+
or ver.startswith("Homebrew clang"):
5661
compiler = "clang"
5762
elif ver.startswith("Intel"):
5863
compiler = "icx"
@@ -92,10 +97,8 @@ def sniff_compiler_version(cc, allow_fail=False):
9297
pass
9398

9499
# Pure integer versions (e.g., ggc5, rather than gcc5.0) need special handling
95-
try:
100+
with suppress(TypeError):
96101
ver = Version(float(ver))
97-
except TypeError:
98-
pass
99102

100103
return ver
101104

@@ -335,21 +338,21 @@ def make(self, loc, args):
335338
logfile = path.join(self.get_jit_dir(), f"{hash_key}.log")
336339
errfile = path.join(self.get_jit_dir(), f"{hash_key}.err")
337340

338-
with change_directory(loc), open(logfile, "w") as lf:
339-
with open(errfile, "w") as ef:
340-
341-
command = ['make'] + args
342-
lf.write("Compilation command:\n")
343-
lf.write(" ".join(command))
344-
lf.write("\n\n")
345-
try:
346-
check_call(command, stderr=ef, stdout=lf)
347-
except CalledProcessError as e:
348-
raise CompilationError(f'Command "{e.cmd}" return error status'
349-
f'{e.returncode}. '
350-
f'Unable to compile code.\n'
351-
f'Compile log in {logfile}\n'
352-
f'Compile errors in {errfile}\n')
341+
with change_directory(loc), open(logfile, "w") as lf, open(errfile, "w") as ef:
342+
command = ['make'] + args
343+
lf.write("Compilation command:\n")
344+
lf.write(" ".join(command))
345+
lf.write("\n\n")
346+
try:
347+
check_call(command, stderr=ef, stdout=lf)
348+
except CalledProcessError as e:
349+
raise CompilationError(
350+
f'Command "{e.cmd}" return error status'
351+
f'{e.returncode}. '
352+
f'Unable to compile code.\n'
353+
f'Compile log in {logfile}\n'
354+
f'Compile errors in {errfile}\n'
355+
) from e
353356
debug(f"Make <{' '.join(args)}>")
354357

355358
def _cmdline(self, files, object=False):
@@ -395,9 +398,11 @@ def jit_compile(self, soname, code):
395398
# ranks would end up creating different cache dirs
396399
cache_dir = cache_dir.joinpath('jit-backdoor')
397400
cache_dir.mkdir(parents=True, exist_ok=True)
398-
except FileNotFoundError:
399-
raise ValueError(f"Trying to use the JIT backdoor for `{src_file}`, but "
400-
"the file isn't present")
401+
except FileNotFoundError as e:
402+
raise ValueError(
403+
f"Trying to use the JIT backdoor for `{src_file}`, but "
404+
"the file isn't present"
405+
) from e
401406

402407
# Should the compilation command be emitted?
403408
debug = configuration['log-level'] == 'DEBUG'
@@ -708,12 +713,10 @@ def __init_finalize__(self, **kwargs):
708713
# explicitly pass the flags that an `mpicc` would implicitly use
709714
compile_flags, link_flags = sniff_mpi_flags('mpicxx')
710715

711-
try:
716+
with suppress(ValueError):
712717
# No idea why `-pthread` would pop up among the `compile_flags`
718+
# Just in case they fix it, we wrap it up within a suppress
713719
compile_flags.remove('-pthread')
714-
except ValueError:
715-
# Just in case they fix it, we wrap it up within a try-except
716-
pass
717720
self.cflags.extend(compile_flags)
718721

719722
# Some arguments are for the host compiler
@@ -1005,15 +1008,9 @@ def __new__(cls, *args, **kwargs):
10051008
elif isinstance(platform, IntelDevice):
10061009
_base = OneapiCompiler
10071010
elif isinstance(platform, NvidiaDevice):
1008-
if language == 'cuda':
1009-
_base = CudaCompiler
1010-
else:
1011-
_base = NvidiaCompiler
1011+
_base = CudaCompiler if language == 'cuda' else NvidiaCompiler
10121012
elif platform is AMDGPUX:
1013-
if language == 'hip':
1014-
_base = HipCompiler
1015-
else:
1016-
_base = AOMPCompiler
1013+
_base = HipCompiler if language == 'hip' else AOMPCompiler
10171014
else:
10181015
_base = GNUCompiler
10191016

devito/builtins/arithmetic.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def norm(f, order=2):
3333

3434
op = dv.Operator([dv.Eq(s, 0.0)] + eqns +
3535
[dv.Inc(s, Pow(dv.Abs(p), order)), dv.Eq(n[0], s)],
36-
name='norm%d' % order)
36+
name=f'norm{order}')
3737
op.apply(**kwargs)
3838

3939
v = np.power(n.data[0], 1/order)
@@ -63,24 +63,24 @@ def sum(f, dims=None):
6363
new_dims = tuple(d for d in f.dimensions if d not in dims)
6464
shape = tuple(f._size_domain[d] for d in new_dims)
6565
if f.is_TimeFunction and f.time_dim not in dims:
66-
out = f._rebuild(name="%ssum" % f.name, shape=shape, dimensions=new_dims,
66+
out = f._rebuild(name=f'{f.name}sum', shape=shape, dimensions=new_dims,
6767
initializer=np.empty(0))
6868
elif f.is_SparseTimeFunction:
6969
if f.time_dim in dims:
7070
# Sum over time -> SparseFunction
7171
new_coords = f.coordinates._rebuild(
72-
name="%ssum_coords" % f.name, initializer=f.coordinates.initializer
72+
name=f'{f.name}sum_coords', initializer=f.coordinates.initializer
7373
)
74-
out = dv.SparseFunction(name="%ssum" % f.name, grid=f.grid,
74+
out = dv.SparseFunction(name=f'{f.name}sum', grid=f.grid,
7575
dimensions=new_dims, npoint=f.shape[1],
7676
coordinates=new_coords)
7777
else:
7878
# Sum over rec -> TimeFunction
79-
out = dv.TimeFunction(name="%ssum" % f.name, grid=f.grid, shape=shape,
79+
out = dv.TimeFunction(name=f'{f.name}sum', grid=f.grid, shape=shape,
8080
dimensions=new_dims, space_order=0,
8181
time_order=f.time_order)
8282
else:
83-
out = dv.Function(name="%ssum" % f.name, grid=f.grid,
83+
out = dv.Function(name=f'{f.name}sum', grid=f.grid,
8484
space_order=f.space_order, shape=shape,
8585
dimensions=new_dims)
8686

@@ -217,4 +217,4 @@ def _reduce_func(f, func, mfunc):
217217
else:
218218
return v.item()
219219
else:
220-
raise ValueError("Expected Function, got `%s`" % type(f))
220+
raise ValueError(f'Expected Function, got `{type(f)}`')

devito/builtins/initializers.py

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -59,18 +59,18 @@ def assign(f, rhs=0, options=None, name='assign', assign_halo=False, **kwargs):
5959

6060
eqs = []
6161
if options:
62-
for i, j, k in zip(as_list(f), rhs, options):
62+
for i, j, k in zip(as_list(f), rhs, options, strict=True):
6363
if k is not None:
6464
eqs.append(dv.Eq(i, j, **k))
6565
else:
6666
eqs.append(dv.Eq(i, j))
6767
else:
68-
for i, j in zip(as_list(f), rhs):
68+
for i, j in zip(as_list(f), rhs, strict=True):
6969
eqs.append(dv.Eq(i, j))
7070

7171
if assign_halo:
7272
subs = {}
73-
for d, h in zip(f.dimensions, f._size_halo):
73+
for d, h in zip(f.dimensions, f._size_halo, strict=True):
7474
if sum(h) == 0:
7575
continue
7676
subs[d] = dv.CustomDimension(name=d.name, parent=d,
@@ -143,15 +143,15 @@ def __init__(self, lw):
143143
self.lw = lw
144144

145145
def define(self, dimensions):
146-
return {d: ('middle', l, l) for d, l in zip(dimensions, self.lw)}
146+
return {d: ('middle', l, l) for d, l in zip(dimensions, self.lw, strict=True)}
147147

148148
def create_gaussian_weights(sigma, lw):
149149
weights = [w/w.sum() for w in (np.exp(-0.5/s**2*(np.linspace(-l, l, 2*l+1))**2)
150-
for s, l in zip(sigma, lw))]
150+
for s, l in zip(sigma, lw, strict=True))]
151151
return as_tuple(np.array(w) for w in weights)
152152

153153
def fset(f, g):
154-
indices = [slice(l, -l, 1) for _, l in zip(g.dimensions, lw)]
154+
indices = [slice(l, -l, 1) for _, l in zip(g.dimensions, lw, strict=True)]
155155
slices = (slice(None, None, 1), )*g.ndim
156156
if isinstance(f, np.ndarray):
157157
f[slices] = g.data[tuple(indices)]
@@ -182,7 +182,7 @@ def fset(f, g):
182182

183183
# Create the padded grid:
184184
objective_domain = ObjectiveDomain(lw)
185-
shape_padded = tuple([np.array(s) + 2*l for s, l in zip(shape, lw)])
185+
shape_padded = tuple([np.array(s) + 2*l for s, l in zip(shape, lw, strict=True)])
186186
extent_padded = tuple([s-1 for s in shape_padded])
187187
grid = dv.Grid(shape=shape_padded, subdomains=objective_domain,
188188
extent=extent_padded)
@@ -193,7 +193,7 @@ def fset(f, g):
193193
weights = create_gaussian_weights(sigma, lw)
194194

195195
mapper = {}
196-
for d, l, w in zip(f_c.dimensions, lw, weights):
196+
for d, l, w in zip(f_c.dimensions, lw, weights, strict=True):
197197
lhs = []
198198
rhs = []
199199
options = []
@@ -238,13 +238,15 @@ def _initialize_function(function, data, nbl, mapper=None, mode='constant'):
238238
def buff(i, j):
239239
return [(i + k - 2*max(max(nbl))) for k in j]
240240

241-
b = [min(l) for l in (w for w in (buff(i, j) for i, j in zip(local_size, halo)))]
241+
b = [min(l) for l in (
242+
w for w in (buff(i, j) for i, j in zip(local_size, halo, strict=True))
243+
)]
242244
if any(np.array(b) < 0):
243-
raise ValueError("Function `%s` halo is not sufficiently thick." % function)
245+
raise ValueError(f'Function `{function}` halo is not sufficiently thick.')
244246

245-
for d, (nl, nr) in zip(function.space_dimensions, as_tuple(nbl)):
246-
dim_l = dv.SubDimension.left(name='abc_%s_l' % d.name, parent=d, thickness=nl)
247-
dim_r = dv.SubDimension.right(name='abc_%s_r' % d.name, parent=d, thickness=nr)
247+
for d, (nl, nr) in zip(function.space_dimensions, as_tuple(nbl), strict=True):
248+
dim_l = dv.SubDimension.left(name=f'abc_{d.name}_l', parent=d, thickness=nl)
249+
dim_r = dv.SubDimension.right(name=f'abc_{d.name}_r', parent=d, thickness=nr)
248250
if mode == 'constant':
249251
subsl = nl
250252
subsr = d.symbolic_max - nr
@@ -259,7 +261,7 @@ def buff(i, j):
259261
rhs.append(function.subs({d: subsr}))
260262
options.extend([None, None])
261263

262-
if mapper and d in mapper.keys():
264+
if mapper and d in mapper:
263265
exprs = mapper[d]
264266
lhs_extra = exprs['lhs']
265267
rhs_extra = exprs['rhs']
@@ -353,8 +355,9 @@ def initialize_function(function, data, nbl, mapper=None, mode='constant',
353355
if not isinstance(data, (list, tuple)):
354356
raise TypeError("Expected a list of `data`")
355357
elif len(function) != len(data):
356-
raise ValueError("Expected %d `data` items, got %d" %
357-
(len(function), len(data)))
358+
raise ValueError(
359+
f'Expected {len(function)} `data` items, got {len(data)}'
360+
)
358361

359362
if mapper is not None:
360363
raise NotImplementedError("Unsupported `mapper` with batching")
@@ -374,14 +377,14 @@ def initialize_function(function, data, nbl, mapper=None, mode='constant',
374377
f._create_data()
375378

376379
if nbl == 0:
377-
for f, data in zip(functions, datas):
380+
for f, data in zip(functions, datas, strict=True):
378381
if isinstance(data, dv.Function):
379382
f.data[:] = data.data[:]
380383
else:
381384
f.data[:] = data[:]
382385
else:
383386
lhss, rhss, optionss = [], [], []
384-
for f, data in zip(functions, datas):
387+
for f, data in zip(functions, datas, strict=True):
385388

386389
lhs, rhs, options = _initialize_function(f, data, nbl, mapper, mode)
387390

@@ -391,7 +394,7 @@ def initialize_function(function, data, nbl, mapper=None, mode='constant',
391394

392395
assert len(lhss) == len(rhss) == len(optionss)
393396

394-
name = name or 'initialize_%s' % '_'.join(f.name for f in functions)
397+
name = name or f'initialize_{"_".join(f.name for f in functions)}'
395398
assign(lhss, rhss, options=optionss, name=name, **kwargs)
396399

397400
if pad_halo:

0 commit comments

Comments
 (0)