Skip to content

Commit

Permalink
sty: automatic changes by ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
oesteban committed Mar 19, 2024
1 parent bd3330e commit e39de93
Show file tree
Hide file tree
Showing 60 changed files with 2,913 additions and 2,870 deletions.
6 changes: 3 additions & 3 deletions mriqc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,6 @@
"""
from mriqc._version import __version__

__copyright__ = "Copyright 2022, The NiPreps Developers"
__download__ = f"https://github.com/nipreps/mriqc/archive/{__version__}.tar.gz"
__all__ = ["__version__", "__copyright__", "__download__"]
__copyright__ = 'Copyright 2022, The NiPreps Developers'
__download__ = f'https://github.com/nipreps/mriqc/archive/{__version__}.tar.gz'
__all__ = ['__version__', '__copyright__', '__download__']
7 changes: 4 additions & 3 deletions mriqc/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@
#
from .cli.run import main

if __name__ == "__main__":
if __name__ == '__main__':
import sys

from . import __name__ as module

# `python -m <module>` typically displays the command as __main__.py
if "__main__.py" in sys.argv[0]:
sys.argv[0] = f"{sys.executable} -m {module}"
if '__main__.py' in sys.argv[0]:
sys.argv[0] = f'{sys.executable} -m {module}'
main()
6 changes: 3 additions & 3 deletions mriqc/_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,17 @@
import logging
import warnings

_wlog = logging.getLogger("py.warnings")
_wlog = logging.getLogger('py.warnings')
_wlog.addHandler(logging.NullHandler())


def _warn(message, category=None, stacklevel=1, source=None):
"""Redefine the warning function."""
if category is not None:
category = type(category).__name__
category = category.replace("type", "WARNING")
category = category.replace('type', 'WARNING')

logging.getLogger("py.warnings").warning(f"{category or 'WARNING'}: {message}")
logging.getLogger('py.warnings').warning(f"{category or 'WARNING'}: {message}")


def _showwarning(message, category, filename, lineno, file=None, line=None):
Expand Down
79 changes: 40 additions & 39 deletions mriqc/bin/abide2bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,42 +34,43 @@
from xml.etree import ElementTree as et

import numpy as np

from mriqc.bin import messages


def main():
"""Entry point."""
parser = ArgumentParser(
description="ABIDE2BIDS downloader.",
description='ABIDE2BIDS downloader.',
formatter_class=RawTextHelpFormatter,
)
g_input = parser.add_argument_group("Inputs")
g_input.add_argument("-i", "--input-abide-catalog", action="store", required=True)
g_input = parser.add_argument_group('Inputs')
g_input.add_argument('-i', '--input-abide-catalog', action='store', required=True)
g_input.add_argument(
"-n", "--dataset-name", action="store", default="ABIDE Dataset"
'-n', '--dataset-name', action='store', default='ABIDE Dataset'
)
g_input.add_argument(
"-u", "--nitrc-user", action="store", default=os.getenv("NITRC_USER")
'-u', '--nitrc-user', action='store', default=os.getenv('NITRC_USER')
)
g_input.add_argument(
"-p",
"--nitrc-password",
action="store",
default=os.getenv("NITRC_PASSWORD"),
'-p',
'--nitrc-password',
action='store',
default=os.getenv('NITRC_PASSWORD'),
)

g_outputs = parser.add_argument_group("Outputs")
g_outputs.add_argument("-o", "--output-dir", action="store", default="ABIDE-BIDS")
g_outputs = parser.add_argument_group('Outputs')
g_outputs.add_argument('-o', '--output-dir', action='store', default='ABIDE-BIDS')

opts = parser.parse_args()

if opts.nitrc_user is None or opts.nitrc_password is None:
raise RuntimeError("NITRC user and password are required")
raise RuntimeError('NITRC user and password are required')

dataset_desc = {
"BIDSVersion": "1.0.0rc3",
"License": "CC Attribution-NonCommercial-ShareAlike 3.0 Unported",
"Name": opts.dataset_name,
'BIDSVersion': '1.0.0rc3',
'License': 'CC Attribution-NonCommercial-ShareAlike 3.0 Unported',
'Name': opts.dataset_name,
}

out_dir = op.abspath(opts.output_dir)
Expand All @@ -79,22 +80,22 @@ def main():
if exc.errno != errno.EEXIST:
raise exc

with open(op.join(out_dir, "dataset_description.json"), "w") as dfile:
with open(op.join(out_dir, 'dataset_description.json'), 'w') as dfile:
json.dump(dataset_desc, dfile)

catalog = et.parse(opts.input_abide_catalog).getroot()
urls = [el.get("URI") for el in catalog.iter() if el.get("URI") is not None]
urls = [el.get('URI') for el in catalog.iter() if el.get('URI') is not None]

pool = Pool()
args_list = [(url, opts.nitrc_user, opts.nitrc_password, out_dir) for url in urls]
res = pool.map(fetch, args_list)

tsv_data = np.array([("subject_id", "site_name")] + res)
tsv_data = np.array([('subject_id', 'site_name')] + res)
np.savetxt(
op.join(out_dir, "participants.tsv"),
op.join(out_dir, 'participants.tsv'),
tsv_data,
fmt="%s",
delimiter="\t",
fmt='%s',
delimiter='\t',
)


Expand Down Expand Up @@ -124,46 +125,46 @@ def fetch(args: Tuple[str, str, str, str]) -> Tuple[str, str]:
else:
out_dir = op.abspath(out_dir)

pkg_id = [u[9:] for u in url.split("/") if u.startswith("NITRC_IR_")][0]
sub_file = op.join(tmpdir, "%s.zip" % pkg_id)
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", f"{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])
sp.check_call(['unzip', '-qq', '-d', tmpdir, '-u', sub_file])

abide_root = op.join(tmpdir, "ABIDE")
abide_root = op.join(tmpdir, 'ABIDE')
files = []
for root, path, fname in os.walk(abide_root):
if fname and (fname[0].endswith("nii") or fname[0].endswith("nii.gz")):
if fname and (fname[0].endswith('nii') or fname[0].endswith('nii.gz')):
if path:
root = op.join(root, path[0])
files.append(op.join(root, fname[0]))

index = len(abide_root) + 1
site_name, sub_str = files[0][index:].split("/")[0].split("_")
subject_id = "sub-" + sub_str
site_name, sub_str = files[0][index:].split('/')[0].split('_')
subject_id = 'sub-' + sub_str

for i in files:
ext = ".nii.gz"
if i.endswith(".nii"):
ext = ".nii"
if "mprage" in i:
bids_dir = op.join(out_dir, subject_id, "anat")
ext = '.nii.gz'
if i.endswith('.nii'):
ext = '.nii'
if 'mprage' in i:
bids_dir = op.join(out_dir, subject_id, 'anat')
try:
os.makedirs(bids_dir)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise exc
shutil.copy(i, op.join(bids_dir, subject_id + "_T1w" + ext))
shutil.copy(i, op.join(bids_dir, subject_id + '_T1w' + ext))

if "rest" in i:
bids_dir = op.join(out_dir, subject_id, "func")
if 'rest' in i:
bids_dir = op.join(out_dir, subject_id, 'func')
try:
os.makedirs(bids_dir)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise exc
shutil.copy(i, op.join(bids_dir, subject_id + "_rest_bold" + ext))
shutil.copy(i, op.join(bids_dir, subject_id + '_rest_bold' + ext))

shutil.rmtree(tmpdir, ignore_errors=True, onerror=_myerror)

Expand All @@ -187,5 +188,5 @@ def _myerror(message: str):
print(warning)


if __name__ == "__main__":
if __name__ == '__main__':
main()
53 changes: 27 additions & 26 deletions mriqc/bin/dfcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

import numpy as np
import pandas as pd

from mriqc.bin import messages
from mriqc.utils.misc import BIDS_COMP

Expand All @@ -37,7 +38,7 @@ def read_iqms(feat_file):
"""Read in a features table."""
feat_file = Path(feat_file)

if feat_file.suffix == ".csv":
if feat_file.suffix == '.csv':
x_df = pd.read_csv(
feat_file, index_col=False, dtype={col: str for col in BIDS_COMP}
)
Expand All @@ -46,7 +47,7 @@ def read_iqms(feat_file):
bids_comps_present = [bit for bit in BIDS_COMP if bit in bids_comps_present]
x_df = x_df.sort_values(by=bids_comps_present)
# Remove sub- prefix in subject_id
x_df.subject_id = x_df.subject_id.str.lstrip("sub-")
x_df.subject_id = x_df.subject_id.str.lstrip('sub-')

# Remove columns that are not IQMs
feat_names = list(x_df._get_numeric_data().columns.ravel())
Expand All @@ -56,18 +57,18 @@ def read_iqms(feat_file):
except ValueError:
pass
else:
bids_comps_present = ["subject_id"]
bids_comps_present = ['subject_id']
x_df = pd.read_csv(
feat_file, index_col=False, sep="\t", dtype={"bids_name": str}
feat_file, index_col=False, sep='\t', dtype={'bids_name': str}
)
x_df = x_df.sort_values(by=["bids_name"])
x_df["subject_id"] = x_df.bids_name.str.lstrip("sub-")
x_df = x_df.drop(columns=["bids_name"])
x_df.subject_id = ["_".join(v.split("_")[:-1]) for v in x_df.subject_id.ravel()]
x_df = x_df.sort_values(by=['bids_name'])
x_df['subject_id'] = x_df.bids_name.str.lstrip('sub-')
x_df = x_df.drop(columns=['bids_name'])
x_df.subject_id = ['_'.join(v.split('_')[:-1]) for v in x_df.subject_id.ravel()]
feat_names = list(x_df._get_numeric_data().columns.ravel())

for col in feat_names:
if col.startswith(("size_", "spacing_", "Unnamed")):
if col.startswith(('size_', 'spacing_', 'Unnamed')):
feat_names.remove(col)

return x_df, feat_names, bids_comps_present
Expand All @@ -76,31 +77,31 @@ def read_iqms(feat_file):
def main():
"""Entry point."""
parser = ArgumentParser(
description="Compare two pandas dataframes.",
description='Compare two pandas dataframes.',
formatter_class=RawTextHelpFormatter,
)
g_input = parser.add_argument_group("Inputs")
g_input = parser.add_argument_group('Inputs')
g_input.add_argument(
"-i",
"--input-csv",
action="store",
'-i',
'--input-csv',
action='store',
type=Path,
required=True,
help="input data frame",
help='input data frame',
)
g_input.add_argument(
"-r",
"--reference-csv",
action="store",
'-r',
'--reference-csv',
action='store',
type=Path,
required=True,
help="reference dataframe",
help='reference dataframe',
)
g_input.add_argument(
"--tolerance",
'--tolerance',
type=float,
default=1.0e-5,
help="relative tolerance for comparison",
help='relative tolerance for comparison',
)

opts = parser.parse_args()
Expand Down Expand Up @@ -146,13 +147,13 @@ def main():
changed_to = tst_df[ref_names].values[difference_locations]
cols = [ref_names[v] for v in difference_locations[1]]
bids_df = ref_df.loc[difference_locations[0], ref_bids].reset_index()
chng_df = pd.DataFrame({"iqm": cols, "from": changed_from, "to": changed_to})
chng_df = pd.DataFrame({'iqm': cols, 'from': changed_from, 'to': changed_to})
table = pd.concat([bids_df, chng_df], axis=1)
print(table[ref_bids + ["iqm", "from", "to"]].to_string(index=False))
print(table[ref_bids + ['iqm', 'from', 'to']].to_string(index=False))

corr = pd.DataFrame()
corr["iqms"] = ref_names
corr["cc"] = [
corr['iqms'] = ref_names
corr['cc'] = [
float(
np.corrcoef(
ref_df[[var]].values.ravel(),
Expand All @@ -174,5 +175,5 @@ def main():
sys.exit(0)


if __name__ == "__main__":
if __name__ == '__main__':
main()
Loading

0 comments on commit e39de93

Please sign in to comment.