Skip to content

Commit 48b57f7

Browse files
committed
fix: Issues identified by ruff
1 parent 576163d commit 48b57f7

File tree

13 files changed

+41
-52
lines changed

13 files changed

+41
-52
lines changed

.circleci/version.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22

33
import sdcflows
44

5-
print(sdcflows.__version__, end='', file=open('/tmp/.docker-version.txt', 'w'))
5+
with open('/tmp/.docker-version.txt', 'w') as f:
6+
f.write(sdcflows.__version__)

docs/tools/apigen.py

Lines changed: 16 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,8 @@ def _parse_module(self, uri):
185185
# nothing that we could handle here.
186186
return ([], [])
187187

188-
f = open(filename)
189-
functions, classes = self._parse_lines(f)
190-
f.close()
188+
with open(filename) as f:
189+
functions, classes = self._parse_lines(f)
191190
return functions, classes
192191

193192
def _parse_module_with_import(self, uri):
@@ -220,9 +219,7 @@ def _parse_module_with_import(self, uri):
220219
if not self.other_defines and getmodule(obj) != mod:
221220
continue
222221
# figure out if obj is a function or class
223-
if (
224-
hasattr(obj, 'func_name') or isinstance(obj, (BuiltinFunctionType, FunctionType))
225-
):
222+
if hasattr(obj, 'func_name') or isinstance(obj, (BuiltinFunctionType, FunctionType)):
226223
functions.append(obj_str)
227224
else:
228225
try:
@@ -348,15 +345,7 @@ def _survives_exclude(self, matchstr, match_type):
348345
L = len(self.package_name)
349346
if matchstr[:L] == self.package_name:
350347
matchstr = matchstr[L:]
351-
for pat in patterns:
352-
try:
353-
pat.search
354-
except AttributeError:
355-
pat = re.compile(pat)
356-
if pat.search(matchstr):
357-
return False
358-
359-
return True
348+
return not any(re.search(pat, matchstr) for pat in patterns)
360349

361350
def discover_modules(self):
362351
r"""Return module sequence discovered from ``self.package_name``
@@ -436,11 +425,8 @@ def write_modules_api(self, modules, outdir):
436425
document_body.append(body)
437426

438427
out_module = ulm + self.rst_extension
439-
outfile = os.path.join(outdir, out_module)
440-
fileobj = open(outfile, 'w')
441-
442-
fileobj.writelines(document_head + document_body)
443-
fileobj.close()
428+
with open(os.path.join(outdir, out_module), 'w') as fileobj:
429+
fileobj.writelines(document_head + document_body)
444430
written_modules.append(out_module)
445431

446432
self.written_modules = written_modules
@@ -495,14 +481,13 @@ def write_index(self, outdir, froot='gen', relative_to=None):
495481
relpath = (outdir + os.path.sep).replace(relative_to + os.path.sep, '')
496482
else:
497483
relpath = outdir
498-
idx = open(path, 'w')
499-
w = idx.write
500-
w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
501-
502-
title = 'API Reference'
503-
w(title + '\n')
504-
w('=' * len(title) + '\n\n')
505-
w('.. toctree::\n\n')
506-
for f in self.written_modules:
507-
w(f' {os.path.join(relpath, f)}\n')
508-
idx.close()
484+
with open(path, 'w') as idx:
485+
w = idx.write
486+
w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')
487+
488+
title = 'API Reference'
489+
w(title + '\n')
490+
w('=' * len(title) + '\n\n')
491+
w('.. toctree::\n\n')
492+
for f in self.written_modules:
493+
w(f' {os.path.join(relpath, f)}\n')

docs/tools/buildmodref.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python
22
"""Script to auto-generate API docs."""
33

4-
54
# stdlib imports
65
import sys
76

@@ -48,7 +47,7 @@ def writeapi(package, outdir, source_version, other_defines=True):
4847
]
4948
docwriter.write_api_docs(outdir)
5049
docwriter.write_index(outdir, 'index', relative_to=outdir)
51-
print('%d files written' % len(docwriter.written_modules))
50+
print(f'{len(docwriter.written_modules)} files written')
5251

5352

5453
if __name__ == '__main__':

sdcflows/fieldmaps.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ def __attrs_post_init__(self):
376376
raise ValueError(
377377
'A fieldmap or phase-difference estimation type was found, '
378378
f'but an anatomical reference ({magnitude} file) is missing.'
379-
)
379+
) from None
380380

381381
# Check presence and try to find (if necessary) the second magnitude file
382382
if self.method == EstimatorType.PHASEDIFF and 'magnitude2' not in suffix_set:
@@ -390,7 +390,7 @@ def __attrs_post_init__(self):
390390
raise ValueError(
391391
'A phase-difference estimation (phase1/2) type was found, '
392392
'but an anatomical reference (magnitude2 file) is missing.'
393-
)
393+
) from None
394394

395395
# Fieldmap option 2: PEPOLAR (and fieldmap-less or ANAT)
396396
# IMPORTANT NOTE: fieldmap-less approaches can be considered PEPOLAR with RO = 0.0s

sdcflows/tests/test_fieldmaps.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def test_FieldmapEstimation(dsA_dir, inputfiles, method, nsources):
125125

126126
# Exercise workflow creation
127127
wf = fe.get_workflow()
128-
wf == fe.get_workflow()
128+
assert wf == fe.get_workflow()
129129

130130

131131
@pytest.mark.parametrize(

sdcflows/transform.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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.', stacklevel=2
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.', stacklevel=1
523+
'are implemented for its quality assurance.',
524+
stacklevel=1,
523525
)
524526

525527
# Resample

sdcflows/utils/bimap.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,11 @@ def __setitem__(self, key, value):
135135
try:
136136
hash(value)
137137
except TypeError as exc:
138-
raise TypeError(f"value '{value}' of {exc}")
138+
raise TypeError(f"value '{value}' of {exc}") from None
139139
try:
140140
hash(key)
141141
except TypeError as exc:
142-
raise TypeError(f"key '{key}' of {exc}")
142+
raise TypeError(f"key '{key}' of {exc}") from None
143143

144144
if self.__contains__(key):
145145
raise KeyError(f"'{key}' is already {'a value' * (key in self._inverse)} in mapping")

sdcflows/utils/phasemanip.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,13 +135,15 @@ def delta_te(in_values):
135135
te2 = float(in_values.get('EchoTimeDifference'))
136136
return abs(te2)
137137
except TypeError:
138-
raise ValueError('Phase/phase-difference fieldmaps: no echo-times information.')
138+
raise ValueError(
139+
'Phase/phase-difference fieldmaps: no echo-times information.'
140+
) from None
139141
except ValueError:
140-
raise ValueError(f'Could not interpret metadata <EchoTimeDifference={te2}>.')
142+
raise ValueError(f'Could not interpret metadata <EchoTimeDifference={te2}>.') from None
141143
try:
142144
te2 = float(te2 or 'unknown')
143145
te1 = float(te1 or 'unknown')
144146
except ValueError:
145-
raise ValueError(f'Could not interpret metadata <EchoTime(1,2)={(te1, te2)}>.')
147+
raise ValueError(f'Could not interpret metadata <EchoTime(1,2)={(te1, te2)}>.') from None
146148

147149
return abs(te2 - te1)

sdcflows/utils/wrangler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -606,7 +606,7 @@ def find_anatomical_estimators(
606606
meta.update({'TotalReadoutTime': get_trt(meta, candidate.path)})
607607
epi_targets.append(fm.FieldmapFile(candidate, metadata=meta))
608608

609-
def sort_key(fmap):
609+
def sort_key(fmap, suffixes=suffixes):
610610
# Return sbref before DWI/BOLD and shortest echo first
611611
return suffixes.index(fmap.suffix), fmap.metadata.get('EchoTime', 1)
612612

sdcflows/workflows/apply/registration.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,8 @@ def init_coeff2epi_wf(
164164
if write_coeff:
165165
warn(
166166
'SDCFlows does not tinker with the coefficients file anymore, '
167-
'the `write_coeff` parameter will be removed in a future release.', stacklevel=2
167+
'the `write_coeff` parameter will be removed in a future release.',
168+
stacklevel=2,
168169
)
169170

170171
return workflow

0 commit comments

Comments
 (0)