### Installing pytest with pip (Shell) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localtests.md Command to install or upgrade the pytest testing framework using the pip package manager. ```Shell pip install -U pytest ``` -------------------------------- ### Installing pytest with conda (Shell) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localtests.md Command to install the pytest testing framework from the conda-forge channel using the conda package manager. ```Shell conda install -c conda-forge pytest ``` -------------------------------- ### Parameterized Pytest Tests (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localtests.md Example of a pytest test file (`test_example_functions.py`) demonstrating how to test functions imported from another module and using the `@pytest.mark.parametrize` decorator to run tests with multiple input/output combinations. ```Python #Example 2: test_example_functions.py from src.example_functions import add, remove_spaces import pytest @pytest.mark.parametrize('x, y, result', [ (10,10,20), (12,0,12), (-1,-6,-7) ]) def test_add(x, y, result): assert add(x,y) == result @pytest.mark.parametrize('data, result', [ ('a b', 'ab'), ('first last', 'firstlast') ]) def test_remove_spaces(data,result): assert remove_spaces(data,result) == result ``` -------------------------------- ### Simple Pytest Test File (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localtests.md Example of a basic pytest test file (`test_OSIPItf.py`) containing a function to be tested (`capital_case`) and a corresponding test function (`test_capital_case`) using a simple assertion. ```Python #Example 1:test_OSIPItf.py def capital_case(x): return x.capitalize() def test_capital_case(): assert capital_case('perfusion') == 'Perfusion' ``` -------------------------------- ### Configuring Seaborn Plot Styles and Options (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ExtendedToftsModel.ipynb This snippet configures the visual style for seaborn plots, setting the context to "talk" with a specific figure size and applying the "ticks" style. It also defines a dictionary `plotopts` containing common parameters for the `make_catplot` function, such as hue, column splitting, column order, dodging, wrapping, marker size, height, and aspect ratio. This setup ensures consistent styling and layout for the subsequent categorical swarm plots. ```python # set-up styling for seaborn plots #sns.set(font_scale=1.5) #sns.set_style("whitegrid") sns.set_style("ticks") sns.set_context("talk", rc={"figure.figsize": (10,8)}) plotopts = {"hue":"author", "col":"source", "col_order":["SNR 20","SNR 30","SNR 50","SNR 100","high SNR"], "dodge":True, "col_wrap":3, "s":100, "height":4, "aspect":1.25 } ``` -------------------------------- ### Calculating Parameter Errors and Defining Tolerances (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ExtendedToftsModel.ipynb This snippet calculates the absolute errors for Ktrans, ve, and vp parameters by subtracting reference values from measured values and stores them in new DataFrame columns. It also defines a dictionary specifying absolute and relative tolerances for each parameter, likely used for validation or comparison purposes. This setup is a prerequisite for subsequent error analysis and plotting. ```python df['error_Ktrans'] = df['Ktrans_meas'] - df['Ktrans_ref'] df['error_ve'] = df['ve_meas']- df['ve_ref'] df['error_vp'] = df['vp_meas']- df['vp_ref'] # tolerances tolerances = { 'Ktrans': {'atol' : 0.005, 'rtol': 0.1 },'ve': {'atol':0.05, 'rtol':0}, 'vp': {'atol':0.025, 'rtol':0}} ``` -------------------------------- ### Importing Libraries and Setting Style - Matplotlib - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv2.ipynb Imports the `os` module, `matplotlib.pyplot` for plotting, and sets a custom matplotlib style from a URL to control plot appearance. This prepares the environment for data visualization. ```python import os import matplotlib.pyplot as plt plt.style.use('https://gist.github.com/notZaki/8bfb049230e307f4432fd68d24c603a1/raw/c0baa2a1c55afdf1764b26ee2ebeb1cbf26d8d98/pltstyle') ``` -------------------------------- ### Importing OSIPI Tofts Utilities (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Imports necessary functions from the osipi_code_collection package, including utilities for Tofts model fitting, data downloading, loading, and visualization of results and errors. ```python from osipi_code_collection.wrappers.tofts import tofts_fit, show_maps, show_error_maps from osipi_code_collection.utils.nb import download_osf, loadmat ``` -------------------------------- ### Running Pytest from Command Line (Shell) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localtests.md The standard command to execute pytest tests in the current directory or specified path from the command line. ```Shell $ pytest ``` -------------------------------- ### Downloading and Loading QIBA Phantom Data (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Downloads the QIBA v6 Tofts phantom data file from a specified OSF URL to a local path and then loads the data from the .mat file into a Python variable using a utility function. ```python # Download the QIBA phantom data url = "https://osf.io/xhn3y/download" dcefile = "./data/qiba_tofts.mat" download_osf(url, dcefile); # Load the QIBA phantom data dcedata = loadmat(dcefile) ``` -------------------------------- ### Importing Libraries and Setting Plot Style (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Imports standard Python libraries like os and matplotlib.pyplot, and applies a custom matplotlib style from a URL for consistent plotting aesthetics. ```python import os import matplotlib.pyplot as plt plt.style.use('https://gist.github.com/notZaki/8bfb049230e307f4432fd68d24c603a1/raw/c0baa2a1c55afdf1764b26ee2ebeb1cbf26d8d98/pltstyle') ``` -------------------------------- ### Downloading and Loading Data - OSF/MATLAB - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv2.ipynb Imports custom functions `vfa_fit`, `show_error_maps`, `download_osf`, `loadmat`, and `make_error_map_gif`. It defines a local file path, downloads a `.mat` file containing VFA data from an OSF repository, and loads the data into a variable `vfadata`. ```python from osipi_code_collection.wrappers.vfa import vfa_fit, show_error_maps from osipi_code_collection.utils.nb import download_osf, loadmat, make_error_map_gif vfafile = "./data/vfadata_noisy.mat" download_osf("https://osf.io/3hwtc/download", vfafile) vfadata = loadmat(vfafile) ``` -------------------------------- ### Display QIBA Phantom Ground Truth Maps (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Uses the `show_maps` function from the OSIP collection to visualize the ground truth M0 and T1 parameter maps contained within the loaded `vfadata` for the QIBA v1 phantom. ```python show_maps(M0 = vfadata.M0, T1 = vfadata.T1, truth = vfadata) ``` -------------------------------- ### Displaying Sample 2CXM Reference Parameters - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CXM.ipynb Selects the 'label', 'ps_ref', 'vp_ref', 've_ref', and 'fp_ref' columns from the processed results DataFrame (df) and displays the first 23 rows using the .head() method. This provides a quick look at the reference parameter values for the initial test cases. ```python df.head(n=23)[['label','ps_ref','vp_ref', 've_ref','fp_ref']] ``` -------------------------------- ### Pushing Git Branch with Upstream - Shell Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localguide.md Pushes the local branch (e.g., 'OsipiTaskForce') and its commits to the remote repository ('origin'), setting up the upstream tracking connection. Required when pushing a new branch for the first time. ```Shell git push --set-upstream origin OsipiTaskForce ``` -------------------------------- ### Loading Test Metadata - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ParkerAIF.ipynb Loads metadata from the 'results-meta.json' file located in the parent directory's 'test' folder. This metadata likely contains information about the test results files to be processed later. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Loading Results Meta Data (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/DSC_pars.ipynb Loads metadata from a JSON file located at '../test/results-meta.json'. This metadata is expected to contain information about the result files generated by different parameter estimation methods. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Download and Load VFA Data (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Imports necessary functions from the OSIP code collection for VFA fitting and notebook utilities. It downloads a .mat file containing VFA data from an OSF repository to a local path and then loads the data from the file. ```python from osipi_code_collection.wrappers.vfa import vfa_fit, show_maps, show_error_maps from osipi_code_collection.utils.nb import download_osf, loadmat vfafile = "./data/vfadata.mat" download_osf("https://osf.io/jzu4k/download", vfafile) vfadata = loadmat(vfafile) ``` -------------------------------- ### Cloning a Git Repository - Shell Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localguide.md Clones a remote Git repository from the specified URL into a new directory on the local machine. This creates a local copy for development. ```Shell git clone https://github.com/OSIPI/DCE-DSC-MRI_CodeCollection.git ``` -------------------------------- ### Displaying QIBA Phantom Ground Truth Maps (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Visualizes the ground truth parameter maps (ktrans and ve) contained within the loaded QIBA phantom dataset using a dedicated utility function for display. ```python show_maps(kt = dcedata.kt, ve = dcedata.ve, truth = dcedata) ``` -------------------------------- ### Fitting Edinburgh1 Nonlinear Tofts Model and Showing Errors (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'edinburgh1' nonlinear least squares implementation from the OSIPI collection and displays the error maps comparing the fit results to the ground truth. ```python %%time fits = tofts_fit("edinburgh1", data = dcedata) show_error_maps(fits, truth = dcedata, clim = (-2, 2), showcbar = True) ``` -------------------------------- ### Displaying Reference Values for Patlak Test Cases - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Displays the first 9 rows of the processed DataFrame, specifically showing the voxel label and the reference values for PS and vp. This snippet serves as a quick reference table to understand the ground truth parameters for the test cases visualized or analyzed later. ```python df.head(n=9)[['voxel','ps_ref','vp_ref']] ``` -------------------------------- ### Fitting Edinburgh2 Nonlinear Tofts Model and Showing Errors (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'edinburgh2' nonlinear least squares implementation from the OSIPI collection and displays the error maps comparing the fit results to the ground truth. ```python %%time fits = tofts_fit("edinburgh2", data = dcedata) show_error_maps(fits, truth = dcedata, clim = (-2, 2), showcbar = True) ``` -------------------------------- ### Importing Libraries (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/DSC_pars.ipynb Imports necessary Python libraries for data handling (numpy, pandas, csv, json), plotting (matplotlib, seaborn), file path manipulation (os, pathlib), and custom plotting/statistics functions. ```python # import statements import os import numpy as np from matplotlib import pyplot as plt import csv import pandas as pd import seaborn as sns from plotting_results_nb import plot_bland_altman, bland_altman_statistics import json from pathlib import Path ``` -------------------------------- ### Creating and Checking Out a New Git Branch - Shell Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localguide.md Creates a new branch with the specified name (e.g., 'OsipiTaskForce') and immediately switches the working directory to that branch. Useful for isolating development work. ```Shell git checkout -b OsipiTaskForce ``` -------------------------------- ### Fitting Manchester Linear Tofts Model and Showing Errors (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'manchester' linear least squares implementation from the OSIPI collection and immediately displays the error maps comparing the fit results to the ground truth. ```python %%time fits = tofts_fit("manchester", data = dcedata) show_error_maps(fits, truth = dcedata, clim = (-2, 2), showcbar = True) ``` -------------------------------- ### Staging Files for Git Commit - Shell Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localguide.md Adds changes from the specified file (e.g., 'new_file_in_repository') to the staging area. Staged changes are included in the next commit. ```Shell git add new_file_in_repository ``` -------------------------------- ### Perform and Show Edinburgh LLS VFA Fit (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Applies the Linear Least Squares (LLS) VFA fitting method using the 'edinburgh' implementation from the OSIP collection to the loaded `vfadata`. It then displays the error maps of the fitted parameters relative to the ground truth. The `%%time` magic command is used to measure execution time. ```python %%time edinburgh_lls = fittedM0, fittedT1 = vfa_fit("edinburgh", fittype = "linear", data = vfadata) show_error_maps(edinburgh_lls, truth = vfadata, title = "Edinburgh LLS", clim = (-20, 20), showcbar = True); ``` -------------------------------- ### Fitting Oslo Nonlinear Tofts Model and Showing Errors (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'oslo' nonlinear least squares implementation from the OSIPI collection and displays the error maps comparing the fit results to the ground truth. ```python %%time fits = tofts_fit("oslo", data = dcedata, fittype = "nonlinear") show_error_maps(fits, truth = dcedata, clim = (-2, 2), showcbar = True) ``` -------------------------------- ### Perform and Show Edinburgh NLS VFA Fit (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Applies the Non-Linear Least Squares (NLS) VFA fitting method using the 'edinburgh' implementation from the OSIP collection to the loaded `vfadata`. It then displays the error maps of the fitted parameters relative to the ground truth. The `%%time` magic command is used to measure execution time. ```python %%time edinburgh_nls = vfa_fit(data = vfadata, author = "edinburgh", fittype = "nonlinear") show_error_maps(edinburgh_nls, truth = vfadata, title = "Edinburgh NLS", clim = (-20, 20), showcbar = True); ``` -------------------------------- ### Fitting Amsterdam Nonlinear Tofts Model (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'amsterdam' nonlinear least squares implementation from the OSIPI collection. The results are stored in the 'fits' variable for subsequent analysis. ```python %%time fits = tofts_fit("amsterdam", data = dcedata) ``` -------------------------------- ### Perform and Show McGill LLS VFA Fit (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Applies the Linear Least Squares (LLS) VFA fitting method using the 'mcgill' implementation from the OSIP collection to the loaded `vfadata`. It then displays the error maps of the fitted parameters relative to the ground truth. The `%%time` magic command is used to measure execution time. ```python %%time mcgill_lls = vfa_fit(author = "mcgill", fittype = "linear", data = vfadata) show_error_maps(mcgill_lls, truth = vfadata, title = "McGill LLS", clim = (-20, 20), showcbar = True); ``` -------------------------------- ### Fitting Oslo Linear Tofts Model and Showing Errors (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'oslo' linear least squares implementation from the OSIPI collection and displays the error maps comparing the fit results to the ground truth. ```python %%time fits = tofts_fit("oslo", data = dcedata, fittype = "linear") show_error_maps(fits, truth = dcedata, clim = (-2, 2), showcbar = True) ``` -------------------------------- ### Perform and Show McGill NLS VFA Fit (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Applies the Non-Linear Least Squares (NLS) VFA fitting method using the 'mcgill' implementation from the OSIP collection to the loaded `vfadata`. It then displays the error maps of the fitted parameters relative to the ground truth. The `%%time` magic command is used to measure execution time. ```python %%time mcgill_nls = vfa_fit(author = "mcgill", fittype = "nonlinear", data = vfadata) show_error_maps(mcgill_nls, truth = vfadata, title = "McGill NLS", clim = (-20, 20), showcbar = True); ``` -------------------------------- ### Running VFA Fits (LLS and NLS) - osipi_code_collection - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv2.ipynb Executes the `vfa_fit` function for both linear (LLS) and non-linear (NLS) fitting types, using implementations from different authors ("edinburgh", "sydney", "mcgill"). The `%time` magic command is used to measure the execution time for each fit. This compares the performance of different implementations on the noisy VFA data. ```python print("========================") print("LINEAR LEAST SQUARES") print(" ") print("LLS - Edinburgh") %time edinburgh_lls = vfa_fit(author = "edinburgh", fittype = "linear", data = vfadata) print(" ") print("LLS - Sydney") %time sydney_lls = vfa_fit(author = "sydney", fittype = "linear", data = vfadata) print(" ") print("LLS - McGill") %time mcgill_lls = vfa_fit(author = "mcgill", fittype = "linear", data = vfadata) print(" ") print("========================") print("NON-LINEAR LEAST SQUARES") print(" ") print("NLS - Edinburgh") %time edinburgh_nls = vfa_fit(author = "edinburgh", fittype = "nonlinear", data = vfadata) print(" ") print("NLS - Sydney") %time sydney_nls = vfa_fit(author = "sydney", fittype = "nonlinear", data = vfadata) print(" ") print("NLS - McGill") %time mcgill_nls = vfa_fit(author = "mcgill", fittype = "nonlinear", data = vfadata) print(" ") ``` -------------------------------- ### Configure Matplotlib Style (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Imports the matplotlib.pyplot library and applies a custom plot style from a specified URL to configure the appearance of subsequent plots. ```python import matplotlib.pyplot as plt plt.style.use('https://gist.github.com/notZaki/8bfb049230e307f4432fd68d24c603a1/raw/c0baa2a1c55afdf1764b26ee2ebeb1cbf26d8d98/pltstyle') ``` -------------------------------- ### Perform and Show Sydney NLS VFA Fit (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Applies the Non-Linear Least Squares (NLS) VFA fitting method using the 'sydney' implementation from the OSIP collection to the loaded `vfadata`. It then displays the error maps of the fitted parameters relative to the ground truth. The `%%time` magic command is used to measure execution time. ```python %%time sydney_nls = vfa_fit(author = "sydney", fittype = "nonlinear", data = vfadata) show_error_maps(sydney_nls, truth = vfadata, title = "Sydney NLS", clim = (-20, 20), showcbar = True); ``` -------------------------------- ### Checking Git Repository Status - Shell Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localguide.md Displays the status of the working tree, including changes that have been staged, unstaged, and untracked files. Useful for seeing the current state of the repository. ```Shell git status ``` -------------------------------- ### Perform and Show Sydney LLS VFA Fit (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/T1mapping_QIBAv1.ipynb Applies the Linear Least Squares (LLS) VFA fitting method using the 'sydney' implementation from the OSIP collection to the loaded `vfadata`. It then displays the error maps of the fitted parameters relative to the ground truth. The `%%time` magic command is used to measure execution time. ```python %%time sydney_lls = vfa_fit("sydney", fittype = "linear", data = vfadata) show_error_maps(sydney_lls, truth = vfadata, title = "Sydney LLS", clim = (-20, 20), showcbar = True); ``` -------------------------------- ### Fitting Sydney Nonlinear Tofts Model (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Performs Tofts model fitting using the 'sydney' nonlinear least squares implementation from the OSIPI collection. The results are stored in the 'fits' variable for subsequent analysis. ```python %%time fits = tofts_fit("sydney", data = dcedata) ``` -------------------------------- ### Categorizing Data Sources and Identifying Authors - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ParkerAIF.ipynb Adds a 'source' column to the consolidated DataFrame, categorizing each row based on keywords ('original', 'acq_time_', 'temp_res', 'delay') found in the 'label' column. It also extracts a list of unique authors present in the data and counts the number of unique authors. ```python # label data source df['source']='' df.loc[df['label'].str.contains('original'),'source']='original' df.loc[df['label'].str.contains('acq_time_'),'source']='acq_time' df.loc[df['label'].str.contains('temp_res'),'source']='temp_res' df.loc[df['label'].str.contains('delay'),'source']='delay' author_list = df.author.unique() no_authors = len(author_list) ``` -------------------------------- ### Calculating vp Bland-Altman Statistics (No Delay) (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CUM.ipynb Computes Bland-Altman statistics for the estimated vp parameter error, grouped by author, using results where no delay was fitted. Prints the calculated statistics. ```python resultsBA = bland_altman_statistics(data=df[~df['delay']],par='error_vp',grouptag='author') print(resultsBA) ``` -------------------------------- ### Importing Libraries for Parker AIF Analysis - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ParkerAIF.ipynb Imports standard libraries like os, numpy, matplotlib, csv, seaborn, pandas, json, and pathlib for file operations, numerical computation, plotting, data manipulation, and JSON parsing, which are required for processing and visualizing the Parker AIF test results. ```python import os import numpy from matplotlib import pyplot as plt from matplotlib.transforms import offset_copy import csv import seaborn as sns import pandas as pd import json from pathlib import Path ``` -------------------------------- ### Displaying Reference Values Head in Pandas Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ToftsModel.ipynb Displays the first 5 rows of the DataFrame `df`, specifically showing the 'voxel', 'Ktrans_ref', and 've_ref' columns. This provides a quick overview of the reference parameter values associated with each test voxel. ```python df.head(n=5)[['voxel','Ktrans_ref','ve_ref']] ``` -------------------------------- ### Import Libraries for Signal to Concentration Conversion Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/SItoC.ipynb Imports standard Python libraries like numpy, matplotlib, csv, seaborn, pandas, and json, along with project-specific modules for plotting and statistics, and pathlib for path manipulation. These libraries are required for data loading, processing, analysis, and visualization. ```python import os import numpy as np from matplotlib import pyplot as plt import csv import seaborn as sns import pandas as pd from plotting_results_nb import plot_bland_altman, bland_altman_statistics import json from pathlib import Path ``` -------------------------------- ### Importing Libraries for Preclinical AIF Analysis (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PreclinicalAIF.ipynb Imports necessary libraries for data loading, manipulation, plotting, and file handling, including numpy, matplotlib, csv, seaborn, pandas, json, and pathlib. ```python import os import numpy from matplotlib import pyplot as plt from matplotlib.transforms import offset_copy import csv import seaborn as sns import pandas as pd import json from pathlib import Path ``` -------------------------------- ### Visualizing Simulated Patlak Test Data - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Loads simulated Patlak model concentration-time data from a CSV file, extracts time and concentration arrays for each voxel, and plots the curves using Matplotlib. This snippet provides a visual overview of the input data used for model fitting. ```python #plot test data filename = ('../test/DCEmodels/data/patlak_sd_0.02_delay_0.csv') # read from CSV to pandas df1 = pd.read_csv(filename) no_voxels = len(df1.label) fig, ax = plt.subplots(1, 1, sharex='col', sharey='row', figsize=(6,6)) for currentvoxel in range(no_voxels): labelname = 'case_' + str(currentvoxel+1) testdata = df1[(df1['label']==labelname)] t = testdata['t'].to_numpy() t = np.fromstring(t[0], dtype=float, sep=' ') c = testdata['C_t'].to_numpy() c = np.fromstring(c[0], dtype=float, sep=' ') ax.plot(t, c, label=labelname) ax.set_ylabel('C (mM)', fontsize=14) ax.set_xlabel('time (ms)', fontsize=14) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0,fontsize=12); plt.xticks(fontsize=14) plt.yticks(fontsize=14); ``` -------------------------------- ### Setting up Seaborn Plot Styles and Options (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CUM.ipynb Configures seaborn plot aesthetics and defines common plotting options used for generating catplots. Sets font scale, style, and parameters like hue, dodge, size, height, and aspect. ```python sns.set(font_scale=1.5) sns.set_style("ticks") plotopts = {"hue":"author", "dodge":True, "s":100, "height":4, "aspect":3 } ``` -------------------------------- ### Importing Libraries for 2CXM Analysis - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CXM.ipynb Imports standard libraries like os, numpy, matplotlib, csv, pandas, seaborn, json, and pathlib, along with a custom module plotting_results_nb for visualization and statistics. These are required for data loading, processing, plotting, and analysis of 2CXM model results. ```python # import statements import os import numpy as np from matplotlib import pyplot as plt import csv import pandas as pd import seaborn as sns from plotting_results_nb import plot_bland_altman, bland_altman_statistics, make_catplot import json from pathlib import Path ``` -------------------------------- ### Process Loaded Data and Define Parameters Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/SItoC.ipynb Adds a 'source' column to the DataFrame based on the 'label' column to identify original data. Calculates the error between measured and reference concentration values. Defines absolute and relative tolerances for concentration comparison and sets the time step (dt) for the data. ```python # label data source df['source']='' df.loc[df['label'].str.contains('original'),'source']='original' author_list = df.author.unique() no_authors = len(author_list) voxel_list = df.label.unique() no_voxels = len(voxel_list) # calculate error between measured and reference R_1 values df['error_conc'] = df['conc_meas'] - df['conc_ref'] tolerances = { 'conc': {'atol' : 0.00001, 'rtol': 0.00001 }} dt = 2.5 # in s ``` -------------------------------- ### Importing Libraries for Patlak Model Analysis - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Imports necessary Python libraries for data handling (numpy, pandas, csv, json, pathlib), plotting (matplotlib, seaborn), and custom plotting functions (plotting_results_nb). These libraries are prerequisites for the subsequent data loading, processing, and visualization steps. ```python # import statements import os import numpy as np from matplotlib import pyplot as plt import csv import pandas as pd import seaborn as sns from plotting_results_nb import plot_bland_altman, bland_altman_statistics, make_catplot import json from pathlib import Path ``` -------------------------------- ### Loading Metadata for Test Results (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PreclinicalAIF.ipynb Loads metadata from a JSON file named "results-meta.json" located in the parent directory's "test" folder. This metadata is used to identify and locate test result files. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Loading Test Results Metadata - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CXM.ipynb Opens and loads a JSON file named results-meta.json located in the test directory. This file is expected to contain metadata about the test results, likely including file paths and other relevant information for subsequent processing. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Plotting Parker AIF Results for Varying Acquisition Times - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ParkerAIF.ipynb Filters the DataFrame for data with the 'acq_time' source. It creates a grid of subplots (acquisition times vs. authors) to visualize the measured AIF ('cb_measured') and reference AIF ('aif_ref') for each combination. Titles, axis labels, and row/column annotations are added for clarity. ```python data_acqtime = df[(df['source']=='acq_time')] acq_list = data_acqtime.label.unique() no_acq = len(acq_list) fig, ax = plt.subplots(no_acq, no_authors, sharex='col', sharey='row', figsize=(12,9)) for current_acq in range(no_acq): for current_author in range(no_authors): subset_data = data_acqtime[(data_acqtime['author'] == author_list[current_author]) & (data_acqtime['label'] == acq_list[current_acq])] ax[current_acq,current_author].plot(subset_data.time_ref, subset_data.cb_measured, color='black',label ="AIF") ax[current_acq,current_author].plot(subset_data.time_ref, subset_data.aif_ref, color='darkgrey', linestyle='dashed', label='ref') if current_acq == 0: ax[current_acq,current_author].set_title(author_list[current_author]) if current_author == 0: ax[current_acq,current_author].set_ylabel('C (mM)', fontsize=14) if current_acq == no_acq-1: ax[current_acq,current_author].set_xlabel('time (s)', fontsize=14) ax[current_acq,current_author].tick_params(axis='x', labelsize=12) ax[current_acq,current_author].tick_params(axis='y', labelsize=12) ax[no_acq-1,no_authors-1].legend(fontsize=14) # add extra labels for rows (example taken from: https://microeducate.tech/row-and-column-headers-in-matplotlibs-subplots/) pad = 5 for a, row in zip(ax[:,0], acq_list): a.annotate(row, xy=(0, 0.5), xytext=(-a.yaxis.labelpad - pad, 0), xycoords=a.yaxis.label, textcoords='offset points', ha='right', va='center', rotation=90, fontsize=14) fig.tight_layout() fig.subplots_adjust(left=0.15, top=0.95) ``` -------------------------------- ### Configuring Seaborn Plot Styles and Options Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ToftsModel.ipynb Sets up the visual style for seaborn plots, including font scale and tick style. It also defines a dictionary `plotopts` containing common parameters for the `make_catplot` function, such as hue, column splitting, ordering, dodging, size, height, and aspect ratio. ```python # set-up styling for seaborn plots sns.set(font_scale=1.5) #sns.set_style("whitegrid") sns.set_style("ticks") plotopts = {"hue":"author", "col":"source", "col_order":["SNR 20","SNR 30","SNR 50","SNR 100","high SNR"], "dodge":True, "col_wrap":3, "s":100, "height":4, "aspect":1.25 } ``` -------------------------------- ### Setting Seaborn Plot Style and Options (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Configures the global seaborn plot style and defines a dictionary of common plotting options (`plotopts`) to be reused across multiple plots. ```python sns.set(font_scale=1.5) sns.set_style("ticks") plotopts = {"hue":"author", "dodge":True, "s":100, "height":4, "aspect":3 } ``` -------------------------------- ### Visualizing 2CXM Test Data - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CXM.ipynb Loads concentration-time data from a specified CSV file into a pandas DataFrame. It then iterates through each voxel's data, extracts time and concentration arrays, and plots the concentration-time curves using matplotlib to visualize the test data. ```python #plot test data filename = ('../test/DCEmodels/data/2cxm_sd_0.001_delay_0.csv') # read from CSV to pandas df1 = pd.read_csv(filename) no_voxels = len(df1.label) fig, ax = plt.subplots(1, 1, sharex='col', sharey='row', figsize=(6,6)) for currentvoxel in range(no_voxels): labelname = 'case_' + str(currentvoxel+1) testdata = df1[(df1['label']==labelname)] t = testdata['t'].to_numpy() t = np.fromstring(t[0], dtype=float, sep=' ') c = testdata['C_t'].to_numpy() c = np.fromstring(c[0], dtype=float, sep=' ') ax.plot(t, c, label=labelname) ax.set_ylabel('C (mM)', fontsize=14) ax.set_xlabel('time (ms)', fontsize=14) plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0,fontsize=10); plt.xticks(fontsize=14) plt.yticks(fontsize=14); ``` -------------------------------- ### Modified Simple Pytest Test (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/localtests.md A modified version of the basic pytest test function (`test_capital_case`) with an additional assertion added to demonstrate a failing test case when the input 'osipi' is not capitalized as 'OSIPI'. ```Python #Example 1:test_OSIPItf.py def capital_case(x): return x.capitalize() def test_capital_case(): assert capital_case('perfusion') == 'Perfusion' assert capital_case('osipi') == 'OSIPI' ``` -------------------------------- ### Calculating Bland-Altman Statistics for vp Error with Delay (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Computes Bland-Altman statistics for the error in estimated vp values, focusing on data where a delay was fitted. The results are grouped by 'author'. ```python resultsBA = bland_altman_statistics(data=df[df['delay']],par='error_vp',grouptag='author') print(resultsBA) ``` -------------------------------- ### Loading Results Metadata (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CUM.ipynb Loads a JSON file containing metadata about test results using the `json` library, likely to identify result files for different models, categories, methods, and authors. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Importing Libraries for Tofts Model Testing - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ToftsModel.ipynb Imports standard Python libraries like numpy, pandas, and matplotlib, along with custom modules for plotting and analysis, required for processing and visualizing DCE-MRI data used in Tofts model testing. These libraries provide functionalities for data manipulation, visualization, and file handling. ```python # import statements import os import numpy as np from matplotlib import pyplot as plt import csv import pandas as pd import seaborn as sns from plotting_results_nb import plot_bland_altman, bland_altman_statistics, make_catplot import json from pathlib import Path ``` -------------------------------- ### Calculating Bland-Altman Statistics for vp Error without Delay (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Computes Bland-Altman statistics for the error in estimated vp values, focusing on data where no delay was fitted. The results are grouped by 'author'. ```python resultsBA = bland_altman_statistics(data=df[~df['delay']],par='error_vp',grouptag='author') print(resultsBA) ``` -------------------------------- ### Processing and Consolidating Test Results - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ParkerAIF.ipynb Iterates through the loaded metadata, filtering for entries related to 'PopulationAIF' and 'Parker' method. For each matching entry, it reads the specified CSV file into a pandas DataFrame, adds an 'author' column, and appends it to a list. Finally, all collected DataFrames are concatenated into a single DataFrame for further analysis. ```python # Loop over each entry and collect the dataframe df = [] for entry in meta: if (entry['category'] == 'PopulationAIF') & (entry['method'] == 'Parker') : fpath, fname, category, method, author = entry.values() df_entry = pd.read_csv(Path(fpath, fname)).assign(author=author) df.append(df_entry) # Concat all entries df = pd.concat(df) ``` -------------------------------- ### Calculating fp Bland-Altman Statistics (No Delay) (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CUM.ipynb Computes Bland-Altman statistics for the estimated fp parameter error, grouped by author, using results where no delay was fitted. Prints the calculated statistics. ```python resultsBA = bland_altman_statistics(data=df[~df['delay']],par='error_fp',grouptag='author') print(resultsBA) ``` -------------------------------- ### Plotting Bolus Arrival Time Variations - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ParkerAIF.ipynb This snippet filters data based on 'delay' source and plots the measured concentration (cb_measured) and reference AIF (aif_ref) over time for different bolus arrival times and authors. It generates a grid of subplots, zoomed to the first 50 seconds, to compare how different contributions handle variations in bolus arrival time. ```python data_delay = df[(df['source']=='delay')] delay_list = data_delay.label.unique() no_delay = len(delay_list) fig, ax = plt.subplots(no_delay, no_authors, sharex='col', sharey='row', figsize=(12,20)) for current_delay in range(no_delay): for current_author in range(no_authors): subset_data = data_delay[(data_delay['author'] == author_list[current_author]) & (data_delay['label'] == delay_list[current_delay])] ax[current_delay,current_author].plot(subset_data.time_ref, subset_data.cb_measured, color='black',label ="AIF") ax[current_delay,current_author].plot(subset_data.time_ref, subset_data.aif_ref, color='darkgrey', linestyle='dashed', label='ref') if current_delay == 0: ax[current_delay,current_author].set_title(author_list[current_author], fontsize=14) if current_author == 0: ax[current_delay,current_author].set_ylabel('C (mM)', fontsize=14) if current_delay == no_res-1: ax[current_delay,current_author].set_xlabel('time (s)', fontsize=14) ax[current_delay,current_author].set_xlim([0, 50]) ax[current_res,current_author].tick_params(axis='x', labelsize=12) ax[current_res,current_author].tick_params(axis='y', labelsize=12) ax[no_delay-1,no_authors-1].legend(fontsize=14) # add extra labels for rows pad = 5 for a, row in zip(ax[:,0], delay_list): a.annotate(row, xy=(0, 0.5), xytext=(-a.yaxis.labelpad - pad, 0), xycoords=a.yaxis.label, textcoords='offset points', ha='right', va='center', rotation=90, fontsize=14) fig.tight_layout() fig.subplots_adjust(left=0.15, top=0.95) ``` -------------------------------- ### Loading Metadata from JSON (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/GeorgiouAIF.ipynb Loads metadata from a JSON file named 'results-meta.json' located in the '../test/' directory. This metadata is expected to contain information about test results. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Loading Test Results Metadata - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ToftsModel.ipynb Loads metadata from a specified JSON file (`../test/results-meta.json`) into a Python dictionary. This metadata is used to locate and process test result files for different models and methods, including the Tofts model. Requires the `json` library. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Calculating PS Bland-Altman Statistics (No Delay) (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CUM.ipynb Computes Bland-Altman statistics for the estimated PS parameter error, grouped by author, using results where no delay was fitted. Prints the calculated statistics. ```python resultsBA = bland_altman_statistics(data=df[~df['delay']],par='error_ps',grouptag='author') print(resultsBA) ``` -------------------------------- ### Loading Test Results Metadata (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ExtendedToftsModel.ipynb Loads metadata from a JSON file named 'results-meta.json'. This metadata is expected to contain information about test results files, including file paths, names, categories, methods, and authors. The loaded data is stored in the 'meta' variable. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Loading Results Metadata - Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Loads metadata about the test results from a JSON file. This metadata likely contains file paths and information about different model implementations and authors, which is used to locate and load the actual result data files. ```python # Load the meta data meta = json.load(open("../test/results-meta.json")) ``` -------------------------------- ### Importing Libraries for Extended Tofts Model Analysis (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/ExtendedToftsModel.ipynb Imports necessary Python libraries for data manipulation, plotting, file handling, and specific DCE-MRI analysis functions. Includes standard libraries like numpy, pandas, matplotlib, csv, json, os, itertools, pathlib, and custom functions from plotting_results_nb. ```python # import statements import itertools import os import numpy as np from matplotlib import pyplot as plt import csv import pandas as pd import seaborn as sns from plotting_results_nb import plot_bland_altman, bland_altman_statistics, make_catplot import json from pathlib import Path ``` -------------------------------- ### Calculating Bland-Altman Statistics (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/SItoC.ipynb This snippet calculates Bland-Altman statistics, such as bias and limits of agreement, for the error in estimated concentration values. It uses a `bland_altman_statistics` function, providing the DataFrame (`df`), the parameter to analyze (`error_conc`), and a grouping tag (`author`). The results are then printed to the console. ```python resultsBA = bland_altman_statistics(data=df,par='error_conc',grouptag='author') print('Bias results estimated concentration values combined for all voxels') print(resultsBA) ``` -------------------------------- ### Calculate Bland-Altman Stats for vp Error (No Delay) in Python Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/2CXM.ipynb Calculates and prints Bland-Altman statistics for the bias in estimated vp values, using data where no delay was considered. Results are grouped by 'author'. ```python resultsBA = bland_altman_statistics(data=df[~df['delay']],par='error_vp',grouptag='author') print(resultsBA) ``` -------------------------------- ### Visualizing Test Data Concentration Curves (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/DSC_pars.ipynb Reads simulated concentration time curve data for DSC-MRI from a CSV file. It iterates through each voxel's data, converts the string representation of the curve to a numpy array, and plots the curves using Matplotlib to visualize the raw test data. ```python #plot test data filename = ('../test/DSCmodels/data/dsc_data.csv') # read from CSV to pandas df1 = pd.read_csv(filename) no_voxels = len(df1.label) fig, ax = plt.subplots(1, 1, sharex='col', sharey='row', figsize=(6,6)) for currentvoxel in range(no_voxels): a = df1['C_tis'][currentvoxel] c = np.fromstring(a, dtype=float, sep=' ') ax.plot(c) ax.set_ylabel('C (mM)', fontsize=14) ax.set_xlabel('index', fontsize=14) plt.xticks(fontsize=14) plt.yticks(fontsize=14); ``` -------------------------------- ### Showing Amsterdam Nonlinear Tofts Model Error Maps (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/old_nb/DCE_ToftsModel.ipynb Displays the error maps for the Tofts model fit performed by the 'amsterdam' nonlinear implementation, comparing the fit results stored in the 'fits' variable to the ground truth. ```python show_error_maps(fits, truth = dcedata, clim = (-2, 2), showcbar = True) ``` -------------------------------- ### Plotting vp Error with Delay using make_catplot (Python) Source: https://github.com/osipi/dce-dsc-mri_testresults/blob/master/docs/_sources/PatlakModel.ipynb Generates a categorical plot showing the error in estimated vp values, specifically for data points where a delay was fitted. It uses the predefined `plotopts` for styling. ```python make_catplot(x='voxel', y="error_vp", data=df[df['delay']], ylabel="$\Delta$ $v_p$ (-)", **plotopts) ```