diff --git a/.github/workflows/pythonpackage.yml b/.github/workflows/pythonpackage.yml index 1ec634f76..f2fc1d7d1 100644 --- a/.github/workflows/pythonpackage.yml +++ b/.github/workflows/pythonpackage.yml @@ -79,7 +79,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - run: pipx run ruff format --diff + - run: | + pipx run ruff check --output-format=github + pipx run ruff format --diff codespell: runs-on: ubuntu-latest diff --git a/docs/notebooks/MRIQC Web API.ipynb b/docs/notebooks/MRIQC Web API.ipynb index b0e6cfcd9..f0e107166 100644 --- a/docs/notebooks/MRIQC Web API.ipynb +++ b/docs/notebooks/MRIQC Web API.ipynb @@ -19,14 +19,16 @@ }, "outputs": [], "source": [ - "import pandas as pd\n", - "from json import load\n", - "import urllib.request, json\n", - "from pandas.io.json import json_normalize\n", - "import seaborn as sns\n", - "import pylab as plt\n", + "import json\n", "import multiprocessing as mp\n", + "import urllib.request\n", + "from json import load\n", + "\n", "import numpy as np\n", + "import pandas as pd\n", + "import pylab as plt\n", + "import seaborn as sns\n", + "from pandas.io.json import json_normalize\n", "\n", "%matplotlib inline" ] @@ -62,14 +64,13 @@ " query = []\n", "\n", " if software is not None:\n", - " query.append('\"provenance.software\":\"%s\"' % software)\n", + " query.append(f'\"provenance.software\":\"{software}\"')\n", "\n", " if version != '*':\n", - " query.append('\"provenance.version\":\"%s\"' % version)\n", + " query.append(f'\"provenance.version\":\"{version}\"')\n", "\n", - " page_url = url_root.format(\n", - " modality=modality, query='where={%s}&page=%d' % (','.join(query), page)\n", - " )\n", + " where = ','.join(query)\n", + " page_url = url_root.format(modality=modality, query=f'where={where}&page={page}')\n", " with urllib.request.urlopen(page_url) as url:\n", " data = json.loads(url.read().decode())\n", " dfs.append(json_normalize(data['_items']))\n", @@ -150,8 +151,9 @@ ], "source": [ "import datetime\n", - "from dateutil import parser\n", + "\n", "import matplotlib.dates as mdates\n", + "from dateutil import parser\n", "\n", "dates_t1w = [parser.parse(d) for d in df_t1w['_created'].values]\n", "dates_t1w.sort()\n", @@ -224,11 +226,11 @@ "print(\n", " ','.join(\n", " [\n", - " l\n", - " for l in df_t1w.columns\n", - " if not l.startswith('_')\n", - " and not l.startswith('bids_meta')\n", - " and not l.startswith('provenance')\n", + " line\n", + " for line in df_t1w.columns\n", + " if not line.startswith('_')\n", + " and not line.startswith('bids_meta')\n", + " and not line.startswith('provenance')\n", " ]\n", " )\n", ")" @@ -291,11 +293,11 @@ "print(\n", " ','.join(\n", " [\n", - " l\n", - " for l in df_bold.columns\n", - " if not l.startswith('_')\n", - " and not l.startswith('bids_meta')\n", - " and not l.startswith('provenance')\n", + " line\n", + " for line in df_bold.columns\n", + " if not line.startswith('_')\n", + " and not line.startswith('bids_meta')\n", + " and not line.startswith('provenance')\n", " ]\n", " )\n", ")" diff --git a/docs/notebooks/Paper-v1.0.ipynb b/docs/notebooks/Paper-v1.0.ipynb index 5fbda5fee..ba0655d85 100644 --- a/docs/notebooks/Paper-v1.0.ipynb +++ b/docs/notebooks/Paper-v1.0.ipynb @@ -11,13 +11,14 @@ "%matplotlib inline\n", "%load_ext autoreload\n", "%autoreload 2\n", - "import matplotlib.pyplot as plt\n", "import os.path as op\n", - "import pandas as pd\n", + "\n", + "import matplotlib.pyplot as plt\n", "import numpy as np\n", - "import seaborn as sn\n", + "import pandas as pd\n", + "import seaborn as sns\n", "\n", - "sn.set(style='whitegrid')" + "sns.set(style='whitegrid')" ] }, { @@ -31,7 +32,7 @@ "from mriqc.classifier import data as mcd\n", "\n", "abide, _ = mcd.read_dataset(x_path, y_path, rate_label='rater_1')\n", - "sites = list(sorted(set(abide.site.values.ravel())))\n", + "sites = sorted(set(abide.site.values.ravel()))\n", "\n", "fmt = r'{site} & \\pixmat{{{size[0]:d}$\\pm${sr[0]:d}}}{{{size[1]:d}$\\pm${sr[1]:d}}}{{{size[2]:d}$\\pm${sr[1]:d}}}'\n", "fmt += r'& \\pixmat[mm]{{{sp[0]:.2f}$\\pm${spr[0]:.2f}}}{{{sp[1]:.2f}$\\pm${spr[1]:.2f}}}{{{sp[2]:.2f}$\\pm${spr[1]:.2f}}}'\n", @@ -191,7 +192,7 @@ " ax = plt.gca()\n", "\n", " outer_score = data.loc[data[score].notnull(), [score, 'zscored']]\n", - " sn.distplot(\n", + " sns.distplot(\n", " outer_score.loc[outer_score.zscored == zscored, score],\n", " hist=True,\n", " norm_hist=True,\n", @@ -213,40 +214,47 @@ " draw_line(mean + std, ax=ax, color=color, extend=True)\n", "\n", " ax.annotate(\n", - " '$\\mu$=%0.3f' % mean,\n", + " rf'$\\mu$={mean:0.3f}',\n", " xy=(mean_coord[0], 0.75 * ymax),\n", " xytext=(-35, 30),\n", " textcoords='offset points',\n", " va='center',\n", " color='w',\n", " size=14,\n", - " bbox=dict(boxstyle='round', fc=color, ec='none', color='none', lw=0),\n", - " arrowprops=dict(\n", - " arrowstyle='wedge,tail_width=0.8',\n", - " lw=0,\n", - " patchA=None,\n", - " patchB=None,\n", - " fc=color,\n", - " ec='none',\n", - " relpos=(0.5, 0.5),\n", - " ),\n", + " bbox={'boxstyle': 'round', 'fc': color, 'ec': 'none', 'color': 'none', 'lw': 0},\n", + " arrowprops={\n", + " 'arrowstyle': 'wedge,tail_width=0.8',\n", + " 'lw': 0,\n", + " 'patchA': None,\n", + " 'patchB': None,\n", + " 'fc': color,\n", + " 'ec': 'none',\n", + " 'relpos': (0.5, 0.5),\n", + " },\n", " )\n", " sigmay = 0.70 * ymax\n", " ax.annotate(\n", " s='',\n", " xy=(mean - std, sigmay),\n", " xytext=(mean + std, sigmay),\n", - " arrowprops=dict(arrowstyle='<->'),\n", + " arrowprops={'arrowstyle': '<->'},\n", " )\n", " ax.annotate(\n", - " '$2\\sigma$=%0.3f' % (2 * std),\n", + " r'$2\\sigma$=%0.3f' % (2 * std),\n", " xy=(mean_coord[0], 0.70 * ymax),\n", " xytext=(-25, -12),\n", " textcoords='offset points',\n", " va='center',\n", " color='k',\n", " size=12,\n", - " bbox=dict(boxstyle='round', fc='w', ec='none', color='none', alpha=0.7, lw=0),\n", + " bbox={\n", + " 'boxstyle': 'round',\n", + " 'fc': 'w',\n", + " 'ec': 'none',\n", + " 'color': 'none',\n", + " 'alpha': 0.7,\n", + " 'lw': 0,\n", + " },\n", " )\n", "\n", " if ds030_score is not None:\n", @@ -259,16 +267,16 @@ " va='center',\n", " color='w',\n", " size=16,\n", - " bbox=dict(boxstyle='round', fc=color, ec='none', color='none', lw=0),\n", - " arrowprops=dict(\n", - " arrowstyle='wedge,tail_width=0.8',\n", - " lw=0,\n", - " patchA=None,\n", - " patchB=None,\n", - " fc=color,\n", - " ec='none',\n", - " relpos=(0.5, 0.5),\n", - " ),\n", + " bbox={'boxstyle': 'round', 'fc': color, 'ec': 'none', 'color': 'none', 'lw': 0},\n", + " arrowprops={\n", + " 'arrowstyle': 'wedge,tail_width=0.8',\n", + " 'lw': 0,\n", + " 'patchA': None,\n", + " 'patchB': None,\n", + " 'fc': color,\n", + " 'ec': 'none',\n", + " 'relpos': (0.5, 0.5),\n", + " },\n", " )\n", "\n", "\n", @@ -310,12 +318,12 @@ }, "outputs": [], "source": [ - "sn.set(style='whitegrid')\n", + "sns.set(style='whitegrid')\n", "\n", "fig = plt.figure(figsize=(20, 8))\n", "ax1 = plt.subplot2grid((2, 4), (0, 0), colspan=2, rowspan=2)\n", "\n", - "sn.violinplot(\n", + "sns.violinplot(\n", " x='Classifier',\n", " y='AUC',\n", " hue='Split scheme',\n", @@ -382,8 +390,8 @@ "outputs": [], "source": [ "zscoreddf = loso_outer.loc[loso_outer.zscored == 0, ['auc', 'acc', 'site']]\n", - "palette = sn.color_palette('cubehelix', len(set(zscoreddf.site)))\n", - "sn.pairplot(\n", + "palette = sns.color_palette('cubehelix', len(set(zscoreddf.site)))\n", + "sns.pairplot(\n", " zscoreddf.loc[zscoreddf.auc.notnull(), ['auc', 'acc', 'site']], hue='site', palette=palette\n", ")" ] @@ -396,13 +404,13 @@ }, "outputs": [], "source": [ - "sites = sorted(list(set(loso_outer.site.ravel().tolist())))\n", - "palette = sn.color_palette('husl', len(sites))\n", + "sites = sorted(set(loso_outer.site.ravel().tolist()))\n", + "palette = sns.color_palette('husl', len(sites))\n", "fig = plt.figure()\n", "for i, site in enumerate(sites):\n", " sitedf = loso_outer.loc[loso_outer.site == site]\n", " accdf = sitedf.loc[sitedf.zscored == 0]\n", - " sn.distplot(accdf.acc.values.ravel(), bins=20, kde=0, label=site, color=palette[i])\n", + " sns.distplot(accdf.acc.values.ravel(), bins=20, kde=0, label=site, color=palette[i])\n", "\n", "fig.gca().legend()\n", "fig.gca().set_xlim([0.5, 1.0])" diff --git a/docs/notebooks/Paper-v2.0.ipynb b/docs/notebooks/Paper-v2.0.ipynb index 02f2c03e5..0fb4f9591 100644 --- a/docs/notebooks/Paper-v2.0.ipynb +++ b/docs/notebooks/Paper-v2.0.ipynb @@ -24,12 +24,12 @@ "%load_ext autoreload\n", "%autoreload 2\n", "import os.path as op\n", + "\n", "import numpy as np\n", "import pandas as pd\n", - "from pkg_resources import resource_filename as pkgrf\n", - "\n", + "from mriqc.classifier.data import combine_datasets, read_dataset\n", "from mriqc.viz import misc as mviz\n", - "from mriqc.classifier.data import read_dataset, combine_datasets\n", + "from pkg_resources import resource_filename as pkgrf\n", "\n", "# Where the outputs should be saved\n", "outputs_path = '../../mriqc-data/'\n", @@ -63,7 +63,7 @@ "rater_types = {'rater_1': float, 'rater_2': float, 'rater_3': float}\n", "mdata = pd.read_csv(y_path, index_col=False, dtype=rater_types)\n", "\n", - "sites = list(sorted(list(set(mdata.site.values.ravel().tolist()))))" + "sites = sorted(set(mdata.site.values.ravel().tolist()))" ] }, { @@ -283,14 +283,14 @@ " y1, y2, out_file=op.join(outputs_path, 'figures', 'fig02-irv.pdf')\n", ")\n", "\n", - "print(\"Cohen's Kappa %f\" % cohen_kappa_score(y1, y2))\n", + "print(f\"Cohen's Kappa {cohen_kappa_score(y1, y2):f}\")\n", "\n", "y1 = overlap.rater_1.values.ravel()\n", "y1[y1 == 0] = 1\n", "\n", "y2 = overlap.rater_2.values.ravel()\n", "y2[y2 == 0] = 1\n", - "print(\"Cohen's Kappa (binarized): %f\" % cohen_kappa_score(y1, y2))" + "print(f\"Cohen's Kappa (binarized): {cohen_kappa_score(y1, y2):f}\")" ] }, { @@ -309,7 +309,7 @@ "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", - "import seaborn as sn\n", + "import seaborn as sns\n", "\n", "rfc_acc = [\n", " 0.842,\n", @@ -391,13 +391,13 @@ "\n", "fig = plt.figure(figsize=(10, 3))\n", "ax2 = plt.subplot2grid((1, 4), (0, 3))\n", - "plot = sn.violinplot(\n", + "plot = sns.violinplot(\n", " data=df, x='Model', y='accuracy', ax=ax2, palette=colors, bw=0.1, linewidth=0.7\n", ")\n", "for i in range(dim):\n", " ax2.axhline(np.average(allvals[i]), ls='--', color=colors[i], lw=0.8)\n", "# ax2.axhline(np.percentile(allvals[i], 50), ls='--', color=colors[i], lw=.8)\n", - "# sn.swarmplot(x=\"model\", y=\"accuracy\", data=df, color=\"w\", alpha=.5, ax=ax2);\n", + "# sns.swarmplot(x=\"model\", y=\"accuracy\", data=df, color=\"w\", alpha=.5, ax=ax2);\n", "ax2.yaxis.tick_right()\n", "ax2.set_ylabel('')\n", "ax2.set_xticklabels(ax2.get_xticklabels(), rotation=40)\n", @@ -506,7 +506,7 @@ "\n", "fig = plt.figure(figsize=(10, 3))\n", "ax2 = plt.subplot2grid((1, 4), (0, 3))\n", - "plot = sn.violinplot(data=df, x='Model', y='auc', ax=ax2, palette=colors, bw=0.1, linewidth=0.7)\n", + "plot = sns.violinplot(data=df, x='Model', y='auc', ax=ax2, palette=colors, bw=0.1, linewidth=0.7)\n", "for i in range(dim):\n", " ax2.axhline(np.average(allvals[i]), ls='--', color=colors[i], lw=0.8)\n", "\n", @@ -584,10 +584,10 @@ }, "outputs": [], "source": [ - "import seaborn as sn\n", + "import seaborn as sns\n", "from sklearn.externals.joblib import load as loadpkl\n", "\n", - "sn.set_style('white')\n", + "sns.set_style('white')\n", "\n", "# Get the RFC\n", "estimator = loadpkl(\n", @@ -666,8 +666,8 @@ " df['Importance'] += [tree.feature_importances_[i]]\n", "fig = plt.figure(figsize=(20, 6))\n", "# plt.title(\"Feature importance plot\")\n", - "sn.boxplot(x='Feature', y='Importance', data=pd.DataFrame(df), linewidth=1, notch=True)\n", - "plt.xlabel('Features selected (%d)' % len(features))\n", + "sns.boxplot(x='Feature', y='Importance', data=pd.DataFrame(df), linewidth=1, notch=True)\n", + "plt.xlabel(f'Features selected ({len(features)})')\n", "# plt.bar(range(nft), importances[indices],\n", "# color=\"r\", yerr=std[indices], align=\"center\")\n", "plt.xticks(range(nft))\n", @@ -776,17 +776,17 @@ "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", - "from mriqc.viz.utils import plot_slice\n", "import nibabel as nb\n", + "from mriqc.viz.utils import plot_slice\n", "\n", "for im, z in fn_clear:\n", - " image_path = op.join(ds030_path, 'sub-%s' % im, 'anat', 'sub-%s_T1w.nii.gz' % im)\n", + " image_path = op.join(ds030_path, f'sub-{im}', 'anat', f'sub-{im}_T1w.nii.gz')\n", " imdata = nb.load(image_path).get_data()\n", "\n", " fig, ax = plt.subplots()\n", " plot_slice(imdata[..., z], annotate=True)\n", " fig.savefig(\n", - " op.join(outputs_path, 'figures', 'fig-06_sub-%s_slice-%03d.svg' % (im, z)),\n", + " op.join(outputs_path, 'figures', f'fig-06_sub-{im}_slice-{z:03}.svg'),\n", " dpi=300,\n", " bbox_inches='tight',\n", " )\n", @@ -807,13 +807,13 @@ " ('50073', 162),\n", "]\n", "for im, z in fp_clear:\n", - " image_path = op.join(ds030_path, 'sub-%s' % im, 'anat', 'sub-%s_T1w.nii.gz' % im)\n", + " image_path = op.join(ds030_path, f'sub-{im}', 'anat', f'sub-{im}_T1w.nii.gz')\n", " imdata = nb.load(image_path).get_data()\n", "\n", " fig, ax = plt.subplots()\n", " plot_slice(imdata[..., z], annotate=True)\n", " fig.savefig(\n", - " op.join(outputs_path, 'figures', 'fig-06_sub-%s_slice-%03d.svg' % (im, z)),\n", + " op.join(outputs_path, 'figures', f'fig-06_sub-{im}_slice-{z:03}.svg'),\n", " dpi=300,\n", " bbox_inches='tight',\n", " )\n", diff --git a/docs/notebooks/Supplemental Materials.ipynb b/docs/notebooks/Supplemental Materials.ipynb index 0758f3489..5068aaa08 100644 --- a/docs/notebooks/Supplemental Materials.ipynb +++ b/docs/notebooks/Supplemental Materials.ipynb @@ -23,6 +23,7 @@ "%load_ext autoreload\n", "%autoreload 2\n", "import os.path as op\n", + "\n", "import numpy as np\n", "import pandas as pd\n", "from mriqc.viz import misc as mviz\n", @@ -47,7 +48,7 @@ "rater_types = {'rater_1': float, 'rater_2': float, 'rater_3': float}\n", "mdata = pd.read_csv(y_path, index_col=False, dtype=rater_types)\n", "\n", - "sites = list(sorted(list(set(mdata.site.values.ravel().tolist()))))" + "sites = sorted(set(mdata.site.values.ravel().tolist()))" ] }, { @@ -86,14 +87,14 @@ " out_file=op.join(outputs_path, 'figures', 'suppl-intrarv.pdf'),\n", ")\n", "\n", - "print(\"Cohen's Kappa %f\" % cohen_kappa_score(y1, y2))\n", + "print(f\"Cohen's Kappa {cohen_kappa_score(y1, y2):f}\")\n", "\n", "y1 = overlap.rater_2.values.ravel()\n", "y1[y1 == 0] = 1\n", "\n", "y2 = overlap.rater_3.values.ravel()\n", "y2[y2 == 0] = 1\n", - "print(\"Cohen's Kappa (binarized): %f\" % cohen_kappa_score(y1, y2))" + "print(f\"Cohen's Kappa (binarized): {cohen_kappa_score(y1, y2):f}\")" ] }, { diff --git a/docs/notebooks/finding_spikes.ipynb b/docs/notebooks/finding_spikes.ipynb index a2e688673..b7d42d903 100644 --- a/docs/notebooks/finding_spikes.ipynb +++ b/docs/notebooks/finding_spikes.ipynb @@ -8,14 +8,16 @@ }, "outputs": [], "source": [ - "import nibabel, nipy, nilearn\n", - "from nipy.labs.mask import compute_mask\n", - "from nilearn.masking import compute_epi_mask\n", - "from nilearn.image import mean_img, new_img_like\n", + "import nibabel\n", + "import nilearn\n", + "import nipy\n", + "import numpy as np\n", "import pylab as plt\n", "import seaborn as sns\n", - "from nilearn.plotting import plot_epi, plot_anat, plot_roi\n", - "import numpy as np\n", + "from nilearn.image import mean_img, new_img_like\n", + "from nilearn.masking import compute_epi_mask\n", + "from nilearn.plotting import plot_anat, plot_epi, plot_roi\n", + "from nipy.labs.mask import compute_mask\n", "\n", "%matplotlib inline" ] diff --git a/mriqc/bin/dfcheck.py b/mriqc/bin/dfcheck.py index 832b3fd5e..346b6a68b 100644 --- a/mriqc/bin/dfcheck.py +++ b/mriqc/bin/dfcheck.py @@ -40,7 +40,7 @@ def read_iqms(feat_file): feat_file = Path(feat_file) if feat_file.suffix == '.csv': - x_df = pd.read_csv(feat_file, index_col=False, dtype={col: str for col in BIDS_COMP}) + x_df = pd.read_csv(feat_file, index_col=False, dtype=dict.fromkeys(BIDS_COMP, str)) # Find present bids bits and sort by them bids_comps_present = list(set(x_df.columns) & set(BIDS_COMP)) bids_comps_present = [bit for bit in BIDS_COMP if bit in bids_comps_present] diff --git a/mriqc/bin/fs2gif.py b/mriqc/bin/fs2gif.py index 762a13d82..18d5a712a 100644 --- a/mriqc/bin/fs2gif.py +++ b/mriqc/bin/fs2gif.py @@ -125,8 +125,7 @@ def main(): with open(tcl_file, 'w') as tclfp: tclfp.write(tcl_contents) tclfp.write( - 'for { set slice %d } { $slice < %d } { incr slice } {' - % (bbox_min[2], bbox_max[2]) + f'for {{ set slice {bbox_min[2]} }} {{ $slice < {bbox_max[2]} }} {{ incr slice }} {{' ) tclfp.write(' SetSlice $slice\n') tclfp.write(' RedrawScreen\n') @@ -170,10 +169,9 @@ def main(): tclfp.write(tcl_contents) tclfp.write('SetZoomLevel 2') tclfp.write( - 'for { set slice %d } { $slice < %d } { incr slice } {' - % (bbox_min[2], bbox_max[2]) + 'for {{ set slice {bbox_min[2]} }} {{ $slice < {bbox_max[2]} }} {{ incr slice }} {{' ) - tclfp.write(' SetZoomCenter %d %d $slice\n' % (center[0] + 30, center[1] - 10)) + tclfp.write(f' SetZoomCenter {center[0] + 30} {center[1] - 10} $slice\n') tclfp.write(' SetSlice $slice\n') tclfp.write(' RedrawScreen\n') tclfp.write(f' SaveTIFF [format "{tmp_sub}/{subid}-lh-%03d.tif" $i]\n') @@ -195,10 +193,9 @@ def main(): tclfp.write(tcl_contents) tclfp.write('SetZoomLevel 2') tclfp.write( - 'for { set slice %d } { $slice < %d } { incr slice } {' - % (bbox_min[2], bbox_max[2]) + 'for {{ set slice {bbox_min[2]} }} {{ $slice < {bbox_max[2]} }} {{ incr slice }} {{' ) - tclfp.write(' SetZoomCenter %d %d $slice\n' % (center[0] - 30, center[1] - 10)) + tclfp.write(f' SetZoomCenter {center[0] - 30} {center[1] - 10} $slice\n') tclfp.write(' SetSlice $slice\n') tclfp.write(' RedrawScreen\n') tclfp.write(f' SaveTIFF [format "{tmp_sub}/{subid}-rh-%03d.tif" $slice]\n') diff --git a/mriqc/cli/run.py b/mriqc/cli/run.py index efbe345d6..bd872f281 100644 --- a/mriqc/cli/run.py +++ b/mriqc/cli/run.py @@ -35,11 +35,11 @@ def format_elapsed_time(elapsed_timedelta): def main(argv=None): """Entry point for MRIQC's CLI.""" import atexit + import datetime import gc import os import sys import time - import datetime from tempfile import mkstemp from mriqc import config, messages diff --git a/mriqc/config.py b/mriqc/config.py index 898cf94af..c1aca5692 100644 --- a/mriqc/config.py +++ b/mriqc/config.py @@ -93,10 +93,11 @@ import os import pickle import sys +from collections.abc import Iterable from contextlib import suppress from pathlib import Path from time import strftime -from typing import TYPE_CHECKING, Any, Iterable +from typing import TYPE_CHECKING, Any from uuid import uuid4 try: diff --git a/mriqc/conftest.py b/mriqc/conftest.py index 7d0d55a7e..da06ce4bf 100644 --- a/mriqc/conftest.py +++ b/mriqc/conftest.py @@ -70,16 +70,16 @@ def expand_namespace(doctest_namespace): tmpdir.cleanup() -@pytest.fixture() +@pytest.fixture def testdata_path(): return _datadir -@pytest.fixture() +@pytest.fixture def workdir(): return None if test_workdir is None else Path(test_workdir) -@pytest.fixture() +@pytest.fixture def outdir(): return None if test_output_dir is None else Path(test_output_dir) diff --git a/mriqc/qc/tests/test_anatomical.py b/mriqc/qc/tests/test_anatomical.py index b89fa1aa0..5fa4799b2 100644 --- a/mriqc/qc/tests/test_anatomical.py +++ b/mriqc/qc/tests/test_anatomical.py @@ -60,7 +60,7 @@ def get_data(self, sigma, noise='normal'): return test_data, wmdata, bgdata -@pytest.fixture() +@pytest.fixture def gtruth(): return GroundTruth() diff --git a/mriqc/reports/group.py b/mriqc/reports/group.py index 4fa177721..4ef5e7fe1 100644 --- a/mriqc/reports/group.py +++ b/mriqc/reports/group.py @@ -45,9 +45,7 @@ def gen_html(csv_file, mod, csv_failed=None, out_file=None): load_data = Loader('mriqc') if csv_file.suffix == '.csv': - dataframe = pd.read_csv( - csv_file, index_col=False, dtype={comp: object for comp in BIDS_COMP} - ) + dataframe = pd.read_csv(csv_file, index_col=False, dtype=dict.fromkeys(BIDS_COMP, object)) id_labels = list(set(BIDS_COMP) & set(dataframe.columns)) dataframe['label'] = dataframe[id_labels].apply(_format_labels, args=(id_labels,), axis=1) diff --git a/mriqc/synthstrip/model.py b/mriqc/synthstrip/model.py index 3081d2d72..74eba9cf0 100644 --- a/mriqc/synthstrip/model.py +++ b/mriqc/synthstrip/model.py @@ -89,7 +89,7 @@ def __init__( max_pool = [max_pool] * self.nb_levels # cache downsampling / upsampling operations - MaxPooling = getattr(nn, 'MaxPool%dd' % ndims) + MaxPooling = getattr(nn, f'MaxPool{ndims}d') self.pooling = [MaxPooling(s) for s in max_pool] self.upsampling = [nn.Upsample(scale_factor=s, mode='nearest') for s in max_pool] @@ -164,7 +164,7 @@ class ConvBlock(nn.Module): def __init__(self, ndims, in_channels, out_channels, stride=1, activation='leaky'): super().__init__() - Conv = getattr(nn, 'Conv%dd' % ndims) + Conv = getattr(nn, f'Conv{ndims}d') self.conv = Conv(in_channels, out_channels, 3, stride, 1) if activation == 'leaky': self.activation = nn.LeakyReLU(0.2) diff --git a/pyproject.toml b/pyproject.toml index cf5917f56..b929f1ccb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -193,8 +193,6 @@ line-length = 99 [tool.ruff.lint] extend-select = [ - "F", - "E", "W", "I", "UP", @@ -202,10 +200,9 @@ extend-select = [ "S", "BLE", "B", - "A", # "CPY", "C4", "DTZ", - "T10", # "EM", + "T10", "EXE", "FA", "ISC", @@ -216,6 +213,7 @@ extend-select = [ ignore = [ "F841", "S311", # We are not using random for cryptographic purposes + "S310", "S603", ] @@ -224,6 +222,7 @@ inline-quotes = "single" [tool.ruff.lint.extend-per-file-ignores] "*/test_*.py" = ["S101"] +"docs/notebooks/*.ipynb" = ["B018", "F401", "F821"] "docs/source/conf.py" = ["A001"] "mriqc/bin/nib_hash.py" = ["S324"] "mriqc/config.py" = ["S105"]