Skip to content

Commit 5306fb9

Browse files
committed
misc: Automated linting fixes in examples, tests, scripts
1 parent fab89c8 commit 5306fb9

83 files changed

Lines changed: 1824 additions & 1760 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/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: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ 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
@@ -142,7 +142,7 @@ def run_with_advisor(path, output, name, exec_args):
142142
advixe_formatter = logging.Formatter('%(asctime)s: %(message)s')
143143
logger_datetime = '%d.%d.%d.%d.%d.%d' % (dt.year, dt.month,
144144
dt.day, dt.hour, dt.minute, dt.second)
145-
advixe_handler = logging.FileHandler('%s/%s_%s.log' % (output, name, logger_datetime))
145+
advixe_handler = logging.FileHandler(f'{output}/{name}_{logger_datetime}.log')
146146
advixe_handler.setFormatter(advixe_formatter)
147147
advixe_logger.addHandler(advixe_handler)
148148

benchmarks/user/benchmark.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def run_op(solver, operator, **options):
7474
try:
7575
op = getattr(solver, operator)
7676
except AttributeError:
77-
raise AttributeError("Operator %s not implemented for %s" % (operator, solver))
77+
raise AttributeError(f"Operator {operator} not implemented for {solver}")
7878

7979
# This is a bit ugly but not sure how to make clean input creation for different op
8080
if operator == "forward":
@@ -95,7 +95,7 @@ def run_op(solver, operator, **options):
9595
args = args[:-1]
9696
return op(*args, **options)
9797
else:
98-
raise ValueError("Unrecognized operator %s" % operator)
98+
raise ValueError(f"Unrecognized operator {operator}")
9999

100100

101101
@click.group()
@@ -157,15 +157,14 @@ def from_opt(ctx, param, value):
157157
# E.g., `('advanced', {'par-tile': True})`
158158
value = eval(value)
159159
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))
160+
raise click.BadParameter(f"Invalid choice `{str(value)}` (`opt` must be "
161+
"either str or tuple)")
162162
opt = value[0]
163163
except NameError:
164164
# E.g. `'advanced'`
165165
opt = value
166166
if opt not in configuration._accepted['opt']:
167-
raise click.BadParameter("Invalid choice `%s` (choose from %s)"
168-
% (opt, str(configuration._accepted['opt'])))
167+
raise click.BadParameter("Invalid choice `{}` (choose from {})".format(opt, str(configuration._accepted['opt'])))
169168
return value
170169

171170
def config_blockshape(ctx, param, value):
@@ -188,11 +187,11 @@ def config_blockshape(ctx, param, value):
188187
levels = [bs[x:x+3] for x in range(0, len(bs), 3)]
189188
if any(len(level) != 3 for level in levels):
190189
raise ValueError("Expected 3 entries per block shape level, but got "
191-
"one level with less than 3 entries (`%s`)" % levels)
190+
f"one level with less than 3 entries (`{levels}`)")
192191
normalized_value.append(levels)
193192
if not all_equal(len(i) for i in normalized_value):
194193
raise ValueError("Found different block shapes with incompatible "
195-
"number of levels (`%s`)" % normalized_value)
194+
f"number of levels (`{normalized_value}`)")
196195
configuration['opt-options']['blocklevels'] = len(normalized_value[0])
197196
else:
198197
normalized_value = []
@@ -205,8 +204,7 @@ def config_autotuning(ctx, param, value):
205204
elif value != 'off':
206205
# Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off
207206
if ctx.params['block_shape']:
208-
warning("Skipping autotuning (using explicit block-shape `%s`)"
209-
% str(ctx.params['block_shape']))
207+
warning("Skipping autotuning (using explicit block-shape `{}`)".format(str(ctx.params['block_shape'])))
210208
level = False
211209
else:
212210
# Make sure to always run in preemptive mode
@@ -305,11 +303,11 @@ def run(problem, **kwargs):
305303

306304
dumpfile = kwargs.pop('dump_norms')
307305
if dumpfile:
308-
norms = ["'%s': %f" % (i.name, norm(i)) for i in retval[:-1]
306+
norms = [f"'{i.name}': {norm(i):f}" for i in retval[:-1]
309307
if isinstance(i, DiscreteFunction)]
310308
if rank == 0:
311309
with open(dumpfile, 'w') as f:
312-
f.write("{%s}" % ', '.join(norms))
310+
f.write("{{{}}}".format(', '.join(norms)))
313311

314312
return retval
315313

@@ -343,13 +341,13 @@ def run_jit_backdoor(problem, **kwargs):
343341
op = solver.op_fwd()
344342

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

348346
if not os.path.exists(cfile):
349347
# First time we run this problem, let's generate and jit-compile code
350348
op.cfunction
351-
info("You may now edit the generated code in `%s`. "
352-
"Then save the file, and re-run this benchmark." % cfile)
349+
info(f"You may now edit the generated code in `{cfile}`. "
350+
"Then save the file, and re-run this benchmark.")
353351
return
354352

355353
info("Running wave propagation Operator...")
@@ -364,7 +362,7 @@ def _run_jit_backdoor():
364362
if dumpnorms:
365363
for i in retval[:-1]:
366364
if isinstance(i, DiscreteFunction):
367-
info("'%s': %f" % (i.name, norm(i)))
365+
info(f"'{i.name}': {norm(i):f}")
368366

369367
return retval
370368

conftest.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,29 +40,28 @@ def skipif(items, whole_module=False):
4040
accepted.update({'nodevice', 'noomp'})
4141
unknown = sorted(set(items) - accepted)
4242
if unknown:
43-
raise ValueError("Illegal skipif argument(s) `%s`" % unknown)
43+
raise ValueError(f"Illegal skipif argument(s) `{unknown}`")
4444
skipit = False
4545
for i in items:
4646
# Skip if won't run on GPUs
4747
if i == 'device' and isinstance(configuration['platform'], Device):
48-
skipit = "device `%s` unsupported" % configuration['platform'].name
48+
skipit = "device `{}` unsupported".format(configuration['platform'].name)
4949
break
5050
# Skip if won't run on a specific GPU backend
5151
langs = configuration._accepted['language']
52-
if any(i == 'device-%s' % l and configuration['language'] == l for l in langs)\
52+
if any(i == f'device-{l}' and configuration['language'] == l for l in langs)\
5353
and isinstance(configuration['platform'], Device):
54-
skipit = "language `%s` for device unsupported" % configuration['language']
54+
skipit = "language `{}` for device unsupported".format(configuration['language'])
5555
break
56-
if any(i == 'device-%s' % k and isinstance(configuration['compiler'], v)
56+
if any(i == f'device-{k}' and isinstance(configuration['compiler'], v)
5757
for k, v in compiler_registry.items()) and\
5858
isinstance(configuration['platform'], Device):
59-
skipit = "compiler `%s` for device unsupported" % configuration['compiler']
59+
skipit = "compiler `{}` for device unsupported".format(configuration['compiler'])
6060
break
6161
# Skip if must run on GPUs but not currently on a GPU
6262
if i in ('nodevice', 'nodevice-omp', 'nodevice-acc') and\
6363
not isinstance(configuration['platform'], Device):
64-
skipit = ("must run on device, but currently on `%s`" %
65-
configuration['platform'].name)
64+
skipit = ("must run on device, but currently on `{}`".format(configuration['platform'].name))
6665
break
6766
# Skip if it won't run with nvc on CPU backend
6867
if i == 'cpu64-nvc' and \
@@ -137,9 +136,9 @@ def EVAL(exprs, *args):
137136

138137
def get_testname(item):
139138
if item.cls is not None:
140-
return "%s::%s::%s" % (item.fspath, item.cls.__name__, item.name)
139+
return f"{item.fspath}::{item.cls.__name__}::{item.name}"
141140
else:
142-
return "%s::%s" % (item.fspath, item.name)
141+
return f"{item.fspath}::{item.name}"
143142

144143

145144
def set_run_reset(env_vars, call):
@@ -179,7 +178,7 @@ def parallel(item, m):
179178
if len(m) == 2:
180179
nprocs, scheme = m
181180
else:
182-
raise ValueError("Can't run test: unexpected mode `%s`" % m)
181+
raise ValueError(f"Can't run test: unexpected mode `{m}`")
183182

184183
env_vars = {'DEVITO_MPI': scheme}
185184

examples/cfd/01_convection.ipynb

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
"c = 1.\n",
5353
"dx = 2. / (nx - 1)\n",
5454
"dy = 2. / (ny - 1)\n",
55-
"print(\"dx %s, dy %s\" % (dx, dy))\n",
55+
"print(f\"dx {dx}, dy {dy}\")\n",
5656
"sigma = .2\n",
5757
"dt = sigma * dx"
5858
]
@@ -83,7 +83,7 @@
8383
}
8484
],
8585
"source": [
86-
"#NBVAL_IGNORE_OUTPUT\n",
86+
"# NBVAL_IGNORE_OUTPUT\n",
8787
"\n",
8888
"# Create field and assign initial conditions\n",
8989
"u = np.empty((nx, ny))\n",
@@ -119,9 +119,9 @@
119119
"\n",
120120
" # Apply boundary conditions.\n",
121121
" u[0, :] = 1. # left\n",
122-
" u[-1, :] = 1. # right\n",
122+
" u[-1, :] = 1. # right\n",
123123
" u[:, 0] = 1. # bottom\n",
124-
" u[:, -1] = 1. # top\n",
124+
" u[:, -1] = 1. # top\n",
125125
" # Note that in the above expressions the NumPy index -1 corresponds to the final point of the array along the indexed dimension,\n",
126126
" # i.e. here u[-1, :] is equivalent to u[80, :].\n"
127127
]
@@ -143,7 +143,7 @@
143143
}
144144
],
145145
"source": [
146-
"#NBVAL_IGNORE_OUTPUT\n",
146+
"# NBVAL_IGNORE_OUTPUT\n",
147147
"\n",
148148
"# A small sanity check for auto-testing\n",
149149
"assert (u[45:55, 45:55] > 1.8).all()\n",
@@ -193,7 +193,7 @@
193193
}
194194
],
195195
"source": [
196-
"#NBVAL_IGNORE_OUTPUT\n",
196+
"# NBVAL_IGNORE_OUTPUT\n",
197197
"from devito import Grid, TimeFunction\n",
198198
"\n",
199199
"grid = Grid(shape=(nx, ny), extent=(2., 2.))\n",
@@ -302,7 +302,7 @@
302302
}
303303
],
304304
"source": [
305-
"#NBVAL_IGNORE_OUTPUT\n",
305+
"# NBVAL_IGNORE_OUTPUT\n",
306306
"from devito import Operator\n",
307307
"\n",
308308
"# Reset our initial condition in both buffers.\n",
@@ -364,7 +364,7 @@
364364
}
365365
],
366366
"source": [
367-
"#NBVAL_IGNORE_OUTPUT\n",
367+
"# NBVAL_IGNORE_OUTPUT\n",
368368
"\n",
369369
"# Reset our data field and ICs in both buffers\n",
370370
"init_hat(field=u.data[0], dx=dx, dy=dy, value=2.)\n",

examples/cfd/01_convection_revisited.ipynb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
}
7878
],
7979
"source": [
80-
"#NBVAL_IGNORE_OUTPUT\n",
80+
"# NBVAL_IGNORE_OUTPUT\n",
8181
"\n",
8282
"# Create field and assign initial conditions\n",
8383
"u = np.empty((nx, ny))\n",
@@ -114,9 +114,9 @@
114114
" # Apply boundary conditions.\n",
115115
" # Note: -1 here is the last index in the array, not the one at x=-1 or y=-1.\n",
116116
" u[0, :] = 1. # left\n",
117-
" u[-1, :] = 1. # right\n",
117+
" u[-1, :] = 1. # right\n",
118118
" u[:, 0] = 1. # bottom\n",
119-
" u[:, -1] = 1. # top"
119+
" u[:, -1] = 1. # top"
120120
]
121121
},
122122
{
@@ -136,7 +136,7 @@
136136
}
137137
],
138138
"source": [
139-
"#NBVAL_IGNORE_OUTPUT\n",
139+
"# NBVAL_IGNORE_OUTPUT\n",
140140
"\n",
141141
"# A small sanity check for auto-testing\n",
142142
"assert (u[45:55, 45:55] > 1.8).all()\n",
@@ -177,7 +177,7 @@
177177
}
178178
],
179179
"source": [
180-
"#NBVAL_IGNORE_OUTPUT\n",
180+
"# NBVAL_IGNORE_OUTPUT\n",
181181
"from devito import Grid, TimeFunction\n",
182182
"\n",
183183
"grid = Grid(shape=(nx, ny), extent=(2., 2.))\n",
@@ -277,7 +277,7 @@
277277
}
278278
],
279279
"source": [
280-
"#NBVAL_IGNORE_OUTPUT\n",
280+
"# NBVAL_IGNORE_OUTPUT\n",
281281
"from devito import Operator\n",
282282
"\n",
283283
"# Reset our initial condition in both buffers.\n",
@@ -339,7 +339,7 @@
339339
}
340340
],
341341
"source": [
342-
"#NBVAL_IGNORE_OUTPUT\n",
342+
"# NBVAL_IGNORE_OUTPUT\n",
343343
"\n",
344344
"# Reset our data field and ICs in both buffers\n",
345345
"init_smooth(field=u.data[0], dx=dx, dy=dy)\n",

examples/cfd/02_convection_nonlinear.ipynb

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
}
7474
],
7575
"source": [
76-
"#NBVAL_IGNORE_OUTPUT\n",
76+
"# NBVAL_IGNORE_OUTPUT\n",
7777
"\n",
7878
"# Allocate fields and assign initial conditions\n",
7979
"u = np.empty((nx, ny))\n",
@@ -109,8 +109,8 @@
109109
}
110110
],
111111
"source": [
112-
"#NBVAL_IGNORE_OUTPUT\n",
113-
"for n in range(nt + 1): ##loop across number of time steps\n",
112+
"# NBVAL_IGNORE_OUTPUT\n",
113+
"for n 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",
@@ -159,7 +159,7 @@
159159
}
160160
],
161161
"source": [
162-
"#NBVAL_IGNORE_OUTPUT\n",
162+
"# NBVAL_IGNORE_OUTPUT\n",
163163
"from devito import Grid, TimeFunction\n",
164164
"\n",
165165
"# First we need two time-dependent data fields, both initialized with the hat function\n",
@@ -211,8 +211,8 @@
211211
"update_u = Eq(u.forward, stencil_u, subdomain=grid.interior)\n",
212212
"update_v = Eq(v.forward, stencil_v, subdomain=grid.interior)\n",
213213
"\n",
214-
"print(\"U update:\\n%s\\n\" % update_u)\n",
215-
"print(\"V update:\\n%s\\n\" % update_v)"
214+
"print(f\"U update:\\n{update_u}\\n\")\n",
215+
"print(f\"V update:\\n{update_v}\\n\")"
216216
]
217217
},
218218
{
@@ -271,7 +271,7 @@
271271
}
272272
],
273273
"source": [
274-
"#NBVAL_IGNORE_OUTPUT\n",
274+
"# NBVAL_IGNORE_OUTPUT\n",
275275
"from devito import Operator\n",
276276
"\n",
277277
"# Reset our data field and ICs\n",
@@ -452,7 +452,7 @@
452452
}
453453
],
454454
"source": [
455-
"#NBVAL_IGNORE_OUTPUT\n",
455+
"# NBVAL_IGNORE_OUTPUT\n",
456456
"op = Operator([update_U] + bc_u + bc_v)\n",
457457
"op(time=nt, dt=dt)\n",
458458
"\n",

0 commit comments

Comments
 (0)