Skip to content

Commit 4bcd1b6

Browse files
committed
chore: Manual ruff fixes [ignore-rev]
1 parent 46a3018 commit 4bcd1b6

File tree

15 files changed

+75
-84
lines changed

15 files changed

+75
-84
lines changed

.maint/update_authors.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,11 @@ def get_git_lines(fname='line-contributors.txt'):
130130
if not lines:
131131
raise RuntimeError(
132132
"""\
133-
Could not find line-contributors from git repository.%s"""
134-
% """ \
133+
Could not find line-contributors from git repository.{}""".format(
134+
""" \
135135
git-line-summary not found, please install git-extras. """
136-
* (cmd[0] is None)
136+
* (cmd[0] is None)
137+
)
137138
)
138139
return [' '.join(line.strip().split()[1:-1]) for line in lines if '%' in line]
139140

@@ -219,7 +220,7 @@ def zenodo(
219220
elif isinstance(creator['affiliation'], list):
220221
creator['affiliation'] = creator['affiliation'][0]
221222

222-
Path(zenodo_file).write_text('%s\n' % json.dumps(zenodo, indent=2, ensure_ascii=False))
223+
Path(zenodo_file).write_text(f'{json.dumps(zenodo, indent=2, ensure_ascii=False)}\n')
223224

224225

225226
@cli.command()
@@ -266,10 +267,8 @@ def _aslist(value):
266267

267268
aff_indexes = [
268269
', '.join(
269-
[
270-
'%d' % (affiliations.index(a) + 1)
271-
for a in _aslist(author.get('affiliation', 'Unaffiliated'))
272-
]
270+
str(affiliations.index(a) + 1)
271+
for a in _aslist(author.get('affiliation', 'Unaffiliated'))
273272
)
274273
for author in hits
275274
]
@@ -280,15 +279,13 @@ def _aslist(value):
280279
file=sys.stderr,
281280
)
282281

283-
print('Authors (%d):' % len(hits))
284-
print(
285-
'%s.'
286-
% '; '.join(['%s \\ :sup:`%s`\\ ' % (i['name'], idx) for i, idx in zip(hits, aff_indexes)])
287-
)
282+
print(f'Authors ({len(hits)}):')
283+
print('; '.join([rf'{i["name"]} \ :sup:`{idx}`\ ' for i, idx in zip(hits, aff_indexes)]) + '.')
288284

289285
print(
290-
'\n\nAffiliations:\n%s'
291-
% '\n'.join([f'{i + 1: >2}. {a}' for i, a in enumerate(affiliations)])
286+
'\n\nAffiliations:\n{}'.format(
287+
'\n'.join([f'{i + 1: >2}. {a}' for i, a in enumerate(affiliations)])
288+
)
292289
)
293290

294291

docs/tools/apigen.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -217,14 +217,10 @@ def _parse_module_with_import(self, uri):
217217
continue
218218
obj = mod.__dict__[obj_str]
219219
# Check if function / class defined in module
220-
if not self.other_defines and not getmodule(obj) == mod:
220+
if not self.other_defines and getmodule(obj) != mod:
221221
continue
222222
# figure out if obj is a function or class
223-
if (
224-
hasattr(obj, 'func_name')
225-
or isinstance(obj, BuiltinFunctionType)
226-
or isinstance(obj, FunctionType)
227-
):
223+
if hasattr(obj, 'func_name') or isinstance(obj, (BuiltinFunctionType, FunctionType)):
228224
functions.append(obj_str)
229225
else:
230226
try:
@@ -278,7 +274,7 @@ def generate_api_doc(self, uri):
278274

279275
# Make a shorter version of the uri that omits the package name for
280276
# titles
281-
uri_short = re.sub(r'^%s\.' % self.package_name, '', uri)
277+
uri_short = re.sub(rf'^{self.package_name}\.', '', uri)
282278

283279
head = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n'
284280
body = ''
@@ -345,7 +341,7 @@ def _survives_exclude(self, matchstr, match_type):
345341
elif match_type == 'package':
346342
patterns = self.package_skip_patterns
347343
else:
348-
raise ValueError('Cannot interpret match type "%s"' % match_type)
344+
raise ValueError(f'Cannot interpret match type "{match_type}"')
349345
# Match to URI without package name
350346
L = len(self.package_name)
351347
if matchstr[:L] == self.package_name:
@@ -426,7 +422,7 @@ def write_modules_api(self, modules, outdir):
426422
written_modules = []
427423

428424
for ulm, mods in module_by_ulm.items():
429-
print('Generating docs for %s:' % ulm)
425+
print(f'Generating docs for {ulm}:')
430426
document_head = []
431427
document_body = []
432428

@@ -506,5 +502,5 @@ def write_index(self, outdir, froot='gen', relative_to=None):
506502
w('=' * len(title) + '\n\n')
507503
w('.. toctree::\n\n')
508504
for f in self.written_modules:
509-
w(' %s\n' % os.path.join(relpath, f))
505+
w(f' {os.path.join(relpath, f)}\n')
510506
idx.close()

docs/tools/buildmodref.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515

1616
def abort(error):
17-
print('*WARNING* API documentation not generated: %s' % error)
17+
print(f'*WARNING* API documentation not generated: {error}')
1818
exit()
1919

2020

@@ -41,7 +41,7 @@ def writeapi(package, outdir, source_version, other_defines=True):
4141
docwriter = ApiDocWriter(package, rst_extension='.rst', other_defines=other_defines)
4242

4343
docwriter.package_skip_patterns += [
44-
r'\.%s$' % package,
44+
rf'\.{package}$',
4545
r'.*test.*$',
4646
r'\.version.*$',
4747
]

sdcflows/cli/parser.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
#
2323
"""Standalone command line executable for estimation of fieldmaps."""
2424

25-
import re
2625
from argparse import Action, ArgumentDefaultsHelpFormatter, ArgumentParser
2726
from functools import partial
2827
from pathlib import Path
@@ -46,9 +45,7 @@ def _parse_participant_labels(value):
4645
['s060']
4746
4847
"""
49-
return sorted(
50-
set(re.sub(r'^sub-', '', item.strip()) for item in re.split(r'\s+', f'{value}'.strip()))
51-
)
48+
return sorted({item.removeprefix('sub-') for item in value.split()})
5249

5350

5451
def _parser():
@@ -301,12 +298,10 @@ def parse_args(args=None, namespace=None):
301298

302299
# Ensure input and output folders are not the same
303300
if output_dir == bids_dir:
301+
suggested_path = bids_dir / 'derivatives' / f'sdcflows_{version.split("+")[0]}'
304302
parser.error(
305303
'The selected output folder is the same as the input BIDS folder. '
306-
'Please modify the output path (suggestion: %s).'
307-
% bids_dir
308-
/ 'derivatives'
309-
/ ('sdcflows_%s' % version.split('+')[0])
304+
f'Please modify the output path (suggestion: {suggested_path}).'
310305
)
311306

312307
if bids_dir in work_dir.parents:

sdcflows/config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@
124124
from importlib_metadata import version as get_version
125125

126126
# Ignore annoying warnings
127+
import contextlib
128+
127129
from sdcflows import __version__
128130
from sdcflows._warnings import logging
129131

@@ -220,7 +222,7 @@
220222
class _Config:
221223
"""An abstract class forbidding instantiation."""
222224

223-
_paths = tuple()
225+
_paths = ()
224226

225227
def __init__(self):
226228
"""Avert instantiation."""
@@ -239,10 +241,8 @@ def load(cls, settings, init=True):
239241
setattr(cls, k, v)
240242

241243
if init:
242-
try:
244+
with contextlib.suppress(AttributeError):
243245
cls.init()
244-
except AttributeError:
245-
pass
246246

247247
@classmethod
248248
def get(cls):

sdcflows/fieldmaps.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def __attrs_post_init__(self):
342342

343343
# Fieldmap option 1: actual field-mapping sequences
344344
fmap_types = suffix_set.intersection(('fieldmap', 'phasediff', 'phase1', 'phase2'))
345-
if len(fmap_types) > 1 and fmap_types - set(('phase1', 'phase2')):
345+
if len(fmap_types) > 1 and fmap_types - {'phase1', 'phase2'}:
346346
raise TypeError(f'Incompatible suffices found: <{",".join(fmap_types)}>.')
347347

348348
if fmap_types:
@@ -403,7 +403,7 @@ def __attrs_post_init__(self):
403403

404404
if _pepolar_estimation and not anat_types:
405405
self.method = MODALITIES[pepolar_types.pop()]
406-
_pe = set(f.metadata['PhaseEncodingDirection'] for f in self.sources)
406+
_pe = {f.metadata['PhaseEncodingDirection'] for f in self.sources}
407407
if len(_pe) == 1:
408408
raise ValueError(
409409
f'Only one phase-encoding direction <{_pe.pop()}> found across sources.'
@@ -418,9 +418,9 @@ def __attrs_post_init__(self):
418418
# No method has been identified -> fail.
419419
raise ValueError('Insufficient sources to estimate a fieldmap.')
420420

421-
intents_meta = set(
421+
intents_meta = {
422422
el for f in self.sources for el in listify(f.metadata.get('IntendedFor') or [])
423-
)
423+
}
424424

425425
# Register this estimation method
426426
if not self.bids_id:

sdcflows/interfaces/bspline.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,7 @@ def _fix_topup_fieldcoeff(in_coeff, fmap_ref, pe_dir, out_file=None):
628628
)
629629
)
630630
header['cal_min'] = -header['cal_max']
631-
header.set_intent('estimate', tuple(), name='B-Spline coefficients')
631+
header.set_intent('estimate', (), name='B-Spline coefficients')
632632

633633
# Write out fixed (generalized) coefficients
634634
coeffnii.__class__(coeffnii.dataobj, newaff, header).to_filename(out_file)

sdcflows/interfaces/reportlets.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ class FieldmapReportlet(reporting.ReportCapableInterface):
6161
def __init__(self, **kwargs):
6262
"""Instantiate FieldmapReportlet."""
6363
self._n_cuts = kwargs.pop('n_cuts', self._n_cuts)
64-
super(FieldmapReportlet, self).__init__(generate_report=True, **kwargs)
64+
super().__init__(generate_report=True, **kwargs)
6565

6666
def _run_interface(self, runtime):
6767
return runtime
@@ -77,7 +77,7 @@ def _generate_report(self):
7777
fmapnii = nb.squeeze_image(rotate_affine(load_img(self.inputs.fieldmap), rot=canonical_r))
7878

7979
if fmapnii.dataobj.ndim == 4:
80-
for i, tstep in enumerate(nb.four_to_three(fmapnii)):
80+
for tstep in nb.four_to_three(fmapnii):
8181
if np.any(np.asanyarray(tstep.dataobj) != 0):
8282
fmapnii = tstep
8383
break

sdcflows/interfaces/utils.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -196,20 +196,20 @@ def _run_interface(self, runtime):
196196

197197
# Identity transform
198198
if np.array_equal(img2target, [[0, 1], [1, 1], [2, 1]]):
199-
self._results = dict(
200-
out_file=self.inputs.in_file,
201-
pe_dir=self.inputs.pe_dir,
202-
)
199+
self._results = {
200+
'out_file': self.inputs.in_file,
201+
'pe_dir': self.inputs.pe_dir,
202+
}
203203
return runtime
204204

205205
reoriented = img.as_reoriented(img2target)
206206

207207
pe_dirs = [reorient_pedir(pe_dir, img2target) for pe_dir in self.inputs.pe_dir]
208208

209-
self._results = dict(
210-
out_file=fname_presuffix(self.inputs.in_file, suffix=target, newpath=runtime.cwd),
211-
pe_dir=pe_dirs,
212-
)
209+
self._results = {
210+
'out_file': fname_presuffix(self.inputs.in_file, suffix=target, newpath=runtime.cwd),
211+
'pe_dir': pe_dirs,
212+
}
213213

214214
reoriented.to_filename(self._results['out_file'])
215215

@@ -405,7 +405,7 @@ def _flatten(inlist, max_trs=50, out_dir=None):
405405
out_dir = Path(out_dir) if out_dir is not None else Path()
406406

407407
output = []
408-
for i, (path, meta) in enumerate(inlist):
408+
for path, meta in inlist:
409409
img = nb.load(path)
410410
if len(img.shape) == 3:
411411
output.append((path, meta))

sdcflows/transform.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
from collections.abc import Sequence
5353
from functools import partial
5454
from pathlib import Path
55-
from typing import Callable, Tuple
55+
from typing import Callable
5656
from warnings import warn
5757

5858
import attr
@@ -72,7 +72,7 @@
7272
def _sdc_unwarp(
7373
data: np.ndarray,
7474
coordinates: np.ndarray,
75-
pe_info: Tuple[int, float],
75+
pe_info: tuple[int, float],
7676
hmc_xfm: np.ndarray | None,
7777
jacobian: bool,
7878
fmap_hz: np.ndarray,
@@ -121,7 +121,7 @@ def _sdc_unwarp(
121121
async def worker(
122122
data: np.ndarray,
123123
coordinates: np.ndarray,
124-
pe_info: Tuple[int, float],
124+
pe_info: tuple[int, float],
125125
hmc_xfm: np.ndarray,
126126
func: Callable,
127127
semaphore: asyncio.Semaphore,
@@ -137,7 +137,7 @@ async def unwarp_parallel(
137137
fulldataset: np.ndarray,
138138
coordinates: np.ndarray,
139139
fmap_hz: np.ndarray,
140-
pe_info: Sequence[Tuple[int, float]],
140+
pe_info: Sequence[tuple[int, float]],
141141
xfms: Sequence[np.ndarray],
142142
jacobian: bool,
143143
order: int = 3,
@@ -464,7 +464,8 @@ def apply(
464464
if self.mapped is not None:
465465
warn(
466466
'The fieldmap has been already fit, the user is responsible for '
467-
'ensuring the parameters of the EPI target are consistent.'
467+
'ensuring the parameters of the EPI target are consistent.',
468+
stacklevel=2,
468469
)
469470
else:
470471
# Generate warp field (before ensuring positive cosines)
@@ -519,7 +520,8 @@ def apply(
519520
warn(
520521
'Head-motion compensating (realignment) transforms are ignored when applying '
521522
'the unwarp with SDCFlows. This feature will be enabled as soon as unit tests '
522-
'are implemented for its quality assurance.'
523+
'are implemented for its quality assurance.',
524+
stacklevel=1,
523525
)
524526

525527
# Resample
@@ -733,7 +735,7 @@ def grid_bspline_weights(target_nii, ctrl_nii, dtype='float32'):
733735
0,
734736
atol=1e-3,
735737
):
736-
warn("Image's and B-Spline's grids are not aligned.")
738+
warn("Image's and B-Spline's grids are not aligned.", stacklevel=2)
737739

738740
target_to_grid = np.linalg.inv(ctrl_nii.affine) @ target_nii.affine
739741
wd = []

0 commit comments

Comments
 (0)