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 24 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
014135c
STY: Apply ruff/flake8-bugbear rule B007
DimitriPapadopoulos Oct 7, 2024
51f712d
STY: Apply ruff/flake8-bugbear rule B015
DimitriPapadopoulos Oct 7, 2024
c17bc9f
STY: Apply ruff/flake8-bugbear rule B018
DimitriPapadopoulos Oct 7, 2024
e3227a4
Apply ruff/pycodestyle rule E741
DimitriPapadopoulos Oct 7, 2024
121695e
STY: Apply ruff/refurb rule FURB154
DimitriPapadopoulos Oct 7, 2024
b429e2d
STY: Apply ruff/Pylint rule PLE0101
DimitriPapadopoulos Oct 7, 2024
00e19f4
STY: Apply ruff/Pylint rule PLE1205
DimitriPapadopoulos Oct 7, 2024
f0b6d58
STY: Apply ruff/flake8-pytest-style rule PT006
DimitriPapadopoulos Oct 7, 2024
990205b
STY: Apply ruff/flake8-pytest-style rule PT007
DimitriPapadopoulos Oct 7, 2024
b068cae
STY: Apply ruff/flake8-pytest-style rule PT014
DimitriPapadopoulos Oct 7, 2024
874b108
STY: Apply ruff/flake8-quotes rule Q000
DimitriPapadopoulos Oct 7, 2024
778ab94
STY: Apply ruff/flake8-quotes rule Q003
DimitriPapadopoulos Oct 7, 2024
7b23137
STY: Apply ruff rule RUF100
DimitriPapadopoulos Oct 7, 2024
adf037f
STY: Apply ruff/pyupgrade rule UP008
DimitriPapadopoulos Oct 7, 2024
c9ee512
STY: Apply ruff/pyupgrade rule UP032
DimitriPapadopoulos Oct 7, 2024
effe909
STY: Enforce ruff rules
DimitriPapadopoulos Oct 7, 2024
a9f97ca
Update ruff to 0.8.0
DimitriPapadopoulos Nov 24, 2024
ac68f1a
STY: Apply ruff/flake8-bugbear rule B010
DimitriPapadopoulos Nov 24, 2024
dd57d7a
STY: Ignore ruff/pycodestyle rule E741 for now
DimitriPapadopoulos Nov 24, 2024
45bc797
STY: Apply ruff/Pyflakes rule F522
DimitriPapadopoulos Nov 24, 2024
92a6ffd
Apply ruff/Pyflakes rule F821
DimitriPapadopoulos Nov 24, 2024
6d7277a
Apply ruff rule RUF100
DimitriPapadopoulos Nov 24, 2024
802475e
Apply ruff/pyupgrade rule UP015
DimitriPapadopoulos Nov 24, 2024
8f84741
Apply ruff/pyupgrade rule UP025
DimitriPapadopoulos Nov 24, 2024
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.8.0
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(
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 @@
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):

Check warning on line 247 in nipype/algorithms/mesh.py

View check run for this annotation

Codecov / codecov/patch

nipype/algorithms/mesh.py#L247

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

Added lines #L623 - L624 were 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#L635-L636

Added lines #L635 - L636 were 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
12 changes: 6 additions & 6 deletions nipype/interfaces/ants/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -1273,7 +1273,7 @@
self.inputs.moving_image_mask,
)
else:
return "--masks %s" % self.inputs.fixed_image_mask
return "--masks {}".format(self.inputs.fixed_image_mask)

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

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1276

Added line #L1276 was not covered by tests
elif opt == "transforms":
return self._format_registration()
elif opt == "initial_moving_transform":
Expand Down Expand Up @@ -1319,7 +1319,9 @@
out_filename,
)
else:
return "--output %s" % self.inputs.output_transform_prefix
return "--output {}".format(

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

View check run for this annotation

Codecov / codecov/patch

nipype/interfaces/ants/registration.py#L1322

Added line #L1322 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 @@ -1610,7 +1612,7 @@
)
else:
retval = '--masks "{fixed_image_mask}"'.format(
fixed_image_mask=self.inputs.fixed_image_mask
fixed_image_mask=self.inputs.fixed_image_mask,
)
return retval

Expand Down Expand Up @@ -1870,9 +1872,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 @@ -142,10 +142,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
14 changes: 7 additions & 7 deletions nipype/interfaces/camino/dti.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ class TrackDT(Track):

def __init__(self, command=None, **inputs):
inputs["inputmodel"] = "dt"
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class TrackPICoInputSpec(TrackInputSpec):
Expand Down Expand Up @@ -973,7 +973,7 @@ class TrackPICo(Track):

def __init__(self, command=None, **inputs):
inputs["inputmodel"] = "pico"
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class TrackBedpostxDeterInputSpec(TrackInputSpec):
Expand Down Expand Up @@ -1023,7 +1023,7 @@ class TrackBedpostxDeter(Track):

def __init__(self, command=None, **inputs):
inputs["inputmodel"] = "bedpostx_dyad"
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class TrackBedpostxProbaInputSpec(TrackInputSpec):
Expand Down Expand Up @@ -1084,7 +1084,7 @@ class TrackBedpostxProba(Track):

def __init__(self, command=None, **inputs):
inputs["inputmodel"] = "bedpostx"
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class TrackBayesDiracInputSpec(TrackInputSpec):
Expand Down Expand Up @@ -1185,7 +1185,7 @@ class TrackBayesDirac(Track):

def __init__(self, command=None, **inputs):
inputs["inputmodel"] = "bayesdirac"
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class TrackBallStick(Track):
Expand All @@ -1204,7 +1204,7 @@ class TrackBallStick(Track):

def __init__(self, command=None, **inputs):
inputs["inputmodel"] = "ballstick"
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class TrackBootstrapInputSpec(TrackInputSpec):
Expand Down Expand Up @@ -1266,7 +1266,7 @@ class TrackBootstrap(Track):
input_spec = TrackBootstrapInputSpec

def __init__(self, command=None, **inputs):
return super().__init__(command, **inputs)
super().__init__(command, **inputs)


class ComputeMeanDiffusivityInputSpec(CommandLineInputSpec):
Expand Down
Loading