From 7b19951ee0bd7c08d17a3a19be5a09d4c09ab26c Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 14 Jun 2023 12:56:00 +0200 Subject: [PATCH] maint: apply suggestions from pyupgrade --- mriqc/__main__.py | 2 +- mriqc/bin/abide2bids.py | 2 +- mriqc/bin/fs2gif.py | 22 +++++++++++----------- mriqc/bin/subject_wrangler.py | 1 - mriqc/config.py | 2 +- mriqc/engine/plugin.py | 4 ++-- mriqc/instrumentation/__main__.py | 2 +- mriqc/interfaces/bids.py | 6 +++--- mriqc/interfaces/functional.py | 1 - mriqc/interfaces/transitional.py | 2 +- mriqc/qc/functional.py | 4 ++-- mriqc/qc/tests/test_anatomical.py | 3 +-- mriqc/reports/group.py | 4 +--- mriqc/synthstrip/__main__.py | 2 +- mriqc/utils/misc.py | 16 ++++++++-------- mriqc/workflows/anatomical/base.py | 4 ++-- mriqc/workflows/functional/output.py | 4 ++-- mriqc/workflows/utils.py | 3 +-- 18 files changed, 39 insertions(+), 45 deletions(-) diff --git a/mriqc/__main__.py b/mriqc/__main__.py index fbb7ac055..57b233f3b 100644 --- a/mriqc/__main__.py +++ b/mriqc/__main__.py @@ -28,5 +28,5 @@ # `python -m ` typically displays the command as __main__.py if "__main__.py" in sys.argv[0]: - sys.argv[0] = "%s -m %s" % (sys.executable, module) + sys.argv[0] = f"{sys.executable} -m {module}" main() diff --git a/mriqc/bin/abide2bids.py b/mriqc/bin/abide2bids.py index b29953144..e3aaa665a 100644 --- a/mriqc/bin/abide2bids.py +++ b/mriqc/bin/abide2bids.py @@ -127,7 +127,7 @@ def fetch(args: Tuple[str, str, str, str]) -> Tuple[str, str]: pkg_id = [u[9:] for u in url.split("/") if u.startswith("NITRC_IR_")][0] sub_file = op.join(tmpdir, "%s.zip" % pkg_id) - cmd = ["curl", "-s", "-u", "%s:%s" % (user, password), "-o", sub_file, url] + cmd = ["curl", "-s", "-u", f"{user}:{password}", "-o", sub_file, url] sp.check_call(cmd) sp.check_call(["unzip", "-qq", "-d", tmpdir, "-u", sub_file]) diff --git a/mriqc/bin/fs2gif.py b/mriqc/bin/fs2gif.py index fb36a3345..492ac2388 100644 --- a/mriqc/bin/fs2gif.py +++ b/mriqc/bin/fs2gif.py @@ -130,7 +130,7 @@ def main(): tclfp.write(" SetSlice $slice\n") tclfp.write(" RedrawScreen\n") tclfp.write( - ' SaveTIFF [format "%s/%s-' % (tmp_sub, subid) + f' SaveTIFF [format "{tmp_sub}/{subid}-' + '%03d.tif" $i]\n' ) tclfp.write(" incr i\n") @@ -160,8 +160,8 @@ def main(): "10", "-loop", "0", - "%s/%s-*.tif" % (tmp_sub, subid), - "%s/%s.gif" % (out_dir, subid), + f"{tmp_sub}/{subid}-*.tif", + f"{out_dir}/{subid}.gif", ] ) @@ -236,8 +236,8 @@ def main(): "10", "-loop", "0", - "%s/%s-lh-*.tif" % (tmp_sub, subid), - "%s/%s-lh.gif" % (out_dir, subid), + f"{tmp_sub}/{subid}-lh-*.tif", + f"{out_dir}/{subid}-lh.gif", ] ) sp.call( @@ -247,8 +247,8 @@ def main(): "10", "-loop", "0", - "%s/%s-rh-*.tif" % (tmp_sub, subid), - "%s/%s-rh.gif" % (out_dir, subid), + f"{tmp_sub}/{subid}-rh-*.tif", + f"{out_dir}/{subid}-rh.gif", ] ) @@ -268,10 +268,10 @@ def _xvfb_run(wait=5, server_args="-screen 0, 1600x1200x24", logs=None): return [ "xvfb-run", "-a", # automatically get a free server number - "-f {}.out".format(logs), - "-e {}.err".format(logs), - "--wait={:d}".format(wait), - '--server-args="{}"'.format(server_args), + f"-f {logs}.out", + f"-e {logs}.err", + f"--wait={wait:d}", + f'--server-args="{server_args}"', ] diff --git a/mriqc/bin/subject_wrangler.py b/mriqc/bin/subject_wrangler.py index 4c019cfdd..00d812ea7 100644 --- a/mriqc/bin/subject_wrangler.py +++ b/mriqc/bin/subject_wrangler.py @@ -24,7 +24,6 @@ import glob import os.path as op from argparse import ArgumentParser, RawTextHelpFormatter -from builtins import range # pylint: disable=W0622 from random import shuffle from textwrap import dedent diff --git a/mriqc/config.py b/mriqc/config.py index 7e8a24132..8f313f61e 100644 --- a/mriqc/config.py +++ b/mriqc/config.py @@ -397,7 +397,7 @@ class execution(_Config): """Enable resource monitor.""" run_id = None """Filter input dataset by run identifier.""" - run_uuid = "%s_%s" % (strftime("%Y%m%d-%H%M%S"), uuid4()) + run_uuid = "{}_{}".format(strftime("%Y%m%d-%H%M%S"), uuid4()) """Unique identifier of this particular run.""" session_id = None """Filter input dataset by session identifier.""" diff --git a/mriqc/engine/plugin.py b/mriqc/engine/plugin.py index c8d9d50bf..f65be584b 100644 --- a/mriqc/engine/plugin.py +++ b/mriqc/engine/plugin.py @@ -133,7 +133,7 @@ class DistributedPluginBase(PluginBase): def __init__(self, plugin_args=None): """Initialize runtime attributes to none.""" - super(DistributedPluginBase, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) self.procs = None self.depidx = None self.refidx = None @@ -419,7 +419,7 @@ def __init__(self, pool=None, plugin_args=None): """Initialize the plugin.""" from mriqc import config - super(MultiProcPlugin, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) self._taskresult = {} self._task_obj = {} self._taskid = 0 diff --git a/mriqc/instrumentation/__main__.py b/mriqc/instrumentation/__main__.py index 52060aa61..de1776fb8 100644 --- a/mriqc/instrumentation/__main__.py +++ b/mriqc/instrumentation/__main__.py @@ -34,7 +34,7 @@ args = parser.parse_args() if "__main__.py" in argparse._sys.argv[0]: # sys.argv[0]: - argparse._sys.argv[0] = "%s -m %s" % (argparse._sys.executable, module) + argparse._sys.argv[0] = f"{argparse._sys.executable} -m {module}" pid = args.name if args.name.isnumeric() else FindProcess(args.name) diff --git a/mriqc/interfaces/bids.py b/mriqc/interfaces/bids.py index b40d2462e..eb48122ae 100644 --- a/mriqc/interfaces/bids.py +++ b/mriqc/interfaces/bids.py @@ -59,12 +59,12 @@ class IQMFileSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): def __setattr__(self, key, value): if key not in self.copyable_trait_names(): if not isdefined(value): - super(IQMFileSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) self._outputs[key] = value else: if key in self._outputs: self._outputs[key] = value - super(IQMFileSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) class IQMFileSinkOutputSpec(TraitedSpec): @@ -77,7 +77,7 @@ class IQMFileSink(SimpleInterface): expr = re.compile("^root[0-9]+$") def __init__(self, fields=None, force_run=True, **inputs): - super(IQMFileSink, self).__init__(**inputs) + super().__init__(**inputs) if fields is None: fields = [] diff --git a/mriqc/interfaces/functional.py b/mriqc/interfaces/functional.py index 39774fe41..deae4a5d7 100644 --- a/mriqc/interfaces/functional.py +++ b/mriqc/interfaces/functional.py @@ -20,7 +20,6 @@ # # https://www.nipreps.org/community/licensing/ # -from builtins import zip from os import path as op import nibabel as nb diff --git a/mriqc/interfaces/transitional.py b/mriqc/interfaces/transitional.py index 5be6e1077..7678fdf7a 100644 --- a/mriqc/interfaces/transitional.py +++ b/mriqc/interfaces/transitional.py @@ -84,7 +84,7 @@ class GCOR(CommandLine): output_spec = GCOROutputSpec def _run_interface(self, runtime): - runtime = super(GCOR, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) gcor_line = [ line.strip() diff --git a/mriqc/qc/functional.py b/mriqc/qc/functional.py index 4c86a0bee..36baaefd3 100644 --- a/mriqc/qc/functional.py +++ b/mriqc/qc/functional.py @@ -244,7 +244,7 @@ def gsr(epi_data, mask, direction="y", ref_file=None, out_file=None): direction = direction.lower() if direction[-1] not in ["x", "y", "all"]: raise Exception( - "Unknown direction {}, should be one of x, -x, y, -y, all".format(direction) + f"Unknown direction {direction}, should be one of x, -x, y, -y, all" ) if direction == "all": @@ -256,7 +256,7 @@ def gsr(epi_data, mask, direction="y", ref_file=None, out_file=None): if ext == ".gz": fname, ext2 = op.splitext(fname) ext = ext2 + ext - ofile = "{0}_{1}{2}".format(fname, newdir, ext) + ofile = f"{fname}_{newdir}{ext}" result += [gsr(epi_data, mask, newdir, ref_file=ref_file, out_file=ofile)] return result diff --git a/mriqc/qc/tests/test_anatomical.py b/mriqc/qc/tests/test_anatomical.py index 332f1f6c9..b4148763a 100644 --- a/mriqc/qc/tests/test_anatomical.py +++ b/mriqc/qc/tests/test_anatomical.py @@ -23,7 +23,6 @@ """ Anatomical tests """ -from builtins import object from shutil import rmtree from tempfile import mkdtemp @@ -35,7 +34,7 @@ from ..anatomical import art_qi2 -class GroundTruth(object): +class GroundTruth: def get_data(self, sigma, noise="normal"): """Generates noisy 3d data""" size = (50, 50, 50) diff --git a/mriqc/reports/group.py b/mriqc/reports/group.py index 3b76756d1..8b8664394 100644 --- a/mriqc/reports/group.py +++ b/mriqc/reports/group.py @@ -21,8 +21,6 @@ # https://www.nipreps.org/community/licensing/ # """Encapsulates report generation functions.""" -from builtins import object # pylint: disable=W0622 -from io import open from sys import version_info import pandas as pd @@ -297,5 +295,5 @@ def _format_labels(row, id_labels): for col_id, prefix in list(BIDS_COMP.items()): if col_id in id_labels: - crow.append("%s-%s" % (prefix, row[[col_id]].values[0])) + crow.append(f"{prefix}-{row[[col_id]].values[0]}") return "_".join(crow) diff --git a/mriqc/synthstrip/__main__.py b/mriqc/synthstrip/__main__.py index db94edb89..1b248bb22 100644 --- a/mriqc/synthstrip/__main__.py +++ b/mriqc/synthstrip/__main__.py @@ -28,5 +28,5 @@ # `python -m ` typically displays the command as __main__.py if "__main__.py" in sys.argv[0]: - sys.argv[0] = "%s -m %s" % (sys.executable, module) + sys.argv[0] = f"{sys.executable} -m {module}" main() diff --git a/mriqc/utils/misc.py b/mriqc/utils/misc.py index 5a2350c24..f4b6cc666 100644 --- a/mriqc/utils/misc.py +++ b/mriqc/utils/misc.py @@ -31,7 +31,7 @@ try: from collections.abc import MutableMapping except ImportError: - from collections import MutableMapping + from collections.abc import MutableMapping IMTYPES = { "T1w": "anat", @@ -104,9 +104,9 @@ def rotate_files(fname): if not op.isfile(fname): return - prev = glob.glob("{}.*{}".format(name, ext)) + prev = glob.glob(f"{name}.*{ext}") prev.insert(0, fname) - prev.append("{0}.{1:d}{2}".format(name, len(prev) - 1, ext)) + prev.append(f"{name}.{len(prev) - 1:d}{ext}") for i in reversed(list(range(1, len(prev)))): os.rename(prev[i - 1], prev[i]) @@ -114,15 +114,15 @@ def rotate_files(fname): def bids_path(subid, sesid=None, runid=None, prefix=None, out_path=None, ext="json"): import os.path as op - fname = "{}".format(subid) + fname = f"{subid}" if prefix is not None: if not prefix.endswith("_"): prefix += "_" fname = prefix + fname if sesid is not None: - fname += "_ses-{}".format(sesid) + fname += f"_ses-{sesid}" if runid is not None: - fname += "_run-{}".format(runid) + fname += f"_run-{runid}" if out_path is not None: fname = op.join(out_path, fname) @@ -139,7 +139,7 @@ def generate_pred(derivatives_dir, output_dir, mod): return None # If some were found, generate the CSV file and group report - jsonfiles = list(output_dir.glob("sub-*/**/%s/sub-*_%s.json" % (IMTYPES[mod], mod))) + jsonfiles = list(output_dir.glob(f"sub-*/**/{IMTYPES[mod]}/sub-*_{mod}.json")) if not jsonfiles: return None @@ -178,7 +178,7 @@ def generate_tsv(output_dir, mod): # If some were found, generate the CSV file and group report out_tsv = output_dir / ("group_%s.tsv" % mod) - jsonfiles = list(output_dir.glob("sub-*/**/%s/sub-*_%s.json" % (IMTYPES[mod], mod))) + jsonfiles = list(output_dir.glob(f"sub-*/**/{IMTYPES[mod]}/sub-*_{mod}.json")) if not jsonfiles: return None, out_tsv diff --git a/mriqc/workflows/anatomical/base.py b/mriqc/workflows/anatomical/base.py index 34fede0bd..4dec6cacd 100644 --- a/mriqc/workflows/anatomical/base.py +++ b/mriqc/workflows/anatomical/base.py @@ -771,7 +771,7 @@ def _apply_bias_correction(in_file, bias_image, out_file=None): if ext == ".gz": fname, ext2 = op.splitext(fname) ext = ext2 + ext - out_file = op.abspath("{}_inu{}".format(fname, ext)) + out_file = op.abspath(f"{fname}_inu{ext}") out_img.to_filename(out_file) return out_file @@ -788,7 +788,7 @@ def _binarize(in_file, threshold=0.5, out_file=None): if ext == ".gz": fname, ext2 = op.splitext(fname) ext = ext2 + ext - out_file = op.abspath("{}_bin{}".format(fname, ext)) + out_file = op.abspath(f"{fname}_bin{ext}") nii = nb.load(in_file) data = nii.get_fdata() > threshold diff --git a/mriqc/workflows/functional/output.py b/mriqc/workflows/functional/output.py index f5b4e94e4..fc6a421ce 100644 --- a/mriqc/workflows/functional/output.py +++ b/mriqc/workflows/functional/output.py @@ -330,8 +330,8 @@ def spikes_mask(in_file, in_mask=None, out_file=None): if ext == ".gz": fname, ext2 = op.splitext(fname) ext = ext2 + ext - out_file = op.abspath("{}_spmask{}".format(fname, ext)) - out_plot = op.abspath("{}_spmask.pdf".format(fname)) + out_file = op.abspath(f"{fname}_spmask{ext}") + out_plot = op.abspath(f"{fname}_spmask.pdf") in_4d_nii = nb.load(in_file) orientation = nb.aff2axcodes(in_4d_nii.affine) diff --git a/mriqc/workflows/utils.py b/mriqc/workflows/utils.py index 24574bc62..690c88a67 100644 --- a/mriqc/workflows/utils.py +++ b/mriqc/workflows/utils.py @@ -21,7 +21,6 @@ # https://www.nipreps.org/community/licensing/ # """Helper functions for the workflows.""" -from builtins import range def _tofloat(inlist): @@ -53,7 +52,7 @@ def thresh_image(in_file, thres=0.5, out_file=None): if ext == ".gz": fname, ext2 = op.splitext(fname) ext = ext2 + ext - out_file = op.abspath("{}_thresh{}".format(fname, ext)) + out_file = op.abspath(f"{fname}_thresh{ext}") im = nb.load(in_file) data = np.asanyarray(im.dataobj)