Skip to content

Commit

Permalink
STY: Use f-strings where possible
Browse files Browse the repository at this point in the history
These have been changed manually.
  • Loading branch information
DimitriPapadopoulos committed Mar 1, 2024
1 parent f344120 commit 40a616d
Show file tree
Hide file tree
Showing 32 changed files with 103 additions and 110 deletions.
9 changes: 5 additions & 4 deletions docs/sphinxext/docscrape.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,9 @@ def parse_item_name(text):
description = line_match.group("desc")
if line_match.group("trailing") and description:
self._error_location(
"Unexpected comma or period after function list at index %d of "
'line "%s"' % (line_match.end("trailing"), line),
"Unexpected comma or period after function list "
f"at index {line_match.end('trailing')} of line "
f'"{line}"',
error=False,
)
if not description and line.startswith(" "):
Expand Down Expand Up @@ -414,8 +415,8 @@ def _parse(self):
section = " ".join(section)
if self.get(section):
self._error_location(
"The section %s appears twice in %s"
% (section, "\n".join(self._doc._str))
f"The section {section} appears twice "
f"in {'\n'.join(self._doc._str)}"
)

if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
Expand Down
14 changes: 7 additions & 7 deletions docs/sphinxext/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def make_link_node(rawtext, app, type, slug, options):
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
raise ValueError(f'github_project_url configuration value is not set ({err})')

ref = base + type + '/' + slug + '/'
set_classes(options)
Expand Down Expand Up @@ -71,19 +71,19 @@ def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
except ValueError:
msg = inliner.reporter.error(
'GitHub issue number must be a number greater than or equal to 1; '
'"%s" is invalid.' % text, line=lineno)
f'"{text}" is invalid.', line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
app = inliner.document.settings.env.app
#app.info('issue %r' % text)
#app.info(f'issue {text!r}')
if 'pull' in name.lower():
category = 'pull'
elif 'issue' in name.lower():
category = 'issues'
else:
msg = inliner.reporter.error(
'GitHub roles include "ghpull" and "ghissue", '
'"%s" is invalid.' % name, line=lineno)
f'"{name}" is invalid.', line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
node = make_link_node(rawtext, app, category, str(issue_num), options)
Expand All @@ -105,7 +105,7 @@ def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
#app.info(f'user link {text!r}')
ref = 'https://www.github.com/' + text
node = nodes.reference(rawtext, text, refuri=ref, **options)
return [node], []
Expand All @@ -126,15 +126,15 @@ def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
:param content: The directive content for customization.
"""
app = inliner.document.settings.env.app
#app.info('user link %r' % text)
#app.info(f'user link {text!r}')
try:
base = app.config.github_project_url
if not base:
raise AttributeError
if not base.endswith('/'):
base += '/'
except AttributeError as err:
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
raise ValueError(f'github_project_url configuration value is not set ({err})')

ref = base + text
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)
Expand Down
2 changes: 1 addition & 1 deletion docs/sphinxext/math_dollar.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def dollars_to_math(source):
def repl(matchobj):
global _data
s = matchobj.group(0)
t = "___XXX_REPL_%d___" % len(_data)
t = f"___XXX_REPL_{len(_data)}___"
_data[t] = s
return t
s = re.sub(r"({[^{}$]*\$[^{}$]*\$[^{}]*})", repl, s)
Expand Down
4 changes: 1 addition & 3 deletions niworkflows/__about__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@
from datetime import datetime

__packagename__ = "niworkflows"
__copyright__ = "Copyright {}, The NiPreps Developers".format(
datetime.now().year
)
__copyright__ = f"Copyright {datetime.now().year}, The NiPreps Developers"
__credits__ = [
"Oscar Esteban",
"Ross Blair",
Expand Down
12 changes: 6 additions & 6 deletions niworkflows/anat/ants.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,19 +721,19 @@ def init_atropos_wf(

# De-pad
depad_mask = pe.Node(
ImageMath(operation="PadImage", op2="-%d" % padding), name="23_depad_mask"
ImageMath(operation="PadImage", op2=f"-{padding}"), name="23_depad_mask"
)
depad_segm = pe.Node(
ImageMath(operation="PadImage", op2="-%d" % padding), name="24_depad_segm"
ImageMath(operation="PadImage", op2=f"-{padding}"), name="24_depad_segm"
)
depad_gm = pe.Node(
ImageMath(operation="PadImage", op2="-%d" % padding), name="25_depad_gm"
ImageMath(operation="PadImage", op2=f"-{padding}"), name="25_depad_gm"
)
depad_wm = pe.Node(
ImageMath(operation="PadImage", op2="-%d" % padding), name="26_depad_wm"
ImageMath(operation="PadImage", op2=f"-{padding}"), name="26_depad_wm"
)
depad_csf = pe.Node(
ImageMath(operation="PadImage", op2="-%d" % padding), name="27_depad_csf"
ImageMath(operation="PadImage", op2=f"-{padding}"), name="27_depad_csf"
)

msk_conform = pe.Node(niu.Function(function=_conform_mask), name="msk_conform")
Expand Down Expand Up @@ -1061,7 +1061,7 @@ def _select_labels(in_segm, labels):
for label in labels:
newnii = nii.__class__(np.uint8(label_data == label), nii.affine, nii.header)
newnii.set_data_dtype("uint8")
out_file = fname_presuffix(in_segm, suffix="_class-%02d" % label, newpath=cwd)
out_file = fname_presuffix(in_segm, suffix=f"_class-{label:%02d}", newpath=cwd)
newnii.to_filename(out_file)
out_files.append(out_file)
return out_files
Expand Down
2 changes: 1 addition & 1 deletion niworkflows/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Loader:
.. automethod:: cached
"""

def __init__(self, anchor: Union[str, ModuleType]):
def __init__(self, anchor: str | ModuleType):
self._anchor = anchor
self.files = files(anchor)
self.exit_stack = ExitStack()
Expand Down
5 changes: 2 additions & 3 deletions niworkflows/func/tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,10 @@
parameters = zip(bold_datasets, exp_masks)

if not bold_datasets:
_folder_contents = "\n".join([str(p) for p in datapath.glob("ds*/*.nii.gz")])
raise RuntimeError(
f"Data folder <{datapath}> was provided, but no images were found. "
"Folder contents:\n{}".format(
"\n".join([str(p) for p in datapath.glob("ds*/*.nii.gz")])
)
f"Folder contents:\n{_folder_contents}"
)


Expand Down
5 changes: 2 additions & 3 deletions niworkflows/interfaces/bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,8 +858,7 @@ def _run_interface(self, runtime):
for fname in self._fields:
if not self._undef_fields and fname not in metadata:
raise KeyError(
'Metadata field "%s" not found for file %s'
% (fname, self.inputs.in_file)
f'Metadata field "{fname}" not found for file {self.inputs.in_file}'
)
self._results[fname] = metadata.get(fname, Undefined)
return runtime
Expand Down Expand Up @@ -945,7 +944,7 @@ def _run_interface(self, runtime):
if dest.exists():
continue
else:
raise FileNotFoundError("Expected to find '%s' to copy" % source)
raise FileNotFoundError(f"Expected to find '{source}' to copy")

if (
space == 'fsaverage'
Expand Down
10 changes: 5 additions & 5 deletions niworkflows/interfaces/confounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,13 +298,13 @@ def spike_regressors(
mask = reduce((lambda x, y: x | y), mask.values())

for lag in lags:
mask = set([m + lag for m in mask]) | mask
mask = {m + lag for m in mask} | mask

mask = mask.intersection(indices)
if minimum_contiguous is not None:
post_final = data.shape[0] + 1
epoch_length = np.diff(sorted(mask | set([-1, post_final]))) - 1
epoch_end = sorted(mask | set([post_final]))
epoch_length = np.diff(sorted(mask | {-1, post_final})) - 1
epoch_end = sorted(mask | {post_final})
for end, length in zip(epoch_end, epoch_length):
if length < minimum_contiguous:
mask = mask | set(range(end - length, end))
Expand Down Expand Up @@ -357,7 +357,7 @@ def temporal_derivatives(order, variables, data):
if 0 in order:
data_deriv[0] = data[variables]
variables_deriv[0] = variables
order = set(order) - set([0])
order = set(order) - {0}
for o in order:
variables_deriv[o] = [f"{v}_derivative{o}" for v in variables]
data_deriv[o] = np.tile(np.nan, data[variables].shape)
Expand Down Expand Up @@ -400,7 +400,7 @@ def exponential_terms(order, variables, data):
if 1 in order:
data_exp[1] = data[variables]
variables_exp[1] = variables
order = set(order) - set([1])
order = set(order) - {1}
for o in order:
variables_exp[o] = [f"{v}_power{o}" for v in variables]
data_exp[o] = data[variables] ** o
Expand Down
2 changes: 1 addition & 1 deletion niworkflows/interfaces/freesurfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def cmdline(self):
if source is None:
return cmd

return "cp {} {}".format(source, self._list_outputs()["out_file"])
return f"cp {source} {self._list_outputs()['out_file']}"


class _FSInjectBrainExtractedInputSpec(BaseInterfaceInputSpec):
Expand Down
7 changes: 2 additions & 5 deletions niworkflows/interfaces/header.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def _run_interface(self, runtime):
_copyxform(
self.inputs.hdr_file,
out_name,
message="CopyXForm (niworkflows v%s)" % __version__,
message=f"CopyXForm (niworkflows v{__version__})",
)
self._results[f].append(out_name)

Expand Down Expand Up @@ -543,10 +543,7 @@ def _run_interface(self, runtime):
img.to_filename(out_fname)

if warning_txt:
snippet = '<h3 class="elem-title">%s</h3>\n%s\n' % (
warning_txt,
description,
)
snippet = f'<h3 class="elem-title">{warning_txt}</h3>\n{description}\n'
with open(out_report, "w") as fobj:
fobj.write(indent(snippet, "\t" * 3))

Expand Down
2 changes: 1 addition & 1 deletion niworkflows/interfaces/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def _run_interface(self, runtime):
filenii = nb.load(f)
filenii = nb.squeeze_image(filenii)
if len(filenii.shape) == 5:
raise RuntimeError("Input image (%s) is 5D." % f)
raise RuntimeError(f"Input image ({f}) is 5D.")
if filenii.dataobj.ndim == 4:
nii_list += nb.four_to_three(filenii)
else:
Expand Down
8 changes: 4 additions & 4 deletions niworkflows/interfaces/itk.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def _applytfms(args):

in_file, in_xform, ifargs, index, newpath = args
out_file = fname_presuffix(
in_file, suffix="_xform-%05d" % index, newpath=newpath, use_ext=True
in_file, suffix=f"_xform-{index:05d}", newpath=newpath, use_ext=True
)

copy_dtype = ifargs.pop("copy_dtype", False)
Expand Down Expand Up @@ -250,8 +250,8 @@ def _arrange_xfms(transforms, num_files, tmp_folder):

if nxforms != num_files:
raise RuntimeError(
"Number of transforms (%d) found in the ITK file does not match"
" the number of input image files (%d)." % (nxforms, num_files)
f"Number of transforms ({nxforms}) found in the ITK file does"
f" not match the number of input image files ({num_files})."
)

# At this point splitting transforms will be necessary, generate a base name
Expand All @@ -262,7 +262,7 @@ def _arrange_xfms(transforms, num_files, tmp_folder):
split_xfms = []
for xform_i in range(nxforms):
# Find start token to extract
startidx = tfdata.index("#Transform %d" % xform_i)
startidx = tfdata.index(f"#Transform {xform_i}")
next_xform = base_xform + tfdata[startidx + 1:startidx + 4] + [""]
xfm_file = out_base(xform_i)
with open(xfm_file, "w") as out_xfm:
Expand Down
5 changes: 2 additions & 3 deletions niworkflows/interfaces/nibabel.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,9 +661,8 @@ def _gen_reference(
# Keep 0, 2, 3, 4 unchanged
resampled.header.set_qform(xform, int(xform_code))
resampled.header.set_sform(xform, int(xform_code))
resampled.header["descrip"] = "reference image generated by %s." % (
message or "(unknown software)"
)
message = message or "(unknown software)"
resampled.header["descrip"] = f"reference image generated by {message}."
resampled.to_filename(out_file)
return out_file

Expand Down
13 changes: 5 additions & 8 deletions niworkflows/interfaces/norm.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,7 @@ def _get_settings(self):
return self.inputs.settings

# Define a prefix for output files based on the modality of the moving image.
filestart = "{}-mni_registration_{}_".format(
self.inputs.moving.lower(), self.inputs.flavor
)
filestart = f"{self.inputs.moving.lower()}-mni_registration_{self.inputs.flavor}_"

data_dir = load_data()
# Get a list of settings files that match the flavor.
Expand Down Expand Up @@ -224,7 +222,7 @@ def _run_interface(self, runtime):
NIWORKFLOWS_LOG.warning("Retry #%d failed.", self.retry)
# Save outputs (if available)
term_out = _write_outputs(
interface_result.runtime, ".nipype-%04d" % self.retry
interface_result.runtime, f".nipype-{self.retry:04d}"
)
if term_out:
NIWORKFLOWS_LOG.warning(
Expand All @@ -243,7 +241,7 @@ def _run_interface(self, runtime):

# If all tries fail, raise an error.
raise RuntimeError(
"Robust spatial normalization failed after %d retries." % (self.retry - 1)
f"Robust spatial normalization failed after {self.retry - 1} retries."
)

def _get_ants_args(self):
Expand Down Expand Up @@ -435,10 +433,9 @@ def _get_ants_args(self):
self._reference_image = ref_template
if not op.isfile(self._reference_image):
raise ValueError(
"""\
The registration reference must be an existing file, but path "%s" \
f"""\
The registration reference must be an existing file, but path "{ref_template}" \
cannot be found."""
% ref_template
)

# Get the template specified by the user.
Expand Down
4 changes: 2 additions & 2 deletions niworkflows/interfaces/reportlets/masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def _post_run_hook(self, runtime):
if len(self.inputs.mask_files) != 1:
raise ValueError(
"ACompCorRPT only supports a single input mask. "
"A list %s was found." % self.inputs.mask_files
f"A list {self.inputs.mask_files} was found."
)
self._anat_file = self.inputs.realigned_file
self._mask_file = self.inputs.mask_files[0]
Expand Down Expand Up @@ -182,7 +182,7 @@ def _post_run_hook(self, runtime):
if isinstance(high_variance_masks, list):
raise ValueError(
"TCompCorRPT only supports a single output high variance mask. "
"A list %s was found." % high_variance_masks
f"A list {high_variance_masks} was found."
)
self._anat_file = self.inputs.realigned_file
self._mask_file = high_variance_masks
Expand Down
9 changes: 4 additions & 5 deletions niworkflows/interfaces/surf.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,13 +509,12 @@ def _run_interface(self, runtime):
"VolGeomC_A": "0.0",
"VolGeomC_S": "0.0",
}
meta["AnatomicalStructurePrimary"] = "Cortex%s" % (
"Left" if self.inputs.surf_key.startswith("lh") else "Right"
)
_lr = "Left" if self.inputs.surf_key.startswith("lh") else "Right"
meta["AnatomicalStructurePrimary"] = f"Cortex{_lr}"
meta["AnatomicalStructureSecondary"] = SECONDARY_ANAT_STRUC[
self.inputs.surf_key.split(".")[-1]
]
meta["Name"] = "%s_average.gii" % self.inputs.surf_key
meta["Name"] = f"{self.inputs.surf_key}_average.gii"

out_file = Path(runtime.cwd) / meta["Name"]
out_file = ply2gii(self.inputs.in_file, meta, out_file=out_file)
Expand Down Expand Up @@ -754,7 +753,7 @@ def ply2gii(in_file, metadata, out_file=None):
metadata.update(
zip(
("SurfaceCenterX", "SurfaceCenterY", "SurfaceCenterZ"),
["%.4f" % c for c in surf.centroid],
[f"{c:.4f}" for c in surf.centroid],
)
)

Expand Down
4 changes: 2 additions & 2 deletions niworkflows/interfaces/tests/test_bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ def test_ReadSidecarJSON_connection(testdata_dir, field):
"derivatives, subjects_dir",
[
(os.getenv("FREESURFER_HOME"), "subjects"),
("/tmp", "{}/{}".format((os.getenv("FREESURFER_HOME"), "subjects"))),
("/tmp", "{}/{}".format(os.getenv("FREESURFER_HOME"), "subjects")),
],
)
def test_fsdir_noaction(derivatives, subjects_dir):
Expand All @@ -661,7 +661,7 @@ def test_fsdir_noaction(derivatives, subjects_dir):
res = bintfs.BIDSFreeSurferDir(
derivatives=derivatives, subjects_dir=subjects_dir, freesurfer_home=fshome
).run()
assert res.outputs.subjects_dir == "%s/subjects" % fshome
assert res.outputs.subjects_dir == f"{fshome}/subjects"


@pytest.mark.skipif(not os.getenv("FREESURFER_HOME"), reason="No FreeSurfer")
Expand Down
Loading

0 comments on commit 40a616d

Please sign in to comment.