Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

STY: Enforce ruff rules #3690

Draft
wants to merge 16 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ repos:
rev: 24.2.0
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.9
hooks:
- id: ruff
args: ["--fix", "--show-source"]
- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
hooks:
Expand Down
4 changes: 2 additions & 2 deletions doc/devel/matlab_example1.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

class ConmapTxt2MatInputSpec(BaseInterfaceInputSpec):
in_file = File(exists=True, mandatory=True)
out_file = File('cmatrix.mat', usedefault=True)
out_file = File("cmatrix.mat", usedefault=True)


class ConmapTxt2MatOutputSpec(TraitedSpec):
Expand Down Expand Up @@ -48,5 +48,5 @@ def _run_interface(self, runtime):

def _list_outputs(self):
outputs = self._outputs().get()
outputs['out_file'] = os.path.abspath(self.inputs.out_file)
outputs["out_file"] = os.path.abspath(self.inputs.out_file)
return outputs
2 changes: 1 addition & 1 deletion doc/devel/matlab_example2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


class HelloWorldInputSpec(MatlabInputSpec):
name = traits.Str(mandatory=True, desc='Name of person to say hello to')
name = traits.Str(mandatory=True, desc="Name of person to say hello to")


class HelloWorldOutputSpec(TraitedSpec):
Expand Down
15 changes: 5 additions & 10 deletions nipype/algorithms/confounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class ComputeDVARSInputSpec(BaseInterfaceInputSpec):
variance_tol = traits.Float(
1e-7,
usedefault=True,
desc="maximum variance to consider \"close to\" zero for the purposes of removal",
desc='maximum variance to consider "close to" zero for the purposes of removal',
)
save_std = traits.Bool(True, usedefault=True, desc="save standardized DVARS")
save_nstd = traits.Bool(False, usedefault=True, desc="save non-standardized DVARS")
Expand Down 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/algorithms/mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def _run_interface(self, runtime):
if self.inputs.weighting == "area":
faces = vtk1.polys.to_array().reshape(-1, 4).astype(int)[:, 1:]

for i, p1 in enumerate(points2):
for i, _ in enumerate(points2):
# compute surfaces, set in weight
w = 0.0
point_faces = faces[(faces[:, :] == i).any(axis=1)]
Expand Down
25 changes: 12 additions & 13 deletions nipype/algorithms/modelgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@
if hasattr(info, "conditions") and info.conditions is not None:
for cid, cond in enumerate(info.conditions):
sessinfo[i]["cond"].insert(cid, dict())
sessinfo[i]["cond"][cid]["name"] = info.conditions[cid]
sessinfo[i]["cond"][cid]["name"] = cond
scaled_onset = scale_timings(
info.onsets[cid],
self.inputs.input_units,
Expand Down Expand Up @@ -434,12 +434,11 @@
sessinfo[i]["regress"][j]["name"] = info.regressor_names[j]
else:
sessinfo[i]["regress"][j]["name"] = "UR%d" % (j + 1)
sessinfo[i]["regress"][j]["val"] = info.regressors[j]
sessinfo[i]["regress"][j]["val"] = r
sessinfo[i]["scans"] = functional_runs[i]

if realignment_parameters is not None:
for i, rp in enumerate(realignment_parameters):
mc = realignment_parameters[i]
for i, mc in enumerate(realignment_parameters):
for col in range(mc.shape[1]):
colidx = len(sessinfo[i]["regress"])
sessinfo[i]["regress"].insert(colidx, dict(name="", val=[]))
Expand Down Expand Up @@ -597,14 +596,14 @@
for i, info in enumerate(infolist[1:]):
# info.[conditions, tmod] remain the same
if info.onsets:
for j, val in enumerate(info.onsets):
for j, onsets in enumerate(info.onsets):
if self.inputs.input_units == "secs":
onsets = np.array(
info.onsets[j]
) + self.inputs.time_repetition * sum(nscans[0 : (i + 1)])
onsets = np.array(onsets) + self.inputs.time_repetition * sum(
nscans[0 : (i + 1)]
)
infoout.onsets[j].extend(onsets.tolist())
else:
onsets = np.array(info.onsets[j]) + sum(nscans[0 : (i + 1)])
onsets = np.array(onsets) + sum(nscans[0 : (i + 1)])

Check warning on line 606 in nipype/algorithms/modelgen.py

View check run for this annotation

Codecov / codecov/patch

nipype/algorithms/modelgen.py#L606

Added line #L606 was not covered by tests
infoout.onsets[j].extend(onsets.tolist())

for j, val in enumerate(info.durations):
Expand All @@ -621,8 +620,8 @@
)

if hasattr(info, "amplitudes") and info.amplitudes:
for j, val in enumerate(info.amplitudes):
infoout.amplitudes[j].extend(info.amplitudes[j])
for j, amplitudes in enumerate(info.amplitudes):
infoout.amplitudes[j].extend(amplitudes)

Check warning on line 624 in nipype/algorithms/modelgen.py

View check run for this annotation

Codecov / codecov/patch

nipype/algorithms/modelgen.py#L624

Added line #L624 was not covered by tests

if hasattr(info, "pmod") and info.pmod:
for j, val in enumerate(info.pmod):
Expand All @@ -633,8 +632,8 @@
if hasattr(info, "regressors") and info.regressors:
# assumes same ordering of regressors across different
# runs and the same names for the regressors
for j, v in enumerate(info.regressors):
infoout.regressors[j].extend(info.regressors[j])
for j, regressors in enumerate(info.regressors):
infoout.regressors[j].extend(regressors)

Check warning on line 636 in nipype/algorithms/modelgen.py

View check run for this annotation

Codecov / codecov/patch

nipype/algorithms/modelgen.py#L636

Added line #L636 was not covered by tests

# insert session regressors
if not hasattr(infoout, "regressors") or not infoout.regressors:
Expand Down
2 changes: 1 addition & 1 deletion nipype/algorithms/tests/test_CompCor.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def close_up_to_column_sign(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):


@pytest.mark.parametrize(
"a, b, close",
("a", "b", "close"),
[
([[0.1, 0.2], [0.3, 0.4]], [[-0.1, 0.2], [-0.3, 0.4]], True),
([[0.1, 0.2], [0.3, 0.4]], [[-0.1, 0.2], [0.3, -0.4]], False),
Expand Down
2 changes: 1 addition & 1 deletion nipype/algorithms/tests/test_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_ActivationCount(tmpdir):


@pytest.mark.parametrize(
"threshold, above_thresh",
("threshold", "above_thresh"),
[
(1, 15.865), # above one standard deviation (one side)
(2, 2.275), # above two standard deviations (one side)
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 @@
return out

def __repr__(self):
return "{}({}.{}), base_dir={})".format(
return "{}({}.{}), base_dir={})".format( # noqa: UP032

Check warning on line 89 in nipype/caching/memory.py

View check run for this annotation

Codecov / codecov/patch

nipype/caching/memory.py#L89

Added line #L89 was not covered by tests
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 @@
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 @@
)
)
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 _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

Check warning on line 1272 in nipype/interfaces/ants/registration.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1272

Added line #L1272 was not covered by tests
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

Check warning on line 1277 in nipype/interfaces/ants/registration.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1277

Added line #L1277 was not covered by tests
elif opt == "transforms":
return self._format_registration()
elif opt == "initial_moving_transform":
Expand Down Expand Up @@ -1309,18 +1309,20 @@
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

Check warning on line 1312 in nipype/interfaces/ants/registration.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1312

Added line #L1312 was not covered by tests
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

Check warning on line 1323 in nipype/interfaces/ants/registration.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1323

Added line #L1323 was not covered by tests
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 @@
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 _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

Check warning on line 1615 in nipype/interfaces/ants/registration.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1615

Added line #L1615 was not covered by tests
fixed_image_mask=self.inputs.fixed_image_mask,
)
return retval

Expand Down Expand Up @@ -1871,9 +1873,7 @@
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
2 changes: 1 addition & 1 deletion nipype/interfaces/ants/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
# fmt: on


@pytest.mark.parametrize("raw_info, version", ANTS_VERSIONS)
@pytest.mark.parametrize(("raw_info", "version"), ANTS_VERSIONS)
def test_version_parser(raw_info, version):
assert Info.parse_version(raw_info) == version
2 changes: 1 addition & 1 deletion nipype/interfaces/ants/tests/test_resampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,4 @@ def test_WarpTimeSeriesImageMultiTransform_invaffine_wrong(change_dir, create_wt
wtsimt = create_wtsimt
wtsimt.inputs.invert_affine = [0]
with pytest.raises(Exception):
wtsimt.cmdline
wtsimt.cmdline # noqa: B018
8 changes: 4 additions & 4 deletions nipype/interfaces/ants/tests/test_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,20 @@ def test_LaplacianThickness_wrongargs(change_dir, create_lt):
with pytest.raises(
ValueError, match=r".* requires a value for input 'sulcus_prior' .*"
):
lt.cmdline
lt.cmdline # noqa: B018
lt.inputs.sulcus_prior = 0.15
with pytest.raises(ValueError, match=r".* requires a value for input 'dT' .*"):
lt.cmdline
lt.cmdline # noqa: B018
lt.inputs.dT = 0.01
with pytest.raises(
ValueError, match=r".* requires a value for input 'prior_thickness' .*"
):
lt.cmdline
lt.cmdline # noqa: B018
lt.inputs.prior_thickness = 5.9
with pytest.raises(
ValueError, match=r".* requires a value for input 'smooth_param' .*"
):
lt.cmdline
lt.cmdline # noqa: B018
lt.inputs.smooth_param = 4.5
assert (
lt.cmdline == "LaplacianThickness functional.nii diffusion_weighted.nii "
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
6 changes: 3 additions & 3 deletions nipype/interfaces/base/tests/test_specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@
a.foo = 1
assign_a = lambda: setattr(a, "foo", "a")
with pytest.raises(Exception):
assign_a
assign_a()

Check warning on line 74 in nipype/interfaces/base/tests/test_specs.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/base/tests/test_specs.py#L74

Added line #L74 was not covered by tests
pkld_a = dumps(a)
unpkld_a = loads(pkld_a)
assign_a_again = lambda: setattr(unpkld_a, "foo", "a")
with pytest.raises(Exception):
assign_a_again
assign_a_again()

Check warning on line 79 in nipype/interfaces/base/tests/test_specs.py

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/base/tests/test_specs.py#L79

Added line #L79 was not covered by tests


def test_DynamicTraitedSpec_tab_completion():
Expand Down Expand Up @@ -276,7 +276,7 @@
to0 = TestCycle()
not_raised = True
try:
to0.cmdline
to0.cmdline # noqa: B018
except nib.NipypeInterfaceError:
not_raised = False
assert not not_raised
Expand Down
Loading