Skip to content

Commit

Permalink
STY: Apply ruff/pyupgrade rule UP032
Browse files Browse the repository at this point in the history
UP032 Use f-string instead of `format` call

Co-authored-by: Chris Markiewicz <[email protected]>
  • Loading branch information
DimitriPapadopoulos and effigies committed Oct 9, 2024
1 parent a44b431 commit 1253ce5
Show file tree
Hide file tree
Showing 37 changed files with 123 additions and 300 deletions.
13 changes: 4 additions & 9 deletions nipype/algorithms/confounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,8 +608,7 @@ def _run_interface(self, runtime):

if len(imgseries.shape) != 4:
raise ValueError(
"{} expected a 4-D nifti file. Input {} has "
"{} dimensions (shape {})".format(
"{} expected a 4-D nifti file. Input {} has {} dimensions (shape {})".format( # noqa: UP032
self._header,
self.inputs.realigned_file,
len(imgseries.shape),
Expand Down Expand Up @@ -648,8 +647,7 @@ def _run_interface(self, runtime):

if TR == 0:
raise ValueError(
"{} cannot detect repetition time from image - "
"Set the repetition_time input".format(self._header)
f"{self._header} cannot detect repetition time from image - Set the repetition_time input"
)

if isdefined(self.inputs.variance_threshold):
Expand Down Expand Up @@ -753,8 +751,7 @@ def _run_interface(self, runtime):
f.write("\t".join(["component"] + list(metadata.keys())) + "\n")
for i in zip(components_names, *metadata.values()):
f.write(
"{0[0]}\t{0[1]}\t{0[2]:.10f}\t"
"{0[3]:.10f}\t{0[4]:.10f}\t{0[5]}\n".format(i)
f"{i[0]}\t{i[1]}\t{i[2]:.10f}\t{i[3]:.10f}\t{i[4]:.10f}\t{i[5]}\n"
)

return runtime
Expand Down Expand Up @@ -1398,9 +1395,7 @@ def compute_noise_components(
if imgseries.shape[:3] != mask.shape:
raise ValueError(
"Inputs for CompCor, timeseries and mask, do not have "
"matching spatial dimensions ({} and {}, respectively)".format(
imgseries.shape[:3], mask.shape
)
f"matching spatial dimensions ({imgseries.shape[:3]} and {mask.shape}, respectively)"
)

voxel_timecourses = imgseries[mask, :]
Expand Down
2 changes: 1 addition & 1 deletion nipype/caching/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def __call__(self, **kwargs):
return out

def __repr__(self):
return "{}({}.{}), base_dir={})".format(
return "{}({}.{}), base_dir={})".format( # noqa: UP032
self.__class__.__name__,
self.interface.__module__,
self.interface.__name__,
Expand Down
28 changes: 14 additions & 14 deletions nipype/interfaces/ants/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def _transformation_constructor(self):
return "".join(retval)

def _regularization_constructor(self):
return "--regularization {}[{},{}]".format(
return "--regularization {}[{},{}]".format( # noqa: UP032
self.inputs.regularization,
self.inputs.regularization_gradient_field_sigma,
self.inputs.regularization_deformation_field_sigma,
Expand Down Expand Up @@ -1242,7 +1242,7 @@ def _format_winsorize_image_intensities(self):
)
)
self._quantilesDone = True
return "--winsorize-image-intensities [ {}, {} ]".format(
return "--winsorize-image-intensities [ {}, {} ]".format( # noqa: UP032
self.inputs.winsorize_lower_quantile,
self.inputs.winsorize_upper_quantile,
)
Expand All @@ -1269,12 +1269,12 @@ def _get_initial_transform_filenames(self):
def _format_arg(self, opt, spec, val):
if opt == "fixed_image_mask":
if isdefined(self.inputs.moving_image_mask):
return "--masks [ {}, {} ]".format(
return "--masks [ {}, {} ]".format( # noqa: UP032
self.inputs.fixed_image_mask,
self.inputs.moving_image_mask,
)
else:
return "--masks %s" % self.inputs.fixed_image_mask
return "--masks {}".format(self.inputs.fixed_image_mask) # noqa: UP032
elif opt == "transforms":
return self._format_registration()
elif opt == "initial_moving_transform":
Expand Down Expand Up @@ -1309,18 +1309,20 @@ def _format_arg(self, opt, spec, val):
out_filename = self._get_outputfilenames(inverse=False)
inv_out_filename = self._get_outputfilenames(inverse=True)
if out_filename and inv_out_filename:
return "--output [ {}, {}, {} ]".format(
return "--output [ {}, {}, {} ]".format( # noqa: UP032
self.inputs.output_transform_prefix,
out_filename,
inv_out_filename,
)
elif out_filename:
return "--output [ {}, {} ]".format(
return "--output [ {}, {} ]".format( # noqa: UP032
self.inputs.output_transform_prefix,
out_filename,
)
else:
return "--output %s" % self.inputs.output_transform_prefix
return "--output {}".format( # noqa: UP032
self.inputs.output_transform_prefix,
)
elif opt == "winsorize_upper_quantile" or opt == "winsorize_lower_quantile":
if not self._quantilesDone:
return self._format_winsorize_image_intensities()
Expand Down Expand Up @@ -1591,7 +1593,7 @@ class MeasureImageSimilarity(ANTSCommand):
def _metric_constructor(self):
retval = (
'--metric {metric}["{fixed_image}","{moving_image}",{metric_weight},'
"{radius_or_number_of_bins},{sampling_strategy},{sampling_percentage}]".format(
"{radius_or_number_of_bins},{sampling_strategy},{sampling_percentage}]".format( # noqa: UP032
metric=self.inputs.metric,
fixed_image=self.inputs.fixed_image,
moving_image=self.inputs.moving_image,
Expand All @@ -1605,13 +1607,13 @@ def _metric_constructor(self):

def _mask_constructor(self):
if self.inputs.moving_image_mask:
retval = '--masks ["{fixed_image_mask}","{moving_image_mask}"]'.format(
retval = '--masks ["{fixed_image_mask}","{moving_image_mask}"]'.format( # noqa: UP032
fixed_image_mask=self.inputs.fixed_image_mask,
moving_image_mask=self.inputs.moving_image_mask,
)
else:
retval = '--masks "{fixed_image_mask}"'.format(
fixed_image_mask=self.inputs.fixed_image_mask
retval = '--masks "{}"'.format( # noqa: UP032
fixed_image_mask=self.inputs.fixed_image_mask,
)
return retval

Expand Down Expand Up @@ -1871,9 +1873,7 @@ def _list_outputs(self):
f"00_{self.inputs.output_prefix}_AffineTransform.mat"
)
outputs["displacement_field"] = os.path.abspath(
"01_{}_DisplacementFieldTransform.nii.gz".format(
self.inputs.output_prefix
)
f"01_{self.inputs.output_prefix}_DisplacementFieldTransform.nii.gz"
)
if self.inputs.process == "assemble":
outputs["out_file"] = os.path.abspath(self.inputs.out_file)
Expand Down
4 changes: 2 additions & 2 deletions nipype/interfaces/base/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,8 +849,8 @@ def _filename_from_source(self, name, chain=None):

if not isinstance(ns, (str, bytes)):
raise ValueError(
"name_source of '{}' trait should be an input trait "
"name, but a type {} object was found".format(name, type(ns))
f"name_source of '{name}' trait should be an input trait "
f"name, but a type {type(ns)} object was found"
)

if isdefined(getattr(self.inputs, ns)):
Expand Down
5 changes: 1 addition & 4 deletions nipype/interfaces/base/specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,7 @@ def _deprecated_warn(self, obj, name, old, new):
raise TraitError(msg)
else:
if trait_spec.new_name:
msg += "Unsetting old value {}; setting new value {}.".format(
name,
trait_spec.new_name,
)
msg += f"Unsetting old value {name}; setting new value {trait_spec.new_name}."
warn(msg)
if trait_spec.new_name:
self.trait_set(
Expand Down
8 changes: 6 additions & 2 deletions nipype/interfaces/base/tests/test_resource_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ class UseResources(CommandLine):

@pytest.mark.skip(reason="inconsistent readings")
@pytest.mark.skipif(os.getenv("CI_SKIP_TEST", False), reason="disabled in CI tests")
@pytest.mark.parametrize(("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)])
@pytest.mark.parametrize(
("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]
)
def test_cmdline_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor):
"""
Test runtime profiler correctly records workflow RAM/CPUs consumption
Expand All @@ -80,7 +82,9 @@ def test_cmdline_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor):
@pytest.mark.skipif(
True, reason="test disabled temporarily, until function profiling works"
)
@pytest.mark.parametrize(("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)])
@pytest.mark.parametrize(
("mem_gb", "n_procs"), [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]
)
def test_function_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor):
"""
Test runtime profiler correctly records workflow RAM/CPUs consumption
Expand Down
11 changes: 3 additions & 8 deletions nipype/interfaces/cmtk/parcellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,15 +315,10 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name):
)
runCmd(mri_cmd, log)
runCmd("mris_volmask %s" % subject_id, log)
mri_cmd = 'mri_convert -i "{}/mri/ribbon.mgz" -o "{}/mri/ribbon.nii.gz"'.format(
op.join(subjects_dir, subject_id),
op.join(subjects_dir, subject_id),
)
subject_path = op.join(subjects_dir, subject_id)
mri_cmd = f'mri_convert -i "{subject_path}/mri/ribbon.mgz" -o "{subject_path}/mri/ribbon.nii.gz"'
runCmd(mri_cmd, log)
mri_cmd = 'mri_convert -i "{}/mri/aseg.mgz" -o "{}/mri/aseg.nii.gz"'.format(
op.join(subjects_dir, subject_id),
op.join(subjects_dir, subject_id),
)
mri_cmd = f'mri_convert -i "{subject_path}/mri/aseg.mgz" -o "{subject_path}/mri/aseg.nii.gz"'
runCmd(mri_cmd, log)

iflogger.info("[ DONE ]")
Expand Down
5 changes: 2 additions & 3 deletions nipype/interfaces/dtitk/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,10 @@ def __init__(self, *args, **kwargs):
rename_idx = classes.index("DTITKRenameMixin")
new_name = classes[rename_idx + 1]
warnings.warn(
"The {} interface has been renamed to {}\n"
f"The {dep_name} interface has been renamed to {new_name}\n"
"Please see the documentation for DTI-TK "
"interfaces, as some inputs have been "
"added or renamed for clarity."
"".format(dep_name, new_name),
"added or renamed for clarity.",
DeprecationWarning,
)
super().__init__(*args, **kwargs)
Expand Down
12 changes: 2 additions & 10 deletions nipype/interfaces/freesurfer/preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,10 +729,7 @@ def cmdline(self):
outdir = self._get_outdir()
cmd = []
if not os.path.exists(outdir):
cmdstr = "{} -c \"import os; os.makedirs('{}')\"".format(
op.basename(sys.executable),
outdir,
)
cmdstr = f"{op.basename(sys.executable)} -c \"import os; os.makedirs('{outdir}')\""
cmd.extend([cmdstr])
infofile = os.path.join(outdir, "shortinfo.txt")
if not os.path.exists(infofile):
Expand All @@ -741,12 +738,7 @@ def cmdline(self):
files = self._get_filelist(outdir)
for infile, outfile in files:
if not os.path.exists(outfile):
single_cmd = "{}{} {} {}".format(
self._cmd_prefix,
self.cmd,
infile,
os.path.join(outdir, outfile),
)
single_cmd = f"{self._cmd_prefix}{self.cmd} {infile} {os.path.join(outdir, outfile)}"
cmd.extend([single_cmd])
return "; ".join(cmd)

Expand Down
10 changes: 2 additions & 8 deletions nipype/interfaces/freesurfer/tests/test_preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,7 @@ def test_fitmsparams(create_files_in_directory):
# .inputs based parameters setting
fit.inputs.in_files = filelist
fit.inputs.out_dir = outdir
assert fit.cmdline == "mri_ms_fitparms {} {} {}".format(
filelist[0],
filelist[1],
outdir,
)
assert fit.cmdline == f"mri_ms_fitparms {filelist[0]} {filelist[1]} {outdir}"

# constructor based parameter setting
fit2 = freesurfer.FitMSParams(
Expand Down Expand Up @@ -184,9 +180,7 @@ def test_bbregister(create_files_in_directory):
base, _ = os.path.splitext(base)

assert bbr.cmdline == (
"bbregister --t2 --init-fsl "
"--reg {base}_bbreg_fsaverage.dat "
"--mov {full} --s fsaverage".format(full=filelist[0], base=base)
f"bbregister --t2 --init-fsl --reg {base}_bbreg_fsaverage.dat --mov {filelist[0]} --s fsaverage"
)


Expand Down
5 changes: 1 addition & 4 deletions nipype/interfaces/freesurfer/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,7 @@ def test_mrisexpand(tmpdir):
nd_res = expand_nd.run()

# Commandlines differ
node_cmdline = (
"mris_expand -T 60 -pial {cwd}/lh.pial {cwd}/lh.smoothwm "
"1 expandtmp".format(cwd=nd_res.runtime.cwd)
)
node_cmdline = f"mris_expand -T 60 -pial {nd_res.runtime.cwd}/lh.pial {nd_res.runtime.cwd}/lh.smoothwm 1 expandtmp"
assert nd_res.runtime.cmdline == node_cmdline

# Check output
Expand Down
24 changes: 6 additions & 18 deletions nipype/interfaces/freesurfer/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,7 @@ def _format_arg(self, name, spec, value):
if ext != filemap[value]:
if ext in filemap.values():
raise ValueError(
"Cannot create {} file with extension "
"{}".format(value, ext)
f"Cannot create {value} file with extension {ext}"
)
else:
logger.warning(
Expand Down Expand Up @@ -595,8 +594,7 @@ def _format_arg(self, name, spec, value):
if ext != filemap[value]:
if ext in filemap.values():
raise ValueError(
"Cannot create {} file with extension "
"{}".format(value, ext)
f"Cannot create {value} file with extension {ext}"
)
else:
logger.warning(
Expand Down Expand Up @@ -998,10 +996,8 @@ def _format_arg(self, name, spec, value):
if len(value) == 2:
return "-fminmax %.3f %.3f" % value
else:
return "-fminmax {:.3f} {:.3f} -fmid {:.3f}".format(
value[0],
value[2],
value[1],
return (
f"-fminmax {value[0]:.3f} {value[2]:.3f} -fmid {value[1]:.3f}"
)
elif name == "annot_name" and isdefined(value):
# Matching annot by name needs to strip the leading hemi and trailing
Expand All @@ -1015,11 +1011,7 @@ def _format_arg(self, name, spec, value):

def _run_interface(self, runtime):
if not isdefined(self.inputs.screenshot_stem):
stem = "{}_{}_{}".format(
self.inputs.subject_id,
self.inputs.hemi,
self.inputs.surface,
)
stem = f"{self.inputs.subject_id}_{self.inputs.hemi}_{self.inputs.surface}"
else:
stem = self.inputs.screenshot_stem
stem_args = self.inputs.stem_template_args
Expand Down Expand Up @@ -1085,11 +1077,7 @@ def _write_tcl_script(self):
def _list_outputs(self):
outputs = self._outputs().get()
if not isdefined(self.inputs.screenshot_stem):
stem = "{}_{}_{}".format(
self.inputs.subject_id,
self.inputs.hemi,
self.inputs.surface,
)
stem = f"{self.inputs.subject_id}_{self.inputs.hemi}_{self.inputs.surface}"
else:
stem = self.inputs.screenshot_stem
stem_args = self.inputs.stem_template_args
Expand Down
6 changes: 3 additions & 3 deletions nipype/interfaces/fsl/preprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -1327,9 +1327,9 @@ def _format_arg(self, name, spec, value):
if name == "out_intensitymap_file":
value = self._list_outputs()[name]
value = [FNIRT.intensitymap_file_basename(v) for v in value]
assert len(set(value)) == 1, "Found different basenames for {}: {}".format(
name, value
)
assert (
len(set(value)) == 1
), f"Found different basenames for {name}: {value}"
return spec.argstr % value[0]
if name in list(self.filemap.keys()):
return spec.argstr % self._list_outputs()[name]
Expand Down
8 changes: 2 additions & 6 deletions nipype/interfaces/fsl/tests/test_maths.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,9 +401,7 @@ def test_binarymaths(create_files_in_directory_plus_output_type):
assert maths.cmdline == f"fslmaths a.nii -{op} b.nii c.nii"
else:
maths.inputs.operand_value = ent
assert maths.cmdline == "fslmaths a.nii -{} {:.8f} c.nii".format(
op, ent
)
assert maths.cmdline == f"fslmaths a.nii -{op} {ent:.8f} c.nii"

# Test that we don't need to ask for an out file
for op in ops:
Expand Down Expand Up @@ -461,9 +459,7 @@ def test_tempfilt(create_files_in_directory_plus_output_type):
for win in windows:
filt.inputs.highpass_sigma = win[0]
filt.inputs.lowpass_sigma = win[1]
assert filt.cmdline == "fslmaths a.nii -bptf {:.6f} {:.6f} b.nii".format(
win[0], win[1]
)
assert filt.cmdline == f"fslmaths a.nii -bptf {win[0]:.6f} {win[1]:.6f} b.nii"

# Test that we don't need to ask for an out file
filt = fsl.TemporalFilter(in_file="a.nii", highpass_sigma=64)
Expand Down
Loading

0 comments on commit 1253ce5

Please sign in to comment.