From ce158a4b16b0ba95673d79e2cb13b64e15a49da0 Mon Sep 17 00:00:00 2001 From: TheJaeger Date: Tue, 10 Sep 2024 00:45:15 +0000 Subject: [PATCH] Pre-commit autofix --- pydesigner/Tensor_Fit_Guide.ipynb | 144 +++++++++---------- pydesigner/fitting/dwipy.py | 32 ++--- pydesigner/main.py | 16 +-- pydesigner/postprocessing/filters.py | 3 +- pydesigner/preprocessing/mrpreproc.py | 3 +- pydesigner/preprocessing/preparation.py | 3 +- pydesigner/preprocessing/util.py | 3 +- pydesigner/system/models.py | 29 ++-- pydesigner/tractography/dsistudio.py | 2 +- pydesigner/tractography/odf.py | 1 + pydesigner/tractography/sphericalsampling.py | 3 +- 11 files changed, 110 insertions(+), 129 deletions(-) diff --git a/pydesigner/Tensor_Fit_Guide.ipynb b/pydesigner/Tensor_Fit_Guide.ipynb index ff04752d..163d5982 100644 --- a/pydesigner/Tensor_Fit_Guide.ipynb +++ b/pydesigner/Tensor_Fit_Guide.ipynb @@ -24,12 +24,10 @@ "metadata": {}, "outputs": [], "source": [ - "import nibabel as nib\n", - "import numpy as np\n", - "from fitting import dwipy as dp \n", + "import os\n", + "\n", "import matplotlib.pyplot as plt\n", - "import time\n", - "import os" + "from fitting import dwipy as dp" ] }, { @@ -49,8 +47,8 @@ "metadata": {}, "outputs": [], "source": [ - "niiPath = '/Users/sid/Downloads/MUS_C_001/out/preprocessed_dwi.nii'\n", - "savePath = '/Users/sid/Downloads/MUS_C_001/out/expit2'" + "niiPath = \"/Users/sid/Downloads/MUS_C_001/out/preprocessed_dwi.nii\"\n", + "savePath = \"/Users/sid/Downloads/MUS_C_001/out/expit2\"" ] }, { @@ -133,19 +131,19 @@ } ], "source": [ - "fig = plt.figure(figsize=(18, 16), dpi= 80)\n", - "img1 = fig.add_subplot(1,3,1)\n", - "img1.imshow(myimage.img[:,:,30,0]) # Plot first volume, slice 30 (B0)\n", - "img1.title.set_text('B0')\n", - "img1.axis('off')\n", - "img2 = fig.add_subplot(1,3,2)\n", - "img2.imshow(myimage.img[:,:,30,10]) # Plot 10th volume, slice 30 (B1000)\n", - "img2.title.set_text('B1000')\n", - "img2.axis('off')\n", - "img3 = fig.add_subplot(1,3,3)\n", - "img3.imshow(myimage.img[:,:,30,60]) # Plot 70th volume, slice 30 (B2000)\n", - "img3.title.set_text('B2000')\n", - "img3.axis('off')" + "fig = plt.figure(figsize=(18, 16), dpi=80)\n", + "img1 = fig.add_subplot(1, 3, 1)\n", + "img1.imshow(myimage.img[:, :, 30, 0]) # Plot first volume, slice 30 (B0)\n", + "img1.title.set_text(\"B0\")\n", + "img1.axis(\"off\")\n", + "img2 = fig.add_subplot(1, 3, 2)\n", + "img2.imshow(myimage.img[:, :, 30, 10]) # Plot 10th volume, slice 30 (B1000)\n", + "img2.title.set_text(\"B1000\")\n", + "img2.axis(\"off\")\n", + "img3 = fig.add_subplot(1, 3, 3)\n", + "img3.imshow(myimage.img[:, :, 30, 60]) # Plot 70th volume, slice 30 (B2000)\n", + "img3.title.set_text(\"B2000\")\n", + "img3.axis(\"off\")" ] }, { @@ -185,7 +183,7 @@ } ], "source": [ - "outliers, dt_est = myimage.irlls() # Produce 4D outlier map" + "outliers, dt_est = myimage.irlls() # Produce 4D outlier map" ] }, { @@ -225,19 +223,19 @@ } ], "source": [ - "fig = plt.figure(figsize=(18, 16), dpi= 80)\n", - "img1 = fig.add_subplot(1,3,1)\n", - "img1.imshow(outliers[:,:,30,0]) # Plot first volume, slice 30 (B0)\n", - "img1.title.set_text('B0')\n", - "img1.axis('off')\n", - "img2 = fig.add_subplot(1,3,2)\n", - "img2.imshow(outliers[:,:,30,10]) # Plot 10th volume, slice 30 (B1000)\n", - "img2.title.set_text('B1000')\n", - "img2.axis('off')\n", - "img3 = fig.add_subplot(1,3,3)\n", - "img3.imshow(outliers[:,:,30,60]) # Plot 100th volume, slice 30 (B2000)\n", - "img3.title.set_text('B2000')\n", - "img3.axis('off')" + "fig = plt.figure(figsize=(18, 16), dpi=80)\n", + "img1 = fig.add_subplot(1, 3, 1)\n", + "img1.imshow(outliers[:, :, 30, 0]) # Plot first volume, slice 30 (B0)\n", + "img1.title.set_text(\"B0\")\n", + "img1.axis(\"off\")\n", + "img2 = fig.add_subplot(1, 3, 2)\n", + "img2.imshow(outliers[:, :, 30, 10]) # Plot 10th volume, slice 30 (B1000)\n", + "img2.title.set_text(\"B1000\")\n", + "img2.axis(\"off\")\n", + "img3 = fig.add_subplot(1, 3, 3)\n", + "img3.imshow(outliers[:, :, 30, 60]) # Plot 100th volume, slice 30 (B2000)\n", + "img3.title.set_text(\"B2000\")\n", + "img3.axis(\"off\")" ] }, { @@ -273,7 +271,7 @@ } ], "source": [ - "myimage.fit(constraints=[0,1,0])" + "myimage.fit(constraints=[0, 1, 0])" ] }, { @@ -346,22 +344,22 @@ } ], "source": [ - "print('This is a ' + myimage.tensorType().upper() + ' image')\n", + "print(\"This is a \" + myimage.tensorType().upper() + \" image\")\n", "\n", "DT, KT = myimage.tensorReorder(myimage.tensorType())\n", "\n", - "print('Shape of DT tensor is ' + str(DT.shape))\n", - "print('Shape of KT tensor is ' + str(KT.shape))\n", + "print(\"Shape of DT tensor is \" + str(DT.shape))\n", + "print(\"Shape of KT tensor is \" + str(KT.shape))\n", "\n", - "fig = plt.figure(figsize=(18, 16), dpi= 80)\n", - "img1 = fig.add_subplot(1,2,1)\n", - "img1.imshow(DT[:,:,30,1]) \n", - "img1.title.set_text('DT 2 2')\n", - "img1.axis('off')\n", - "img2 = fig.add_subplot(1,2,2)\n", - "img2.imshow(KT[:,:,30, 7]) \n", - "img2.title.set_text('K 2 2 2 2')\n", - "img2.axis('off')" + "fig = plt.figure(figsize=(18, 16), dpi=80)\n", + "img1 = fig.add_subplot(1, 2, 1)\n", + "img1.imshow(DT[:, :, 30, 1])\n", + "img1.title.set_text(\"DT 2 2\")\n", + "img1.axis(\"off\")\n", + "img2 = fig.add_subplot(1, 2, 2)\n", + "img2.imshow(KT[:, :, 30, 7])\n", + "img2.title.set_text(\"K 2 2 2 2\")\n", + "img2.axis(\"off\")" ] }, { @@ -421,7 +419,7 @@ } ], "source": [ - "myimage.akccorrect(akc_out=akc_out, window=7, connectivity='all')\n", + "myimage.akccorrect(akc_out=akc_out, window=7, connectivity=\"all\")\n", "mk, rk, ak, kfa, mkt, trace = myimage.extractDKI()" ] }, @@ -449,28 +447,28 @@ "metadata": {}, "outputs": [], "source": [ - "mdPath = os.path.join(savePath, 'MD.nii')\n", - "rdPath = os.path.join(savePath, 'RD.nii')\n", - "adPath = os.path.join(savePath, 'AD.nii')\n", - "faPath = os.path.join(savePath, 'FA.nii')\n", - "fePath = os.path.join(savePath, 'FE.nii')\n", - "tracePath = os.path.join(savePath, 'Trace.nii')\n", - "mkPath = os.path.join(savePath, 'MK.nii')\n", - "rkPath = os.path.join(savePath, 'RK.nii')\n", - "akPath = os.path.join(savePath, 'AK.nii')\n", - "outlierPath = os.path.join(savePath, 'Outliers_IRLLS.nii')\n", - "akcPath = os.path.join(savePath, 'Outliers_AKC.nii')\n", - "kfaPath = akPath = os.path.join(savePath, 'KFA.nii')\n", - "mktPath = os.path.join(savePath, 'MKT.nii')\n", - "dtPath = os.path.join(savePath, 'DT.nii')\n", - "ktPath = os.path.join(savePath, 'KT.nii')\n", - "awfPath = os.path.join(savePath, 'wmti_awf.nii')\n", - "easadPath = os.path.join(savePath, 'wmti_eas_ad.nii')\n", - "easrdPath = os.path.join(savePath, 'wmti_eas_rd.nii')\n", - "eastortPath = os.path.join(savePath, 'wmti_eas_tort.nii')\n", - "iasadPath = os.path.join(savePath, 'wmti_ias_ad.nii')\n", - "iasrdPath = os.path.join(savePath, 'wmti_ias_rd.nii')\n", - "iastortPath = os.path.join(savePath, 'wmti_ias_tort.nii')\n", + "mdPath = os.path.join(savePath, \"MD.nii\")\n", + "rdPath = os.path.join(savePath, \"RD.nii\")\n", + "adPath = os.path.join(savePath, \"AD.nii\")\n", + "faPath = os.path.join(savePath, \"FA.nii\")\n", + "fePath = os.path.join(savePath, \"FE.nii\")\n", + "tracePath = os.path.join(savePath, \"Trace.nii\")\n", + "mkPath = os.path.join(savePath, \"MK.nii\")\n", + "rkPath = os.path.join(savePath, \"RK.nii\")\n", + "akPath = os.path.join(savePath, \"AK.nii\")\n", + "outlierPath = os.path.join(savePath, \"Outliers_IRLLS.nii\")\n", + "akcPath = os.path.join(savePath, \"Outliers_AKC.nii\")\n", + "kfaPath = akPath = os.path.join(savePath, \"KFA.nii\")\n", + "mktPath = os.path.join(savePath, \"MKT.nii\")\n", + "dtPath = os.path.join(savePath, \"DT.nii\")\n", + "ktPath = os.path.join(savePath, \"KT.nii\")\n", + "awfPath = os.path.join(savePath, \"wmti_awf.nii\")\n", + "easadPath = os.path.join(savePath, \"wmti_eas_ad.nii\")\n", + "easrdPath = os.path.join(savePath, \"wmti_eas_rd.nii\")\n", + "eastortPath = os.path.join(savePath, \"wmti_eas_tort.nii\")\n", + "iasadPath = os.path.join(savePath, \"wmti_ias_ad.nii\")\n", + "iasrdPath = os.path.join(savePath, \"wmti_ias_rd.nii\")\n", + "iastortPath = os.path.join(savePath, \"wmti_ias_tort.nii\")\n", "dp.writeNii(md, myimage.hdr, mdPath)\n", "dp.writeNii(rd, myimage.hdr, rdPath)\n", "dp.writeNii(ad, myimage.hdr, adPath)\n", @@ -568,15 +566,15 @@ "source": [ "# fig = plt.figure(figsize=(18, 16), dpi= 80)\n", "# img1 = fig.add_subplot(1,3,1)\n", - "# img1.imshow(fa[:,:,30]) \n", + "# img1.imshow(fa[:,:,30])\n", "# img1.title.set_text('FA')\n", "# img1.axis('off')\n", "# img2 = fig.add_subplot(1,3,2)\n", - "# img2.imshow(md[:,:,30]) \n", + "# img2.imshow(md[:,:,30])\n", "# img2.title.set_text('MD')\n", "# img2.axis('off')\n", "# img3 = fig.add_subplot(1,3,3)\n", - "# img3.imshow(mk_clipped[:,:,30]) \n", + "# img3.imshow(mk_clipped[:,:,30])\n", "# img3.title.set_text('MK')\n", "# img3.axis('off')" ] diff --git a/pydesigner/fitting/dwipy.py b/pydesigner/fitting/dwipy.py index b0de0c5d..df113d24 100644 --- a/pydesigner/fitting/dwipy.py +++ b/pydesigner/fitting/dwipy.py @@ -1099,11 +1099,7 @@ def extractDTI( md = (l1 + l2 + l3) / 3 rd = (l2 + l3) / 2 ad = l1 - fa = ( - np.sqrt(1 / 2) - * np.sqrt((l1 - l2) ** 2 + (l2 - l3) ** 2 + (l3 - l1) ** 2) - / np.sqrt(l1**2 + l2**2 + l3**2) - ) + fa = np.sqrt(1 / 2) * np.sqrt((l1 - l2) ** 2 + (l2 - l3) ** 2 + (l3 - l1) ** 2) / np.sqrt(l1**2 + l2**2 + l3**2) fe = np.abs(np.stack((fa * v1[:, :, :, 0], fa * v1[:, :, :, 1], fa * v1[:, :, :, 2]), axis=3)) trace = vectorize(trace.T, self.mask) return md, rd, ad, fa, fe, trace @@ -1370,9 +1366,7 @@ def __costCalculator(grid, BT, GT, b0, IMG, iDT, iaDT, zeta, shB, Pl0, g2l_fa_R_ (-BT[b] * (1 - awf) ** -1) * np.diag((GT[b].dot((iDT - (awf**3 * zeta**-2) * iaDT).dot(GT[b].T)))) ) - ) * ( - 1 - awf - ) # Eq. 3 FBWM paper + ) * (1 - awf) # Eq. 3 FBWM paper Sa = (2 * np.pi * b0 * zeta * np.sqrt(np.pi / BT[b])) * ( shB[b].dot((Pl0 * g2l_fa_R_b[b, idx, :][0] * clm)) ) # Eq. 4 FBM paper @@ -1557,8 +1551,7 @@ def fbi_helper( gamma((l_num + 1) / 2 + int_grid) * gamma(l_num + (3 / 2)) * ( - (-BT[b] * f_grid[idx_hyper] ** 2 * zeta**-2) - * np.ones((1, len(f_grid[idx_hyper]))) + (-BT[b] * f_grid[idx_hyper] ** 2 * zeta**-2) * np.ones((1, len(f_grid[idx_hyper]))) ).T ** int_grid / (factorial(int_grid) * gamma(l_num + (3 / 2) + int_grid) * gamma((l_num + 1) / 2)) @@ -1580,11 +1573,7 @@ def fbi_helper( idx_Y = 0 for l_num in degs[::2]: g2l_fa_R_large[idx_Y : idx_Y + (2 * l_num + 1), np.squeeze(~idx_hyper)] = npm.repmat( - ( - np.exp( - -l_num // 2 * (l_num + 1) / ((2 * BT[b] * (f_grid[~idx_hyper] ** 2 * zeta**-2))) - ) - ), + (np.exp(-l_num // 2 * (l_num + 1) / (2 * BT[b] * (f_grid[~idx_hyper] ** 2 * zeta**-2)))), (2 * l_num + 1), 1, ) # Eq. 20 FBI paper @@ -1887,7 +1876,13 @@ def fbi_helper( def extractWMTI( self, - ) -> Tuple[np.ndarray[float], np.ndarray[float], np.ndarray[float], np.ndarray[float], np.ndarray[float],]: + ) -> Tuple[ + np.ndarray[float], + np.ndarray[float], + np.ndarray[float], + np.ndarray[float], + np.ndarray[float], + ]: """Returns white matter tract integrity (WMTI) parameters. Warning: this can only be run after fitting and DWI.extractDTI(). @@ -2167,8 +2162,9 @@ def akccorrect(self, akc_out: np.ndarray[bool], window: int = 3, connectivity: s connLimit = 24 else: raise Exception( - 'Connectivity choice "{}" is invalid. Please ' - 'enter either "all" or "face".'.format(connectivity) + 'Connectivity choice "{}" is invalid. Please ' 'enter either "all" or "face".'.format( + connectivity + ) ) nVoil = np.sum(patchViol) diff --git a/pydesigner/main.py b/pydesigner/main.py index 6a3bf37e..37207d1a 100644 --- a/pydesigner/main.py +++ b/pydesigner/main.py @@ -1,5 +1,4 @@ -"""Runs the PyDesigner pipeline -""" +"""Runs the PyDesigner pipeline""" import argparse # ArgumentParser, add_argument import glob # recursive file search @@ -916,9 +915,9 @@ def main(): os.rename(mif_smoothing, working_path) # update command history cmdtable["smooth"] = [ - "designer.preprocessing.mrpreproc.smooth(input={}, " - "output={}, " - "fwhm={}".format(working_path, mif_smoothing, args.fwhm) + "designer.preprocessing.mrpreproc.smooth(input={}, " "output={}, " "fwhm={}".format( + working_path, mif_smoothing, args.fwhm + ) ] cmdtable["smooth"].append(mrinfoutil.commandhistory(working_path)[-1]) cmdtable["HEAD"] = cmdtable["smooth"] @@ -957,10 +956,9 @@ def main(): os.rename(mif_rician, working_path) # update command history cmdtable["rician"] = [ - "designer.preprocessing.mrpreproc." - "riciancorrect(input={}, " - "output={}, " - "noise={})".format(working_path, mif_rician, filetable["noisemap"].getFull()) + "designer.preprocessing.mrpreproc." "riciancorrect(input={}, " "output={}, " "noise={})".format( + working_path, mif_rician, filetable["noisemap"].getFull() + ) ] cmdtable["rician"].append(mrinfoutil.commandhistory(working_path)[-1]) cmdtable["HEAD"] = cmdtable["rician"] diff --git a/pydesigner/postprocessing/filters.py b/pydesigner/postprocessing/filters.py index f7d2fa3d..7b7ed2f0 100644 --- a/pydesigner/postprocessing/filters.py +++ b/pydesigner/postprocessing/filters.py @@ -1,8 +1,7 @@ #!/usr/bin/env python # -*- coding : utf-8 -*- -"""This module contains filter(s) for postprocessing DTI/DKI maps -""" +"""This module contains filter(s) for postprocessing DTI/DKI maps""" # --------------------------------------------------------------------- # Package Management diff --git a/pydesigner/preprocessing/mrpreproc.py b/pydesigner/preprocessing/mrpreproc.py index 79b9e348..ab8d6d55 100644 --- a/pydesigner/preprocessing/mrpreproc.py +++ b/pydesigner/preprocessing/mrpreproc.py @@ -1,8 +1,7 @@ #!/usr/bin/env python # -*- coding : utf-8 -*- -"""Utilities for running various MRtrix3's DWI preprocessing tools -""" +"""Utilities for running various MRtrix3's DWI preprocessing tools""" import os import os.path as op diff --git a/pydesigner/preprocessing/preparation.py b/pydesigner/preprocessing/preparation.py index 6026ec00..6f24ee90 100644 --- a/pydesigner/preprocessing/preparation.py +++ b/pydesigner/preprocessing/preparation.py @@ -1,8 +1,7 @@ #!/usr/bin/env python # -*- coding : utf-8 -*- -"""Adds utilities for preparing the data for eddy and analysis -""" +"""Adds utilities for preparing the data for eddy and analysis""" import os # mkdir import os.path as op # dirname, basename, join, splitext diff --git a/pydesigner/preprocessing/util.py b/pydesigner/preprocessing/util.py index 9954a23a..1fcf3a6a 100644 --- a/pydesigner/preprocessing/util.py +++ b/pydesigner/preprocessing/util.py @@ -1,5 +1,4 @@ -"""Adds utilities for the command-line interface -""" +"""Adds utilities for the command-line interface""" import json # decode import os diff --git a/pydesigner/system/models.py b/pydesigner/system/models.py index d0d92853..c8fcb274 100644 --- a/pydesigner/system/models.py +++ b/pydesigner/system/models.py @@ -1,57 +1,50 @@ import os.path as op from typing import Optional + from pydantic import BaseModel, ValidationInfo, field_validator + class modelmrtrix(BaseModel): """Define model validation for MRtrix3 CLI""" + file_input: str = None file_output: Optional[str] = None nthreads: Optional[bool] = None force: Optional[bool] = True verbose: Optional[bool] = False - @field_validator('file_input') + @field_validator("file_input") @classmethod def file_input_valid(cls, var: str, info: ValidationInfo): """Validate that input file is correct type and exists.""" if not isinstance(var, str): raise TypeError( - f"Input file path {info.field_name}: {var} is not a string " - f"type. Type entered is {type(var)}." + f"Input file path {info.field_name}: {var} is not a string " f"type. Type entered is {type(var)}." ) if not op.exists(var): - raise FileNotFoundError( - f"Input file {info.field_name}: {var} does not exist." - ) - + raise FileNotFoundError(f"Input file {info.field_name}: {var} does not exist.") - @field_validator('file_output') + @field_validator("file_output") @classmethod def file_output_valid(cls, var: str, info: ValidationInfo): """Validate output filename and parent folder.""" if not isinstance(var, str): raise TypeError( - f"Output file path {info.field_name}: {var} is not a string " - f"type. Type entered is {type(var)}." + f"Output file path {info.field_name}: {var} is not a string " f"type. Type entered is {type(var)}." ) if not op.exists(op.dirname(var)): raise FileNotFoundError( f"Parent directory {op.dirname(var)} for input file {var} does " "not exists. Please ensure that the parent folder exists." ) - + @field_validator("nthreads") @classmethod def correct_nthreads(cls, var: int, info: ValidationInfo) -> int: """Check that nthreads is a postive integer.""" if not isinstance(var, int): raise TypeError( - f"{info.field_name} is not provided as a {type(var)}. Please " - "provide a positive integer." + f"{info.field_name} is not provided as a {type(var)}. Please " "provide a positive integer." ) if var <= 0: - raise ValueError( - f"{info.field_name} needs to be a valid integer." - ) - - + raise ValueError(f"{info.field_name} needs to be a valid integer.") diff --git a/pydesigner/tractography/dsistudio.py b/pydesigner/tractography/dsistudio.py index be6a3000..bd4a9bee 100644 --- a/pydesigner/tractography/dsistudio.py +++ b/pydesigner/tractography/dsistudio.py @@ -11,7 +11,6 @@ """ - import os import os.path as op import subprocess @@ -314,6 +313,7 @@ def makefib(input, output, map=None, mask=None, n_fibers=5, scale=1, other_maps= os.remove(dirs_txt) os.remove(odf_amplitudes_nii) + path_sh = "/mnt/d/Datasets/PyDesigner_Test/test_run/metrics/dki_odf.nii" path_mask = "/mnt/d/Datasets/PyDesigner_Test/test_run/brain_mask.nii" path_out = "/mnt/d/Datasets/PyDesigner_Test/dki_odf/dki.fib" diff --git a/pydesigner/tractography/odf.py b/pydesigner/tractography/odf.py index fd432891..31dd9910 100644 --- a/pydesigner/tractography/odf.py +++ b/pydesigner/tractography/odf.py @@ -4,6 +4,7 @@ """Function for computing DTI and DKI spherical harmonics from diffusion and kurtosis tensors """ + import multiprocessing import os.path as op import warnings diff --git a/pydesigner/tractography/sphericalsampling.py b/pydesigner/tractography/sphericalsampling.py index d8864f8c..fec74354 100644 --- a/pydesigner/tractography/sphericalsampling.py +++ b/pydesigner/tractography/sphericalsampling.py @@ -1,7 +1,6 @@ #!/usr/bin/env python # -*- coding : utf-8 -*- -"""Various definitions of spherical sampling -""" +"""Various definitions of spherical sampling""" import numpy as np