From eb1d4882187052af932fd847c0e0d084bb016999 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 12:33:33 +0200 Subject: [PATCH 1/8] STY: Apply ruff/flake8-simplify rule SIM101 SIM101 Multiple `isinstance` calls for expression, merge into a single call --- nipype/interfaces/base/specs.py | 8 ++------ nipype/interfaces/slicer/generate_classes.py | 4 ++-- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/nipype/interfaces/base/specs.py b/nipype/interfaces/base/specs.py index 2d7a6018b9..4255c555c4 100644 --- a/nipype/interfaces/base/specs.py +++ b/nipype/interfaces/base/specs.py @@ -177,7 +177,7 @@ def get_traitsfree(self, **kwargs): def _clean_container(self, objekt, undefinedval=None, skipundefined=False): """Convert a traited object into a pure python representation.""" - if isinstance(objekt, TraitDictObject) or isinstance(objekt, dict): + if isinstance(objekt, (TraitDictObject, dict)): out = {} for key, val in list(objekt.items()): if isdefined(val): @@ -185,11 +185,7 @@ def _clean_container(self, objekt, undefinedval=None, skipundefined=False): else: if not skipundefined: out[key] = undefinedval - elif ( - isinstance(objekt, TraitListObject) - or isinstance(objekt, list) - or isinstance(objekt, tuple) - ): + elif isinstance(objekt, (TraitListObject, list, tuple)): out = [] for val in objekt: if isdefined(val): diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index 20ed8e9f21..8f20961086 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -54,7 +54,7 @@ def add_class_to_package(class_codes, class_names, module_name, package_dir): def crawl_code_struct(code_struct, package_dir): subpackages = [] for k, v in code_struct.items(): - if isinstance(v, str) or isinstance(v, (str, bytes)): + if isinstance(v, (str, bytes)): module_name = k.lower() class_name = k class_code = v @@ -63,7 +63,7 @@ def crawl_code_struct(code_struct, package_dir): l1 = {} l2 = {} for key in list(v.keys()): - if isinstance(v[key], str) or isinstance(v[key], (str, bytes)): + if isinstance(v[key], (str, bytes)): l1[key] = v[key] else: l2[key] = v[key] From 01c3e76ff78012d5ff1f6e5a1f6b9ee78699a487 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 12:47:15 +0200 Subject: [PATCH 2/8] STY: Apply ruff/flake8-simplify rule SIM103 SIM103 Return the condition directly --- nipype/interfaces/afni/base.py | 4 +--- nipype/interfaces/freesurfer/base.py | 5 +---- nipype/interfaces/fsl/base.py | 5 +---- nipype/interfaces/spm/base.py | 10 ++-------- nipype/pipeline/plugins/condor.py | 4 +--- nipype/pipeline/plugins/lsf.py | 7 +++---- nipype/utils/misc.py | 7 +------ 7 files changed, 10 insertions(+), 32 deletions(-) diff --git a/nipype/interfaces/afni/base.py b/nipype/interfaces/afni/base.py index 5c36ed5f61..e883b22c6e 100644 --- a/nipype/interfaces/afni/base.py +++ b/nipype/interfaces/afni/base.py @@ -326,6 +326,4 @@ def _cmd_prefix(self): def no_afni(): """Check whether AFNI is not available.""" - if Info.version() is None: - return True - return False + return Info.version() is None diff --git a/nipype/interfaces/freesurfer/base.py b/nipype/interfaces/freesurfer/base.py index 0baedd4b82..c84fc78cd5 100644 --- a/nipype/interfaces/freesurfer/base.py +++ b/nipype/interfaces/freesurfer/base.py @@ -269,7 +269,4 @@ def no_freesurfer(): used with skipif to skip tests that will fail if FreeSurfer is not installed""" - if Info.version() is None: - return True - else: - return False + return Info.version() is None diff --git a/nipype/interfaces/fsl/base.py b/nipype/interfaces/fsl/base.py index cae9783362..7be822e4f2 100644 --- a/nipype/interfaces/fsl/base.py +++ b/nipype/interfaces/fsl/base.py @@ -262,10 +262,7 @@ def no_fsl(): used with skipif to skip tests that will fail if FSL is not installed""" - if Info.version() is None: - return True - else: - return False + return Info.version() is None def no_fsl_course_data(): diff --git a/nipype/interfaces/spm/base.py b/nipype/interfaces/spm/base.py index 9c653bb266..ac20682696 100644 --- a/nipype/interfaces/spm/base.py +++ b/nipype/interfaces/spm/base.py @@ -52,10 +52,7 @@ def func_is_3d(in_file): else: img = load(in_file) shape = img.shape - if len(shape) == 3 or (len(shape) == 4 and shape[3] == 1): - return True - else: - return False + return len(shape) == 3 or len(shape) == 4 and shape[3] == 1 def get_first_3dfile(in_files): @@ -254,10 +251,7 @@ def no_spm(): used with pytest.mark.skipif decorator to skip tests that will fail if spm is not installed""" - if "NIPYPE_NO_MATLAB" in os.environ or Info.version() is None: - return True - else: - return False + return "NIPYPE_NO_MATLAB" in os.environ or Info.version() is None class SPMCommandInputSpec(BaseInterfaceInputSpec): diff --git a/nipype/pipeline/plugins/condor.py b/nipype/pipeline/plugins/condor.py index 6ebd080e61..0fff477377 100644 --- a/nipype/pipeline/plugins/condor.py +++ b/nipype/pipeline/plugins/condor.py @@ -55,9 +55,7 @@ def _is_pending(self, taskid): iflogger.setLevel(logging.getLevelName("CRITICAL")) result = cmd.run(ignore_exception=True) iflogger.setLevel(oldlevel) - if result.runtime.stdout.count("\n%d" % taskid): - return True - return False + return bool(result.runtime.stdout.count("\n%d" % taskid)) def _submit_batchtask(self, scriptfile, node): cmd = CommandLine( diff --git a/nipype/pipeline/plugins/lsf.py b/nipype/pipeline/plugins/lsf.py index d2753a264c..cf334be051 100644 --- a/nipype/pipeline/plugins/lsf.py +++ b/nipype/pipeline/plugins/lsf.py @@ -54,10 +54,9 @@ def _is_pending(self, taskid): result = cmd.run(ignore_exception=True) iflogger.setLevel(oldlevel) # logger.debug(result.runtime.stdout) - if "DONE" in result.runtime.stdout or "EXIT" in result.runtime.stdout: - return False - else: - return True + return ( + "DONE" not in result.runtime.stdout and "EXIT" not in result.runtime.stdout + ) def _submit_batchtask(self, scriptfile, node): cmd = CommandLine( diff --git a/nipype/utils/misc.py b/nipype/utils/misc.py index 95f4b408c2..dc76a433bc 100644 --- a/nipype/utils/misc.py +++ b/nipype/utils/misc.py @@ -87,12 +87,7 @@ def is_container(item): True if container False if not (eg string) """ - if isinstance(item, str): - return False - elif hasattr(item, "__iter__"): - return True - else: - return False + return not isinstance(item, str) and hasattr(item, "__iter__") def container_to_string(cont): From 4b88c39cfa9a2d3ece03e1121b612ca35b917cce Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 12:49:32 +0200 Subject: [PATCH 3/8] STY: Apply ruff/flake8-simplify rule SIM113 SIM113 Use `enumerate()` for index variable in `for` loop --- nipype/pipeline/engine/utils.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/nipype/pipeline/engine/utils.py b/nipype/pipeline/engine/utils.py index 3601290cd9..9c53938cb5 100644 --- a/nipype/pipeline/engine/utils.py +++ b/nipype/pipeline/engine/utils.py @@ -1709,13 +1709,11 @@ def topological_sort(graph, depth_first=False): logger.debug("Performing depth first search") nodes = [] groups = [] - group = 0 G = nx.Graph() G.add_nodes_from(graph.nodes()) G.add_edges_from(graph.edges()) components = nx.connected_components(G) - for desc in components: - group += 1 + for group, desc in enumerate(components, start=1): indices = [nodesort.index(node) for node in desc] nodes.extend( np.array(nodesort)[np.array(indices)[np.argsort(indices)]].tolist() From d294476c7b43deed1dbf0cdd089eb89d54283117 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 13:08:22 +0200 Subject: [PATCH 4/8] STY: Apply ruff/flake8-simplify rule SIM115 SIM115 Use a context manager for opening files --- nipype/interfaces/fsl/model.py | 33 ++++++------- nipype/interfaces/nitime/analysis.py | 23 ++++----- nipype/interfaces/slicer/generate_classes.py | 50 ++++++++++---------- tools/checkspecs.py | 6 +-- 4 files changed, 50 insertions(+), 62 deletions(-) diff --git a/nipype/interfaces/fsl/model.py b/nipype/interfaces/fsl/model.py index 70ce3d7439..da2a979992 100644 --- a/nipype/interfaces/fsl/model.py +++ b/nipype/interfaces/fsl/model.py @@ -142,13 +142,12 @@ class Level1Design(BaseInterface): output_spec = Level1DesignOutputSpec def _create_ev_file(self, evfname, evinfo): - f = open(evfname, "w") - for i in evinfo: - if len(i) == 3: - f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n") - else: - f.write("%f\n" % i[0]) - f.close() + with open(evfname, "w") as f: + for i in evinfo: + if len(i) == 3: + f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n") + else: + f.write("%f\n" % i[0]) def _create_ev_files( self, @@ -403,9 +402,8 @@ def _run_interface(self, runtime): fsf_txt += cond_txt fsf_txt += fsf_postscript.substitute(overwrite=1) - f = open(os.path.join(cwd, "run%d.fsf" % i), "w") - f.write(fsf_txt) - f.close() + with open(os.path.join(cwd, "run%d.fsf" % i), "w") as f: + f.write(fsf_txt) return runtime @@ -946,9 +944,8 @@ def _run_interface(self, runtime): for i, rundir in enumerate(ensure_list(self.inputs.feat_dirs)): fsf_txt += fsf_dirs.substitute(runno=i + 1, rundir=os.path.abspath(rundir)) fsf_txt += fsf_footer.substitute() - f = open(os.path.join(os.getcwd(), "register.fsf"), "w") - f.write(fsf_txt) - f.close() + with open(os.path.join(os.getcwd(), "register.fsf"), "w") as f: + f.write(fsf_txt) return runtime @@ -1414,9 +1411,8 @@ def _run_interface(self, runtime): # write design files for i, name in enumerate(["design.mat", "design.con", "design.grp"]): - f = open(os.path.join(cwd, name), "w") - f.write(txt[name]) - f.close() + with open(os.path.join(cwd, name), "w") as f: + f.write(txt[name]) return runtime @@ -1583,9 +1579,8 @@ def _run_interface(self, runtime): if ("fts" in key) and (nfcons == 0): continue filename = key.replace("_", ".") - f = open(os.path.join(cwd, filename), "w") - f.write(val) - f.close() + with open(os.path.join(cwd, filename), "w") as f: + f.write(val) return runtime diff --git a/nipype/interfaces/nitime/analysis.py b/nipype/interfaces/nitime/analysis.py index 351b981077..7c936e4b03 100644 --- a/nipype/interfaces/nitime/analysis.py +++ b/nipype/interfaces/nitime/analysis.py @@ -142,15 +142,13 @@ def _read_csv(self): """ # Check that input conforms to expectations: - first_row = open(self.inputs.in_file).readline() + with open(self.inputs.in_file) as f: + first_row = f.readline() if not first_row[1].isalpha(): raise ValueError( "First row of in_file should contain ROI names as strings of characters" ) - - roi_names = ( - open(self.inputs.in_file).readline().replace('"', "").strip("\n").split(",") - ) + roi_names = first_row.replace('"', "").strip("\n").split(",") # Transpose, so that the time is the last dimension: data = np.loadtxt(self.inputs.in_file, skiprows=1, delimiter=",").T @@ -255,16 +253,15 @@ def _make_output_files(self): tmp_f = tempfile.mkstemp()[1] np.savetxt(tmp_f, this[0], delimiter=",") - fid = open( + with open( fname_presuffix(self.inputs.output_csv_file, suffix="_%s" % this[1]), "w+", - ) - # this writes ROIs as header line - fid.write("," + ",".join(self.ROIs) + "\n") - # this writes ROI and data to a line - for r, line in zip(self.ROIs, open(tmp_f)): - fid.write(f"{r},{line}") - fid.close() + ) as fid: + # this writes ROIs as header line + fid.write("," + ",".join(self.ROIs) + "\n") + # this writes ROI and data to a line + for r, line in zip(self.ROIs, open(tmp_f)): + fid.write(f"{r},{line}") def _make_output_figures(self): """ diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index 8f20961086..b5a68d27a6 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -33,22 +33,22 @@ def force_to_valid_python_variable_name(old_name): def add_class_to_package(class_codes, class_names, module_name, package_dir): module_python_filename = os.path.join(package_dir, "%s.py" % module_name) - f_m = open(module_python_filename, "w") - f_i = open(os.path.join(package_dir, "__init__.py"), "a+") - f_m.write( - """# -*- coding: utf-8 -*- + with ( + open(module_python_filename, "w") as f_m, + open(os.path.join(package_dir, "__init__.py"), "a+") as f_i, + ): + f_m.write( + """# -*- coding: utf-8 -*- \"\"\"Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.\"\"\"\n\n""" - ) - imports = """\ + ) + imports = """\ from ..base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath) import os\n\n\n""" - f_m.write(imports) - f_m.write("\n\n".join(class_codes)) - f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names))) - f_m.close() - f_i.close() + f_m.write(imports) + f_m.write("\n\n".join(class_codes)) + f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names))) def crawl_code_struct(code_struct, package_dir): @@ -70,9 +70,8 @@ def crawl_code_struct(code_struct, package_dir): if l2: v = l2 subpackages.append(k.lower()) - f_i = open(os.path.join(package_dir, "__init__.py"), "a+") - f_i.write("from %s import *\n" % k.lower()) - f_i.close() + with open(os.path.join(package_dir, "__init__.py"), "a+") as f_i: + f_i.write("from %s import *\n" % k.lower()) new_pkg_dir = os.path.join(package_dir, k.lower()) if os.path.exists(new_pkg_dir): rmtree(new_pkg_dir) @@ -88,9 +87,9 @@ def crawl_code_struct(code_struct, package_dir): list(v.values()), list(v.keys()), module_name, package_dir ) if subpackages: - f = open(os.path.join(package_dir, "setup.py"), "w") - f.write( - """# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- + with open(os.path.join(package_dir, "setup.py"), "w") as f: + f.write( + """# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration @@ -105,16 +104,15 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) """.format( - pkg_name=package_dir.split("/")[-1], - sub_pks="\n ".join( - [ - "config.add_data_dir('%s')" % sub_pkg - for sub_pkg in subpackages - ] - ), + pkg_name=package_dir.split("/")[-1], + sub_pks="\n ".join( + [ + "config.add_data_dir('%s')" % sub_pkg + for sub_pkg in subpackages + ] + ), + ) ) - ) - f.close() def generate_all_classes( diff --git a/tools/checkspecs.py b/tools/checkspecs.py index ea3d877484..42e6d03f88 100644 --- a/tools/checkspecs.py +++ b/tools/checkspecs.py @@ -124,10 +124,8 @@ def _parse_module(self, uri): if filename is None: # nothing that we could handle here. return ([], []) - f = open(filename) - functions, classes = self._parse_lines(f, uri) - f.close() - return functions, classes + with open(filename) as f: + return self._parse_lines(f, uri) def _parse_lines(self, linesource, module): """Parse lines of text for functions and classes""" From 697297b178b60d2ee58937b7287e057347535137 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 13:10:51 +0200 Subject: [PATCH 5/8] STY: Apply ruff/flake8-simplify rule SIM118 SIM118 Use `key in dict` instead of `key in dict.keys()` --- nipype/interfaces/afni/model.py | 4 ++-- nipype/interfaces/afni/utils.py | 2 +- nipype/interfaces/base/specs.py | 2 +- nipype/interfaces/dipy/tests/test_base.py | 16 ++++++++-------- nipype/interfaces/fsl/model.py | 2 +- nipype/interfaces/fsl/tests/test_base.py | 2 +- nipype/interfaces/spm/model.py | 6 +++--- nipype/utils/draw_gantt_chart.py | 4 ++-- 8 files changed, 19 insertions(+), 19 deletions(-) diff --git a/nipype/interfaces/afni/model.py b/nipype/interfaces/afni/model.py index 88c4ba716c..a227e90867 100644 --- a/nipype/interfaces/afni/model.py +++ b/nipype/interfaces/afni/model.py @@ -636,7 +636,7 @@ def _parse_inputs(self, skip=None): def _list_outputs(self): outputs = self.output_spec().get() - for key in outputs.keys(): + for key in outputs: if isdefined(self.inputs.get()[key]): outputs[key] = os.path.abspath(self.inputs.get()[key]) @@ -722,7 +722,7 @@ class Synthesize(AFNICommand): def _list_outputs(self): outputs = self.output_spec().get() - for key in outputs.keys(): + for key in outputs: if isdefined(self.inputs.get()[key]): outputs[key] = os.path.abspath(self.inputs.get()[key]) diff --git a/nipype/interfaces/afni/utils.py b/nipype/interfaces/afni/utils.py index ab528f3bae..2426010ffb 100644 --- a/nipype/interfaces/afni/utils.py +++ b/nipype/interfaces/afni/utils.py @@ -234,7 +234,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): m = re.search(pattern, line) if m: d = m.groupdict() - outputs.trait_set(**{k: int(d[k]) for k in d.keys()}) + outputs.trait_set(**{k: int(d[k]) for k in d}) return outputs diff --git a/nipype/interfaces/base/specs.py b/nipype/interfaces/base/specs.py index 4255c555c4..a7f61e6889 100644 --- a/nipype/interfaces/base/specs.py +++ b/nipype/interfaces/base/specs.py @@ -383,7 +383,7 @@ def __deepcopy__(self, memo): dup_dict = deepcopy(self.trait_get(), memo) # access all keys for key in self.copyable_trait_names(): - if key in self.__dict__.keys(): + if key in self.__dict__: _ = getattr(self, key) # clone once dup = self.clone_traits(memo=memo) diff --git a/nipype/interfaces/dipy/tests/test_base.py b/nipype/interfaces/dipy/tests/test_base.py index 896d477ed6..d2d81ec005 100644 --- a/nipype/interfaces/dipy/tests/test_base.py +++ b/nipype/interfaces/dipy/tests/test_base.py @@ -109,10 +109,10 @@ def test_create_interface_specs(): assert new_interface.__name__ == "MyInterface" current_params = new_interface().get() assert len(current_params) == 4 - assert "params1" in current_params.keys() - assert "params2_files" in current_params.keys() - assert "params3" in current_params.keys() - assert "out_params" in current_params.keys() + assert "params1" in current_params + assert "params2_files" in current_params + assert "params3" in current_params + assert "out_params" in current_params @pytest.mark.skipif( @@ -184,10 +184,10 @@ def run(self, in_files, param1=1, out_dir="", out_ref="out1.txt"): params_in = new_specs().inputs.get() params_out = new_specs()._outputs().get() assert len(params_in) == 4 - assert "in_files" in params_in.keys() - assert "param1" in params_in.keys() - assert "out_dir" in params_out.keys() - assert "out_ref" in params_out.keys() + assert "in_files" in params_in + assert "param1" in params_in + assert "out_dir" in params_out + assert "out_ref" in params_out with pytest.raises(ValueError): new_specs().run() diff --git a/nipype/interfaces/fsl/model.py b/nipype/interfaces/fsl/model.py index da2a979992..82601f1d72 100644 --- a/nipype/interfaces/fsl/model.py +++ b/nipype/interfaces/fsl/model.py @@ -318,7 +318,7 @@ def _create_ev_files( for fconidx in ftest_idx: fval = 0 - if con[0] in con_map.keys() and fconidx in con_map[con[0]]: + if con[0] in con_map and fconidx in con_map[con[0]]: fval = 1 ev_txt += contrast_ftest_element.substitute( cnum=ftest_idx.index(fconidx) + 1, diff --git a/nipype/interfaces/fsl/tests/test_base.py b/nipype/interfaces/fsl/tests/test_base.py index c1cc56fc36..d87bc73d70 100644 --- a/nipype/interfaces/fsl/tests/test_base.py +++ b/nipype/interfaces/fsl/tests/test_base.py @@ -79,7 +79,7 @@ def test_gen_fname(args, desired_name): cmd = fsl.FSLCommand(command="junk", output_type="NIFTI_GZ") pth = os.getcwd() fname = cmd._gen_fname("foo.nii.gz", **args) - if "dir" in desired_name.keys(): + if "dir" in desired_name: desired = os.path.join(desired_name["dir"], desired_name["file"]) else: desired = os.path.join(pth, desired_name["file"]) diff --git a/nipype/interfaces/spm/model.py b/nipype/interfaces/spm/model.py index 62bf4447ea..8bc38a1f02 100644 --- a/nipype/interfaces/spm/model.py +++ b/nipype/interfaces/spm/model.py @@ -322,8 +322,8 @@ def _list_outputs(self): betas = [vbeta.fname[0] for vbeta in spm["SPM"][0, 0].Vbeta[0]] if ( - "Bayesian" in self.inputs.estimation_method.keys() - or "Bayesian2" in self.inputs.estimation_method.keys() + "Bayesian" in self.inputs.estimation_method + or "Bayesian2" in self.inputs.estimation_method ): outputs["labels"] = os.path.join(pth, f"labels.{outtype}") outputs["SDerror"] = glob(os.path.join(pth, "Sess*_SDerror*")) @@ -332,7 +332,7 @@ def _list_outputs(self): outputs["Cbetas"] = [os.path.join(pth, f"C{beta}") for beta in betas] outputs["SDbetas"] = [os.path.join(pth, f"SD{beta}") for beta in betas] - if "Classical" in self.inputs.estimation_method.keys(): + if "Classical" in self.inputs.estimation_method: outputs["residual_image"] = os.path.join(pth, f"ResMS.{outtype}") outputs["RPVimage"] = os.path.join(pth, f"RPV.{outtype}") if self.inputs.write_residuals: diff --git a/nipype/utils/draw_gantt_chart.py b/nipype/utils/draw_gantt_chart.py index 79af8262ac..ef4ec58ec2 100644 --- a/nipype/utils/draw_gantt_chart.py +++ b/nipype/utils/draw_gantt_chart.py @@ -114,9 +114,9 @@ def _convert_string_to_datetime(datestring): date_object_node_list: list = list() for n in nodes_list: - if "start" in n.keys(): + if "start" in n: n["start"] = _convert_string_to_datetime(n["start"]) - if "finish" in n.keys(): + if "finish" in n: n["finish"] = _convert_string_to_datetime(n["finish"]) date_object_node_list.append(n) From d557f71d3de73650f3eecdfd67a6ebbc7d401a6d Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 13:13:07 +0200 Subject: [PATCH 6/8] STY: Apply ruff/flake8-simplify rule SIM201 SIM201 Use `... != ...` instead of `not ... == ...` --- nipype/algorithms/misc.py | 8 ++++---- nipype/interfaces/cmtk/cmtk.py | 12 ++++++------ nipype/interfaces/cmtk/convert.py | 14 +++++++------- nipype/interfaces/cmtk/nx.py | 8 ++++---- nipype/interfaces/dcmstack.py | 2 +- nipype/interfaces/io.py | 4 ++-- nipype/interfaces/mne/base.py | 2 +- nipype/interfaces/mrtrix/convert.py | 2 +- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/nipype/algorithms/misc.py b/nipype/algorithms/misc.py index b7bbd3ce21..8d2e406793 100644 --- a/nipype/algorithms/misc.py +++ b/nipype/algorithms/misc.py @@ -684,7 +684,7 @@ def _run_interface(self, runtime): output_array = merge_csvs(self.inputs.in_files) _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) @@ -725,7 +725,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) outputs["csv_file"] = out_file @@ -771,7 +771,7 @@ class AddCSVColumn(BaseInterface): def _run_interface(self, runtime): in_file = open(self.inputs.in_file) _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) @@ -791,7 +791,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) outputs["csv_file"] = out_file diff --git a/nipype/interfaces/cmtk/cmtk.py b/nipype/interfaces/cmtk/cmtk.py index baf1bccaae..c620941c3d 100644 --- a/nipype/interfaces/cmtk/cmtk.py +++ b/nipype/interfaces/cmtk/cmtk.py @@ -77,7 +77,7 @@ def get_rois_crossed(pointsmm, roiData, voxelSize): x = int(pointsmm[j, 0] / float(voxelSize[0])) y = int(pointsmm[j, 1] / float(voxelSize[1])) z = int(pointsmm[j, 2] / float(voxelSize[2])) - if not roiData[x, y, z] == 0: + if roiData[x, y, z] != 0: rois_crossed.append(roiData[x, y, z]) rois_crossed = list( dict.fromkeys(rois_crossed).keys() @@ -91,7 +91,7 @@ def get_connectivity_matrix(n_rois, list_of_roi_crossed_lists): for idx_i, roi_i in enumerate(rois_crossed): for idx_j, roi_j in enumerate(rois_crossed): if idx_i > idx_j: - if not roi_i == roi_j: + if roi_i != roi_j: connectivity_matrix[roi_i - 1, roi_j - 1] += 1 connectivity_matrix = connectivity_matrix + connectivity_matrix.T return connectivity_matrix @@ -371,7 +371,7 @@ def cmat( di["fiber_length_mean"] = 0 di["fiber_length_median"] = 0 di["fiber_length_std"] = 0 - if not u == v: # Fix for self loop problem + if u != v: # Fix for self loop problem G.add_edge(u, v, **di) if "fiblist" in d: numfib.add_edge(u, v, weight=di["number_of_fibers"]) @@ -400,7 +400,7 @@ def cmat( pickle.dump(I, f, pickle.HIGHEST_PROTOCOL) path, name, ext = split_filename(matrix_mat_name) - if not ext == ".mat": + if ext != ".mat": ext = ".mat" matrix_mat_name = matrix_mat_name + ext @@ -608,7 +608,7 @@ def _run_interface(self, runtime): matrix_mat_file = op.abspath(self.inputs.out_matrix_mat_file) path, name, ext = split_filename(matrix_mat_file) - if not ext == ".mat": + if ext != ".mat": ext = ".mat" matrix_mat_file = matrix_mat_file + ext @@ -673,7 +673,7 @@ def _list_outputs(self): matrix_mat_file = op.abspath(self.inputs.out_matrix_mat_file) path, name, ext = split_filename(matrix_mat_file) - if not ext == ".mat": + if ext != ".mat": ext = ".mat" matrix_mat_file = matrix_mat_file + ext diff --git a/nipype/interfaces/cmtk/convert.py b/nipype/interfaces/cmtk/convert.py index 72d105b715..4f55242a94 100644 --- a/nipype/interfaces/cmtk/convert.py +++ b/nipype/interfaces/cmtk/convert.py @@ -194,17 +194,17 @@ def _run_interface(self, runtime): for data in self.inputs.data_files: _, data_name, _ = split_filename(data) cda = cf.CData(name=data_name, src=data, fileformat="NumPy") - if not string.find(data_name, "lengths") == -1: + if string.find(data_name, 'lengths') != -1: cda.dtype = "FinalFiberLengthArray" - if not string.find(data_name, "endpoints") == -1: + if string.find(data_name, 'endpoints') != -1: cda.dtype = "FiberEndpoints" - if not string.find(data_name, "labels") == -1: + if string.find(data_name, 'labels') != -1: cda.dtype = "FinalFiberLabels" a.add_connectome_data(cda) a.print_summary() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" cf.save_to_cff(a, op.abspath(name + ext)) @@ -213,7 +213,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" outputs["connectome_file"] = op.abspath(name + ext) return outputs @@ -281,7 +281,7 @@ def _run_interface(self, runtime): metadata.set_email("My Email") _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" cf.save_to_cff(newcon, op.abspath(name + ext)) @@ -290,7 +290,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" outputs["connectome_file"] = op.abspath(name + ext) return outputs diff --git a/nipype/interfaces/cmtk/nx.py b/nipype/interfaces/cmtk/nx.py index 7a9e2f9d8a..164009541e 100644 --- a/nipype/interfaces/cmtk/nx.py +++ b/nipype/interfaces/cmtk/nx.py @@ -167,7 +167,7 @@ def average_networks(in_files, ntwk_res_file, group_id): data = ntwk.edge[edge[0]][edge[1]] if ntwk.edge[edge[0]][edge[1]]["count"] >= count_to_keep_edge: for key in list(data.keys()): - if not key == "count": + if key != "count": data[key] = data[key] / len(in_files) ntwk.edge[edge[0]][edge[1]] = data avg_ntwk.add_edge(edge[0], edge[1], **data) @@ -184,7 +184,7 @@ def average_networks(in_files, ntwk_res_file, group_id): for edge in avg_edges: data = avg_ntwk.edge[edge[0]][edge[1]] for key in list(data.keys()): - if not key == "count": + if key != "count": edge_dict[key] = np.zeros( (avg_ntwk.number_of_nodes(), avg_ntwk.number_of_nodes()) ) @@ -342,7 +342,7 @@ def add_node_data(node_array, ntwk): node_ntwk = nx.Graph() newdata = {} for idx, data in ntwk.nodes(data=True): - if not int(idx) == 0: + if int(idx) != 0: newdata["value"] = node_array[int(idx) - 1] data.update(newdata) node_ntwk.add_node(int(idx), **data) @@ -354,7 +354,7 @@ def add_edge_data(edge_array, ntwk, above=0, below=0): data = {} for x, row in enumerate(edge_array): for y in range(np.max(np.shape(edge_array[x]))): - if not edge_array[x, y] == 0: + if edge_array[x, y] != 0: data["value"] = edge_array[x, y] if data["value"] <= below or data["value"] >= above: if edge_ntwk.has_edge(x + 1, y + 1): diff --git a/nipype/interfaces/dcmstack.py b/nipype/interfaces/dcmstack.py index b76255ab84..8e9b8feb42 100644 --- a/nipype/interfaces/dcmstack.py +++ b/nipype/interfaces/dcmstack.py @@ -152,7 +152,7 @@ def _run_interface(self, runtime): meta_filter = dcmstack.make_key_regex_filter(exclude_regexes, include_regexes) stack = dcmstack.DicomStack(meta_filter=meta_filter) for src_path in src_paths: - if not imghdr.what(src_path) == "gif": + if imghdr.what(src_path) != "gif": src_dcm = pydicom.dcmread(src_path, force=self.inputs.force_read) stack.add_dcm(src_dcm) nii = stack.to_nifti(embed_meta=True) diff --git a/nipype/interfaces/io.py b/nipype/interfaces/io.py index 34dbc1b461..606122021e 100644 --- a/nipype/interfaces/io.py +++ b/nipype/interfaces/io.py @@ -1053,9 +1053,9 @@ def s3tolocal(self, s3path, bkt): local_directory = str(self.inputs.local_directory) bucket_path = str(self.inputs.bucket_path) template = str(self.inputs.template) - if not os.path.basename(local_directory) == "": + if os.path.basename(local_directory) != "": local_directory += "/" - if not os.path.basename(bucket_path) == "": + if os.path.basename(bucket_path) != "": bucket_path += "/" if template[0] == "/": template = template[1:] diff --git a/nipype/interfaces/mne/base.py b/nipype/interfaces/mne/base.py index 6e9b766305..c8b1f6012d 100644 --- a/nipype/interfaces/mne/base.py +++ b/nipype/interfaces/mne/base.py @@ -138,7 +138,7 @@ def _list_outputs(self): else: raise TypeError outputs[k] = out_files - if not k.rfind("surface") == -1: + if k.rfind("surface") != -1: mesh_paths.append(out_files) outputs["mesh_files"] = mesh_paths return outputs diff --git a/nipype/interfaces/mrtrix/convert.py b/nipype/interfaces/mrtrix/convert.py index 8a0e14d3eb..f47bc0eff2 100644 --- a/nipype/interfaces/mrtrix/convert.py +++ b/nipype/interfaces/mrtrix/convert.py @@ -116,7 +116,7 @@ def track_gen(track_points): pts_str = fileobj.read(n_pts * bytesize) nan_str = fileobj.read(bytesize) if len(pts_str) < (n_pts * bytesize): - if not n_streams == stream_count: + if n_streams != stream_count: raise nb.trackvis.HeaderError( f"Expecting {stream_count} points, found only {n_streams}" ) From 5f200ce21080dd8af9edab0d03e8be80b1a4c3ea Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 22 Sep 2024 13:14:28 +0200 Subject: [PATCH 7/8] STY: Apply ruff/flake8-simplify rule SIM401 SIM401 Use `.get()` instead of an `if` block --- nipype/interfaces/io.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nipype/interfaces/io.py b/nipype/interfaces/io.py index 606122021e..1c424825db 100644 --- a/nipype/interfaces/io.py +++ b/nipype/interfaces/io.py @@ -2938,7 +2938,7 @@ def __init__(self, infields=None, **kwargs): undefined_traits = {} for key in self._infields: self.inputs.add_trait(key, traits.Any) - undefined_traits[key] = kwargs[key] if key in kwargs else Undefined + undefined_traits[key] = kwargs.get(key, Undefined) self.inputs.trait_set(trait_change_notify=False, **undefined_traits) From d040d844c279db0abb9d63c4ab771c8252d3f2f2 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos Orfanos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Sun, 6 Oct 2024 16:24:31 +0200 Subject: [PATCH 8/8] STY: Further simplification Co-authored-by: Chris Markiewicz --- nipype/interfaces/afni/utils.py | 2 +- nipype/interfaces/cmtk/convert.py | 6 +++--- nipype/interfaces/cmtk/nx.py | 4 ++-- nipype/interfaces/slicer/generate_classes.py | 6 ++---- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/nipype/interfaces/afni/utils.py b/nipype/interfaces/afni/utils.py index 2426010ffb..95d7985d68 100644 --- a/nipype/interfaces/afni/utils.py +++ b/nipype/interfaces/afni/utils.py @@ -234,7 +234,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): m = re.search(pattern, line) if m: d = m.groupdict() - outputs.trait_set(**{k: int(d[k]) for k in d}) + outputs.trait_set(**{k: int(v) for k, v in d.items()}) return outputs diff --git a/nipype/interfaces/cmtk/convert.py b/nipype/interfaces/cmtk/convert.py index 4f55242a94..b2e21c3bb9 100644 --- a/nipype/interfaces/cmtk/convert.py +++ b/nipype/interfaces/cmtk/convert.py @@ -194,11 +194,11 @@ def _run_interface(self, runtime): for data in self.inputs.data_files: _, data_name, _ = split_filename(data) cda = cf.CData(name=data_name, src=data, fileformat="NumPy") - if string.find(data_name, 'lengths') != -1: + if 'lengths' in data_name: cda.dtype = "FinalFiberLengthArray" - if string.find(data_name, 'endpoints') != -1: + if 'endpoints' in data_name: cda.dtype = "FiberEndpoints" - if string.find(data_name, 'labels') != -1: + if 'labels' in data_name: cda.dtype = "FinalFiberLabels" a.add_connectome_data(cda) diff --git a/nipype/interfaces/cmtk/nx.py b/nipype/interfaces/cmtk/nx.py index 164009541e..53706389aa 100644 --- a/nipype/interfaces/cmtk/nx.py +++ b/nipype/interfaces/cmtk/nx.py @@ -166,7 +166,7 @@ def average_networks(in_files, ntwk_res_file, group_id): for edge in edges: data = ntwk.edge[edge[0]][edge[1]] if ntwk.edge[edge[0]][edge[1]]["count"] >= count_to_keep_edge: - for key in list(data.keys()): + for key in data: if key != "count": data[key] = data[key] / len(in_files) ntwk.edge[edge[0]][edge[1]] = data @@ -183,7 +183,7 @@ def average_networks(in_files, ntwk_res_file, group_id): avg_edges = avg_ntwk.edges() for edge in avg_edges: data = avg_ntwk.edge[edge[0]][edge[1]] - for key in list(data.keys()): + for key in data: if key != "count": edge_dict[key] = np.zeros( (avg_ntwk.number_of_nodes(), avg_ntwk.number_of_nodes()) diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index b5a68d27a6..a36dd6b55a 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -33,10 +33,7 @@ def force_to_valid_python_variable_name(old_name): def add_class_to_package(class_codes, class_names, module_name, package_dir): module_python_filename = os.path.join(package_dir, "%s.py" % module_name) - with ( - open(module_python_filename, "w") as f_m, - open(os.path.join(package_dir, "__init__.py"), "a+") as f_i, - ): + with open(module_python_filename, "w") as f_m: f_m.write( """# -*- coding: utf-8 -*- \"\"\"Autogenerated file - DO NOT EDIT @@ -48,6 +45,7 @@ def add_class_to_package(class_codes, class_names, module_name, package_dir): import os\n\n\n""" f_m.write(imports) f_m.write("\n\n".join(class_codes)) + with open(os.path.join(package_dir, "__init__.py"), "a+") as f_i: f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names)))