Skip to content

Commit

Permalink
Merge pull request #1124 from DimitriPapadopoulos/pyupgrade
Browse files Browse the repository at this point in the history
MAINT: apply suggestions from pyupgrade
  • Loading branch information
effigies authored Sep 13, 2023
2 parents 2f1aa74 + 7b19951 commit 2d4d97d
Show file tree
Hide file tree
Showing 18 changed files with 39 additions and 45 deletions.
2 changes: 1 addition & 1 deletion mriqc/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@

# `python -m <module>` 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()
2 changes: 1 addition & 1 deletion mriqc/bin/abide2bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])

Expand Down
22 changes: 11 additions & 11 deletions mriqc/bin/fs2gif.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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",
]
)

Expand Down Expand Up @@ -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(
Expand All @@ -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",
]
)

Expand All @@ -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}"',
]


Expand Down
1 change: 0 additions & 1 deletion mriqc/bin/subject_wrangler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion mriqc/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
4 changes: 2 additions & 2 deletions mriqc/engine/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion mriqc/instrumentation/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
6 changes: 3 additions & 3 deletions mriqc/interfaces/bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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 = []
Expand Down
1 change: 0 additions & 1 deletion mriqc/interfaces/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
#
# https://www.nipreps.org/community/licensing/
#
from builtins import zip
from os import path as op

import nibabel as nb
Expand Down
2 changes: 1 addition & 1 deletion mriqc/interfaces/transitional.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions mriqc/qc/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand 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

Expand Down
3 changes: 1 addition & 2 deletions mriqc/qc/tests/test_anatomical.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
"""
Anatomical tests
"""
from builtins import object
from shutil import rmtree
from tempfile import mkdtemp

Expand All @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions mriqc/reports/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
2 changes: 1 addition & 1 deletion mriqc/synthstrip/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,5 @@

# `python -m <module>` 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()
16 changes: 8 additions & 8 deletions mriqc/utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
try:
from collections.abc import MutableMapping
except ImportError:
from collections import MutableMapping
from collections.abc import MutableMapping

IMTYPES = {
"T1w": "anat",
Expand Down Expand Up @@ -104,25 +104,25 @@ 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])


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)
Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions mriqc/workflows/anatomical/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions mriqc/workflows/functional/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions mriqc/workflows/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
# https://www.nipreps.org/community/licensing/
#
"""Helper functions for the workflows."""
from builtins import range


def _tofloat(inlist):
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 2d4d97d

Please sign in to comment.