Skip to content

Commit

Permalink
Run ruff --fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
tsalo committed Oct 31, 2024
1 parent 436dd19 commit 1d4eaaf
Show file tree
Hide file tree
Showing 57 changed files with 3,973 additions and 3,974 deletions.
2 changes: 1 addition & 1 deletion .circleci/get_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from aslprep.tests.utils import download_test_data

if __name__ == "__main__":
if __name__ == '__main__':
data_dir = sys.argv[1]
dset = sys.argv[2]
download_test_data(dset, data_dir)
112 changes: 56 additions & 56 deletions .maint/update_authors.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,30 +36,30 @@ def read_md_table(md_text):
keys = None
retval = []
for line in md_text.splitlines():
if line.strip().startswith("| --- |"):
keys = (k.replace("*", "").strip() for k in prev.split("|"))
if line.strip().startswith('| --- |'):
keys = (k.replace('*', '').strip() for k in prev.split('|'))
keys = [k.lower() for k in keys if k]
continue
elif not keys:
prev = line
continue

if not line or not line.strip().startswith("|"):
if not line or not line.strip().startswith('|'):
break

values = [v.strip() or None for v in line.split("|")][1:-1]
retval.append({k: v for k, v in zip(keys, values) if v})
values = [v.strip() or None for v in line.split('|')][1:-1]
retval.append({k: v for k, v in zip(keys, values, strict=False) if v})

return retval


def sort_contributors(entries, git_lines, exclude=None, last=None):
"""Return a list of author dictionaries, ordered by contribution."""
last = last or []
sorted_authors = sorted(entries, key=lambda i: i["name"])
sorted_authors = sorted(entries, key=lambda i: i['name'])

first_last = [" ".join(val["name"].split(",")[::-1]).strip() for val in sorted_authors]
first_last_excl = [" ".join(val["name"].split(",")[::-1]).strip() for val in exclude or []]
first_last = [' '.join(val['name'].split(',')[::-1]).strip() for val in sorted_authors]
first_last_excl = [' '.join(val['name'].split(',')[::-1]).strip() for val in exclude or []]

unmatched = []
author_matches = []
Expand All @@ -77,15 +77,15 @@ def sort_contributors(entries, git_lines, exclude=None, last=None):
if val not in author_matches:
author_matches.append(val)

names = {" ".join(val["name"].split(",")[::-1]).strip() for val in author_matches}
names = {' '.join(val['name'].split(',')[::-1]).strip() for val in author_matches}
for missing_name in first_last:
if missing_name not in names:
missing = sorted_authors[first_last.index(missing_name)]
author_matches.append(missing)

position_matches = []
for i, item in enumerate(author_matches):
pos = item.pop("position", None)
pos = item.pop('position', None)
if pos is not None:
position_matches.append((i, int(pos)))

Expand All @@ -97,7 +97,7 @@ def sort_contributors(entries, git_lines, exclude=None, last=None):
return author_matches, unmatched


def get_git_lines(fname="line-contributors.txt"):
def get_git_lines(fname='line-contributors.txt'):
"""Run git-line-summary."""
import shutil
import subprocess as sp
Expand All @@ -106,15 +106,15 @@ def get_git_lines(fname="line-contributors.txt"):

lines = []
if contrib_file.exists():
print("WARNING: Reusing existing line-contributors.txt file.", file=sys.stderr)
print('WARNING: Reusing existing line-contributors.txt file.', file=sys.stderr)
lines = contrib_file.read_text().splitlines()

git_line_summary_path = shutil.which("git-line-summary")
git_line_summary_path = shutil.which('git-line-summary')
if not lines and git_line_summary_path:
print("Running git-line-summary on repo")
print('Running git-line-summary on repo')
lines = sp.check_output([git_line_summary_path]).decode().splitlines()
lines = [l for l in lines if "Not Committed Yet" not in l]
contrib_file.write_text("\n".join(lines))
lines = [l for l in lines if 'Not Committed Yet' not in l]
contrib_file.write_text('\n'.join(lines))

if not lines:
raise RuntimeError(
Expand All @@ -124,13 +124,13 @@ def get_git_lines(fname="line-contributors.txt"):
git-line-summary not found, please install git-extras. """
* (git_line_summary_path is None)
)
return [" ".join(line.strip().split()[1:-1]) for line in lines if "%" in line]
return [' '.join(line.strip().split()[1:-1]) for line in lines if '%' in line]


def _namelast(inlist):
retval = []
for i in inlist:
i["name"] = (f"{i.pop('name', '')} {i.pop('lastname', '')}").strip()
i['name'] = (f"{i.pop('name', '')} {i.pop('lastname', '')}").strip()
retval.append(i)
return retval

Expand All @@ -142,13 +142,13 @@ def cli():


@cli.command()
@click.option("-z", "--zenodo-file", type=click.Path(exists=True), default=".zenodo.json")
@click.option("-m", "--maintainers", type=click.Path(exists=True), default=".maint/MAINTAINERS.md")
@click.option('-z', '--zenodo-file', type=click.Path(exists=True), default='.zenodo.json')
@click.option('-m', '--maintainers', type=click.Path(exists=True), default='.maint/MAINTAINERS.md')
@click.option(
"-c", "--contributors", type=click.Path(exists=True), default=".maint/CONTRIBUTORS.md"
'-c', '--contributors', type=click.Path(exists=True), default='.maint/CONTRIBUTORS.md'
)
@click.option("--pi", type=click.Path(exists=True), default=".maint/PIs.md")
@click.option("-f", "--former-file", type=click.Path(exists=True), default=".maint/FORMER.md")
@click.option('--pi', type=click.Path(exists=True), default='.maint/PIs.md')
@click.option('-f', '--former-file', type=click.Path(exists=True), default='.maint/FORMER.md')
def zenodo(
zenodo_file,
maintainers,
Expand All @@ -175,12 +175,12 @@ def zenodo(
zen_pi = _namelast(
sorted(
read_md_table(Path(pi).read_text()),
key=lambda v: (int(v.get("position", -1)), v.get("lastname")),
key=lambda v: (int(v.get('position', -1)), v.get('lastname')),
)
)

zenodo["creators"] = zen_creators
zenodo["contributors"] = zen_contributors + zen_pi
zenodo['creators'] = zen_creators
zenodo['contributors'] = zen_contributors + zen_pi

misses = set(miss_creators).intersection(miss_contributors)
if misses:
Expand All @@ -190,30 +190,30 @@ def zenodo(
)

# Remove position
for creator in zenodo["creators"]:
creator.pop("position", None)
creator.pop("handle", None)
if isinstance(creator["affiliation"], list):
creator["affiliation"] = creator["affiliation"][0]
for creator in zenodo['creators']:
creator.pop('position', None)
creator.pop('handle', None)
if isinstance(creator['affiliation'], list):
creator['affiliation'] = creator['affiliation'][0]

for creator in zenodo["contributors"]:
creator.pop("handle", None)
creator["type"] = "Researcher"
creator.pop("position", None)
for creator in zenodo['contributors']:
creator.pop('handle', None)
creator['type'] = 'Researcher'
creator.pop('position', None)

if isinstance(creator["affiliation"], list):
creator["affiliation"] = creator["affiliation"][0]
if isinstance(creator['affiliation'], list):
creator['affiliation'] = creator['affiliation'][0]

Path(zenodo_file).write_text("%s\n" % json.dumps(zenodo, indent=2))
Path(zenodo_file).write_text('%s\n' % json.dumps(zenodo, indent=2))


@cli.command()
@click.option("-m", "--maintainers", type=click.Path(exists=True), default=".maint/MAINTAINERS.md")
@click.option('-m', '--maintainers', type=click.Path(exists=True), default='.maint/MAINTAINERS.md')
@click.option(
"-c", "--contributors", type=click.Path(exists=True), default=".maint/CONTRIBUTORS.md"
'-c', '--contributors', type=click.Path(exists=True), default='.maint/CONTRIBUTORS.md'
)
@click.option("--pi", type=click.Path(exists=True), default=".maint/PIs.md")
@click.option("-f", "--former-file", type=click.Path(exists=True), default=".maint/FORMER.md")
@click.option('--pi', type=click.Path(exists=True), default='.maint/PIs.md')
@click.option('-f', '--former-file', type=click.Path(exists=True), default='.maint/FORMER.md')
def publication(
maintainers,
contributors,
Expand All @@ -234,12 +234,12 @@ def publication(
pi_hits = _namelast(
sorted(
read_md_table(Path(pi).read_text()),
key=lambda v: (int(v.get("position", -1)), v.get("lastname")),
key=lambda v: (int(v.get('position', -1)), v.get('lastname')),
)
)

pi_names = [pi["name"] for pi in pi_hits]
hits = [hit for hit in hits if hit["name"] not in pi_names] + pi_hits
pi_names = [pi['name'] for pi in pi_hits]
hits = [hit for hit in hits if hit['name'] not in pi_names] + pi_hits

def _aslist(value):
if isinstance(value, (list, tuple)):
Expand All @@ -249,16 +249,16 @@ def _aslist(value):
# Remove position
affiliations = []
for item in hits:
item.pop("position", None)
for a in _aslist(item.get("affiliation", "Unaffiliated")):
item.pop('position', None)
for a in _aslist(item.get('affiliation', 'Unaffiliated')):
if a not in affiliations:
affiliations.append(a)

aff_indexes = [
", ".join(
', '.join(
[
"%d" % (affiliations.index(a) + 1)
for a in _aslist(author.get("affiliation", "Unaffiliated"))
'%d' % (affiliations.index(a) + 1)
for a in _aslist(author.get('affiliation', 'Unaffiliated'))
]
)
for author in hits
Expand All @@ -270,18 +270,18 @@ def _aslist(value):
file=sys.stderr,
)

print("Authors (%d):" % len(hits))
print('Authors (%d):' % len(hits))
print(
"%s."
% "; ".join(["%s \\ :sup:`%s`\\ " % (i["name"], idx) for i, idx in zip(hits, aff_indexes)])
'%s.'
% '; '.join(['%s \\ :sup:`%s`\\ ' % (i['name'], idx) for i, idx in zip(hits, aff_indexes, strict=False)])
)

print(
"\n\nAffiliations:\n%s"
% "\n".join(["{0: >2}. {1}".format(i + 1, a) for i, a in enumerate(affiliations)])
'\n\nAffiliations:\n%s'
% '\n'.join([f'{i + 1: >2}. {a}' for i, a in enumerate(affiliations)])
)


if __name__ == "__main__":
if __name__ == '__main__':
"""Install entry-point"""
cli()
14 changes: 7 additions & 7 deletions aslprep/__about__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
try:
from aslprep._version import __version__
except ImportError:
__version__ = "0+unknown"
__version__ = '0+unknown'

__packagename__ = "aslprep"
__copyright__ = "Copyright 2023, The ASLPrep Developers"
__packagename__ = 'aslprep'
__copyright__ = 'Copyright 2023, The ASLPrep Developers'
__credits__ = (
"Contributors: please check the ``.zenodo.json`` file at the top-level folder "
"of the repository."
'Contributors: please check the ``.zenodo.json`` file at the top-level folder '
'of the repository.'
)
__url__ = "https://github.com/PennLINC/aslprep"
__url__ = 'https://github.com/PennLINC/aslprep'

DOWNLOAD_URL = f"https://github.com/PennLINC/{__packagename__}/archive/{__version__}.tar.gz"
DOWNLOAD_URL = f'https://github.com/PennLINC/{__packagename__}/archive/{__version__}.tar.gz'
8 changes: 4 additions & 4 deletions aslprep/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from aslprep.__about__ import __copyright__, __credits__, __packagename__, __version__

__all__ = [
"__copyright__",
"__credits__",
"__packagename__",
"__version__",
'__copyright__',
'__credits__',
'__packagename__',
'__version__',
]
6 changes: 3 additions & 3 deletions aslprep/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

from aslprep.cli.run import main

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

from aslprep 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 aslprep/_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,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
17 changes: 8 additions & 9 deletions aslprep/cli/aggregate_qc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Aggregate QC measures across all subjects in dataset."""
Expand All @@ -14,9 +13,9 @@ def get_parser():

parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)

parser.add_argument("aslprep_dir", action="store", type=Path, help="aslprep output dir")
parser.add_argument('aslprep_dir', action='store', type=Path, help='aslprep output dir')

parser.add_argument("output_prefix", action="store", type=str, help="output prefix for group")
parser.add_argument('output_prefix', action='store', type=str, help='output prefix for group')
return parser


Expand All @@ -25,23 +24,23 @@ def main():
opts = get_parser().parse_args()

allsubj_dir = os.path.abspath(opts.aslprep_dir)
outputfile = os.getcwd() + "/" + str(opts.output_prefix) + "_allsubjects_qc.tsv"
outputfile = os.getcwd() + '/' + str(opts.output_prefix) + '_allsubjects_qc.tsv'

qclist = []
for r, d, f in os.walk(allsubj_dir):
for filex in f:
if filex.endswith("desc-qualitycontrol_cbf.tsv"):
qclist.append(r + "/" + filex)
if filex.endswith('desc-qualitycontrol_cbf.tsv'):
qclist.append(r + '/' + filex)

datax = pd.read_table(qclist[0])
for i in range(1, len(qclist)):
dy = pd.read_table(qclist[i])
datax = pd.concat([datax, dy])

datax.to_csv(outputfile, index=None, sep="\t")
datax.to_csv(outputfile, index=None, sep='\t')


if __name__ == "__main__":
if __name__ == '__main__':
raise RuntimeError(
"this should be run after running aslprep;\nit required installation of aslprep"
'this should be run after running aslprep;\nit required installation of aslprep'
)
Loading

0 comments on commit 1d4eaaf

Please sign in to comment.