├── .circleci ├── config.yml └── test_data_downloader.sh ├── .gitignore ├── .zenodo.json ├── LICENSE ├── README.rst ├── report_template.html ├── requirements.txt ├── run.py └── run_denoise.py /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Python CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-python/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | # specify the version you desire here 10 | # use `-browsers` prefix for selenium tests, e.g. `3.6.1-browsers` 11 | - image: circleci/python:3.6.1 12 | 13 | # Specify service dependencies here if necessary 14 | # CircleCI maintains a library of pre-built images 15 | # documented at https://circleci.com/docs/2.0/circleci-images/ 16 | # - image: circleci/postgres:9.4 17 | 18 | working_directory: ~/repo 19 | 20 | steps: 21 | - checkout 22 | 23 | # Download and cache dependencies 24 | - restore_cache: 25 | keys: 26 | - v1-dependencies-{{ checksum "requirements.txt" }} 27 | # fallback to using the latest cache if no exact match is found 28 | - v1-dependencies- 29 | 30 | 31 | - run: 32 | name: Install dependencies 33 | command: | 34 | python3 -m venv venv 35 | . venv/bin/activate 36 | pip install scipy 37 | pip install -r requirements.txt 38 | 39 | - save_cache: 40 | paths: 41 | - ./venv 42 | key: v1-dependencies-{{ checksum "requirements.txt" }} 43 | 44 | - restore_cache: 45 | keys: 46 | - test-data 47 | 48 | - run: 49 | name: Download test data 50 | command: | 51 | bash .circleci/test_data_downloader.sh 52 | 53 | - save_cache: 54 | paths: 55 | - ./test_data 56 | key: test-data 57 | 58 | # run tests! 59 | - run: 60 | name: Smoke test - print help 61 | command: | 62 | . venv/bin/activate 63 | ./run_denoise.py --help 64 | 65 | - run: 66 | name: Smoke test - basic denoising 67 | command: | 68 | . venv/bin/activate 69 | mkdir -p test_outputs/basic 70 | ./run_denoise.py test_data/sub-01_task-rhymejudgment_bold_space-MNI152NLin2009cAsym_preproc.nii.gz test_data/sub-01_task-rhymejudgment_bold_confounds.tsv test_outputs/basic 71 | 72 | - run: 73 | name: Smoke test - select subsest of columns 74 | command: | 75 | . venv/bin/activate 76 | mkdir -p test_outputs/subset 77 | ./run_denoise.py test_data/sub-01_task-rhymejudgment_bold_space-MNI152NLin2009cAsym_preproc.nii.gz test_data/sub-01_task-rhymejudgment_bold_confounds.tsv test_outputs/subset --col_names FramewiseDisplacement GlobalSignal 78 | 79 | - run: 80 | name: Smoke test - high pass 81 | command: | 82 | . venv/bin/activate 83 | mkdir -p test_outputs/hp 84 | ./run_denoise.py test_data/sub-01_task-rhymejudgment_bold_space-MNI152NLin2009cAsym_preproc.nii.gz test_data/sub-01_task-rhymejudgment_bold_confounds.tsv test_outputs/hp --hp_filter 0.009 85 | 86 | - run: 87 | name: Smoke test - low pass 88 | command: | 89 | . venv/bin/activate 90 | mkdir -p test_outputs/lp 91 | ./run_denoise.py test_data/sub-01_task-rhymejudgment_bold_space-MNI152NLin2009cAsym_preproc.nii.gz test_data/sub-01_task-rhymejudgment_bold_confounds.tsv test_outputs/lp --lp_filter 0.1 92 | 93 | - store_artifacts: 94 | path: test_outputs 95 | destination: test_outputs 96 | -------------------------------------------------------------------------------- /.circleci/test_data_downloader.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -x 3 | set -e 4 | if [ ! -e test_data ]; then 5 | mkdir test_data 6 | wget http://openneuro.outputs.s3.amazonaws.com/091b91a257f6b517790f2fb82a784c8e/3e22d7c1-c7e8-4cc7-bfdd-c89dd6681982/fmriprep/sub-01/func/sub-01_task-rhymejudgment_bold_space-MNI152NLin2009cAsym_preproc.nii.gz -O test_data/sub-01_task-rhymejudgment_bold_space-MNI152NLin2009cAsym_preproc.nii.gz 7 | wget http://openneuro.outputs.s3.amazonaws.com/091b91a257f6b517790f2fb82a784c8e/3e22d7c1-c7e8-4cc7-bfdd-c89dd6681982/fmriprep/sub-01/func/sub-01_task-rhymejudgment_bold_confounds.tsv -O test_data/sub-01_task-rhymejudgment_bold_confounds.tsv 8 | fi 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | .idea/ -------------------------------------------------------------------------------- /.zenodo.json: -------------------------------------------------------------------------------- 1 | { 2 | "title": "Denoiser: A nuisance regression tool for fMRI BOLD data", 3 | "description": "

Denoiser is a tool for removing sources of noise from and performing temporal filtering of functional MRI data. It also provides visualization of the content of nuisance signals (including motion information, if provided), allowing the user to get a quick sense of data quality before and after noise removal.

", 4 | "creators": [ 5 | { 6 | "affiliation": "Department of Neurobiology and Behavior, Center for the Neurobiology of Learning and Memory, University of California Irvine", 7 | "name": "Tambini, Arielle", 8 | "orcid": "0000-0001-9200-9165" 9 | }, 10 | { 11 | "affiliation": "Department of Psychology, Stanford University", 12 | "name": "Gorgolewski, Krzysztof J.", 13 | "orcid": "0000-0003-3321-7583" 14 | } 15 | ], 16 | "keywords": [ 17 | "neuroimaging", 18 | "preprocessing", 19 | "fMRI" 20 | ], 21 | "license": "Apache-2.0", 22 | "upload_type": "software" 23 | } 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Denoiser: A nuisance regression tool for fMRI BOLD data 2 | ======================================================= 3 | 4 | ``Denoiser`` is a tool for removing sources of noise from and performing temporal filtering 5 | of functional MRI data. It also provides visualization of the content of nuisance signals 6 | (including *motion* information, if provided), allowing the user to get a quick sense of 7 | data quality before and after noise removal. 8 | 9 | Denoiser acts on 4D fMRI data (takes either a nifti file path or an already loaded nibabel 10 | object as input). Nuisance signal removal and temporal filtering are performed on a 11 | voxel-wise level, and a 'cleaned' 4D Nifti file (``_NR`` file)/ nibabel object are created 12 | as outputs. 13 | 14 | The specific noise signals to be removed are specified by the user (contained in a tsv file). 15 | This tool should be used only **after** BOLD data are *minimally preprocessed* (for example, 16 | after preprocessing the data using ``fmriprep``, which creates a .tsv file containing nuisance signals). 17 | 18 | .. image:: https://zenodo.org/badge/4033784/arielletambini/denoiser.svg 19 | :target: https://zenodo.org/badge/latestdoi/4033784/arielletambini/denoiser 20 | 21 | 22 | 23 | For instructions on how to run, type: python run_denoise.py -h:: 24 | 25 | usage: run_denoise.py [-h] [--col_names COL_NAMES [COL_NAMES ...]] [--hp_filter HP_FILTER] [--lp_filter LP_FILTER] [--out_figure_path OUT_FIGURE_PATH] img_file tsv_file out_path 26 | 27 | Function for performing nuisance regression. Saves resulting output nifti file, information about nuisance 28 | regressors and motion (html report), and outputs nibabel object containing clean data 29 | 30 | positional arguments: 31 | img_file 4d nifti img: file path or nibabel object loaded into memory 32 | tsv_file tsv file containing nuisance regressors to be removed 33 | out_path output directory for saving new data file 34 | 35 | optional arguments: 36 | -h, --help show this help message and exit 37 | --col_names COL_NAMES [COL_NAMES ...] 38 | which columns of TSV file to include as nuisance regressors. defaults to ALL columns. 39 | --hp_filter HP_FILTER 40 | frequency cut-off for high pass filter (removing low frequencies). Recommend .009 Hz 41 | --lp_filter LP_FILTER 42 | frequency cut-off for low pass filter (removing high frequencies). Recommend .1 Hz for non-task data 43 | --out_figure_path OUT_FIGURE_PATH 44 | output directory for saving figures. Defaults to location of out_path + _figures 45 | 46 | 47 | If you run into troubles using the tool or have any questions please post them `here `_. 48 | -------------------------------------------------------------------------------- /report_template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 |

Denoising Report for:

11 |

{{ img_file }}

12 | 13 |
14 | 15 |

Output 'Cleaned' file:

16 |

{{ save_img_file }}

17 | 18 |
19 |

{{ Ntrs }} TRs detected

20 | 21 |

Nuisance signal file:

22 |

{{ tsv_file }}

23 | 24 |

Signals removed:

25 | 30 | 31 | {% if hp_filter %} 32 | 33 |

High-pass filter applied [frequencies < {{ hp_filter }} removed]

34 | {% else %} 35 |

***NO additional high-pass filter applied***

36 |

Note that if Nuisance regressors contain low-frequency DRIFT and if low-frequency cosines were not included as Nuisance regressors - drift-like content will be present in 'cleaned' output data!!

37 | {% endif %} 38 | 39 | {% if lp_filter %} 40 |

Low-pass filter applied [frequencies > {{ lp_filter }} removed]

41 | {% else %} 42 |

NO Low-pass filter applied

43 | {% endif %} 44 | 45 |
46 | 47 |

Nuisance Regressor Information

48 | Nuisance Design Matrix 50 | 51 | Nuisance Corr Matrix 53 | 54 |
55 | 56 |

Motion Information

57 |

FD timeseries plot

59 | 60 |
61 | 62 |

Data (voxel time series) before and after Nuisance Regression

63 |

carpet plots

65 | 66 |
67 | 68 |

Nuisance Regressor Stat Maps

69 | 70 |

Total Nuisance R2 Map

71 |

R squared map

73 |
74 | 75 | {% for item in file_tstat %} 76 | 77 |

{{ item.name }} Tstat Map

78 |

{{ item.name }} Map

80 |
81 | {% endfor %} 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | nilearn==0.7.0 2 | nibabel 3 | numpy 4 | pandas 5 | matplotlib 6 | scipy 7 | sklearn 8 | patsy 9 | seaborn 10 | jinja2 11 | nitime 12 | nipype 13 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | print("I'm running!") -------------------------------------------------------------------------------- /run_denoise.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from nilearn.glm import regression 3 | from nilearn.glm.first_level.design_matrix import make_first_level_design_matrix 4 | import nibabel as nb 5 | import numpy as np 6 | import os, pandas, sys, pdb, argparse, copy, scipy, jinja2 7 | from os.path import join as pjoin 8 | from nilearn import plotting 9 | from nilearn.signal import butterworth 10 | from nilearn.input_data import NiftiMasker 11 | 12 | import matplotlib 13 | import pylab as plt 14 | import seaborn as sns 15 | from nilearn._utils.niimg import load_niimg 16 | from nipype.algorithms import confounds as nac 17 | 18 | parser = argparse.ArgumentParser(description='Function for performing nuisance regression. Saves resulting output ' 19 | 'nifti file, information about nuisance regressors and motion (html ' 20 | 'report), and outputs nibabel object containing clean data') 21 | parser.add_argument('img_file', help='4d nifti img: file path or nibabel object loaded into memory') 22 | parser.add_argument('tsv_file', help='tsv file containing nuisance regressors to be removed') 23 | parser.add_argument('out_path', help='output directory for saving new data file') 24 | parser.add_argument('--col_names', 25 | help='which columns of TSV file to include as nuisance regressors. defaults to ALL columns.', 26 | nargs="+") 27 | parser.add_argument('--hp_filter', help='frequency cut-off for high pass filter (removing low frequencies). Recommend ' 28 | '.009 Hz') 29 | parser.add_argument('--lp_filter', help='frequency cut-off for low pass filter (removing high frequencies). Recommend ' 30 | '.1 Hz for non-task data') 31 | parser.add_argument('--out_figure_path', 32 | help='output directory for saving figures. Defaults to location of out_path + _figures') 33 | 34 | args = parser.parse_args() 35 | 36 | img_file = args.img_file 37 | tsv_file = args.tsv_file 38 | out_path = args.out_path 39 | col_names = args.col_names 40 | hp_filter = args.hp_filter 41 | lp_filter = args.lp_filter 42 | out_figure_path = args.out_figure_path 43 | 44 | 45 | def denoise(img_file, tsv_file, out_path, col_names=False, hp_filter=False, lp_filter=False, out_figure_path=False): 46 | nii_ext = '.nii.gz' 47 | FD_thr = [.5] 48 | sc_range = np.arange(-1, 3) 49 | constant = 'constant' 50 | 51 | # read in files 52 | img = load_niimg(img_file) 53 | # get file info 54 | img_name = os.path.basename(img.get_filename()) 55 | file_base = img_name[0:img_name.find('.')] 56 | save_img_file = pjoin(out_path, file_base + \ 57 | '_NR' + nii_ext) 58 | data = img.get_fdata() 59 | df_orig = pandas.read_csv(tsv_file, '\t', na_values='n/a') 60 | df = copy.deepcopy(df_orig) 61 | Ntrs = df.values.shape[0] 62 | print('# of TRs: ' + str(Ntrs)) 63 | assert (Ntrs == data.shape[len(data.shape) - 1]) 64 | 65 | # select columns to use as nuisance regressors 66 | if col_names: 67 | df = df[col_names] 68 | str_append = ' [SELECTED regressors in CSV]' 69 | else: 70 | col_names = df.columns.tolist() 71 | str_append = ' [ALL regressors in CSV]' 72 | 73 | # fill in missing nuisance values with mean for that variable 74 | for col in df.columns: 75 | if sum(df[col].isnull()) > 0: 76 | print('Filling in ' + str(sum(df[col].isnull())) + ' NaN value for ' + col) 77 | df[col] = df[col].fillna(np.mean(df[col])) 78 | print('# of Confound Regressors: ' + str(len(df.columns)) + str_append) 79 | 80 | # implement HP filter in regression 81 | TR = img.header.get_zooms()[-1] 82 | frame_times = np.arange(Ntrs) * TR 83 | if hp_filter: 84 | hp_filter = float(hp_filter) 85 | assert (hp_filter > 0) 86 | df = make_first_level_design_matrix(frame_times, high_pass=hp_filter, add_regs=df.values, 87 | add_reg_names=df.columns.tolist()) 88 | # fn adds intercept into dm 89 | 90 | hp_cols = [col for col in df.columns if 'drift' in col] 91 | print('# of High-pass Filter Regressors: ' + str(len(hp_cols))) 92 | else: 93 | # add in intercept column into data frame 94 | df[constant] = 1 95 | print('No High-pass Filter Applied') 96 | 97 | dm = df.values 98 | 99 | # prep data 100 | data = np.reshape(data, (-1, Ntrs)) 101 | data_mean = np.mean(data, axis=1) 102 | Nvox = len(data_mean) 103 | 104 | # setup and run regression 105 | model = regression.OLSModel(dm) 106 | results = model.fit(data.T) 107 | if not hp_filter: 108 | results_orig_resid = copy.deepcopy(results.residuals) # save for rsquared computation 109 | 110 | # apply low-pass filter 111 | if lp_filter: 112 | # input to butterworth fn is time x voxels 113 | low_pass = float(lp_filter) 114 | Fs = 1. / TR 115 | if low_pass >= Fs / 2: 116 | raise ValueError('Low pass filter cutoff if too close to the Nyquist frequency (%s)' % (Fs / 2)) 117 | 118 | temp_img_file = pjoin(out_path, file_base + \ 119 | '_temp' + nii_ext) 120 | temp_img = nb.Nifti1Image(np.reshape(results.residuals.T + np.reshape(data_mean, (Nvox, 1)), img.shape).astype('float32'), 121 | img.affine, header=img.header) 122 | temp_img.to_filename(temp_img_file) 123 | results.residuals = butterworth(results.residuals, sampling_rate=Fs, low_pass=low_pass, high_pass=None) 124 | print('Low-pass Filter Applied: < ' + str(low_pass) + ' Hz') 125 | 126 | # add mean back into data 127 | clean_data = results.residuals.T + np.reshape(data_mean, (Nvox, 1)) # add mean back into residuals 128 | 129 | # save out new data file 130 | print('Saving output file...') 131 | clean_data = np.reshape(clean_data, img.shape).astype('float32') 132 | new_img = nb.Nifti1Image(clean_data, img.affine, header=img.header) 133 | new_img.to_filename(save_img_file) 134 | 135 | ######### generate Rsquared map for confounds only 136 | if hp_filter: 137 | # first remove low-frequency information from data 138 | hp_cols.append(constant) 139 | model_first = regression.OLSModel(df[hp_cols].values) 140 | results_first = model_first.fit(data.T) 141 | results_first_resid = copy.deepcopy(results_first.residuals) 142 | del results_first, model_first 143 | 144 | # compute sst - borrowed from matlab 145 | sst = np.square(np.linalg.norm(results_first_resid - 146 | np.mean(results_first_resid, axis=0), axis=0)) 147 | 148 | # now regress out 'true' confounds to estimate their Rsquared 149 | nr_cols = [col for col in df.columns if 'drift' not in col] 150 | model_second = regression.OLSModel(df[nr_cols].values) 151 | results_second = model_second.fit(results_first_resid) 152 | 153 | # compute sse - borrowed from matlab 154 | sse = np.square(np.linalg.norm(results_second.residuals, axis=0)) 155 | 156 | del results_second, model_second, results_first_resid 157 | 158 | elif not hp_filter: 159 | # compute sst - borrowed from matlab 160 | sst = np.square(np.linalg.norm(data.T - 161 | np.mean(data.T, axis=0), axis=0)) 162 | 163 | # compute sse - borrowed from matlab 164 | sse = np.square(np.linalg.norm(results_orig_resid, axis=0)) 165 | 166 | del results_orig_resid 167 | 168 | # compute rsquared of nuisance regressors 169 | zero_idx = np.logical_and(sst == 0, sse == 0) 170 | sse[zero_idx] = 1 171 | sst[zero_idx] = 1 # would be NaNs - become rsquared = 0 172 | rsquare = 1 - np.true_divide(sse, sst) 173 | rsquare[np.isnan(rsquare)] = 0 174 | 175 | ######### Visualizing DM & outputs 176 | fontsize = 12 177 | fontsize_title = 14 178 | def_img_size = 8 179 | 180 | if not out_figure_path: 181 | out_figure_path = save_img_file[0:save_img_file.find('.')] + '_figures' 182 | 183 | if not os.path.isdir(out_figure_path): 184 | os.mkdir(out_figure_path) 185 | png_append = '_' + img_name[0:img_name.find('.')] + '.png' 186 | print('Output directory: ' + out_figure_path) 187 | 188 | # DM corr matrix 189 | cm = df[df.columns[0:-1]].corr() 190 | curr_sz = copy.deepcopy(def_img_size) 191 | if cm.shape[0] > def_img_size: 192 | curr_sz = curr_sz + ((cm.shape[0] - curr_sz) * .3) 193 | mtx_scale = curr_sz * 100 194 | 195 | mask = np.zeros_like(cm, dtype=np.bool) 196 | mask[np.triu_indices_from(mask)] = True 197 | 198 | fig, ax = plt.subplots(figsize=(curr_sz, curr_sz)) 199 | cmap = sns.diverging_palette(220, 10, as_cmap=True) 200 | sns.heatmap(cm, mask=mask, cmap=cmap, center=0, vmax=cm[cm < 1].max().max(), vmin=cm[cm < 1].min().min(), 201 | square=True, linewidths=.5, cbar_kws={"shrink": .6}) 202 | ax.set_xticklabels(ax.get_xticklabels(), rotation=60, ha='right', fontsize=fontsize) 203 | ax.set_yticklabels(cm.columns.tolist(), rotation=-30, va='bottom', fontsize=fontsize) 204 | ax.set_title('Nuisance Corr. Matrix', fontsize=fontsize_title) 205 | plt.tight_layout() 206 | file_corr_matrix = 'Corr_matrix_regressors' + png_append 207 | fig.savefig(pjoin(out_figure_path, file_corr_matrix)) 208 | plt.close(fig) 209 | del fig, ax 210 | 211 | # DM of Nuisance Regressors (all) 212 | tr_label = 'TR (Volume #)' 213 | fig, ax = plt.subplots(figsize=(curr_sz - 4.1, def_img_size)) 214 | x_scale_html = ((curr_sz - 4.1) / def_img_size) * 890 215 | plotting.plot_design_matrix(df, ax=ax) 216 | ax.set_title('Nuisance Design Matrix', fontsize=fontsize_title) 217 | ax.set_xticklabels(ax.get_xticklabels(), rotation=60, ha='right', fontsize=fontsize) 218 | ax.set_yticklabels(ax.get_yticklabels(), fontsize=fontsize) 219 | ax.set_ylabel(tr_label, fontsize=fontsize) 220 | plt.tight_layout() 221 | file_design_matrix = 'Design_matrix' + png_append 222 | fig.savefig(pjoin(out_figure_path, file_design_matrix)) 223 | plt.close(fig) 224 | del fig, ax 225 | 226 | # FD timeseries plot 227 | FD = 'FD' 228 | poss_names = ['FramewiseDisplacement', FD, 'framewisedisplacement', 'fd', 'framewise_displacement'] 229 | fd_idx = [df_orig.columns.__contains__(i) for i in poss_names] 230 | if np.sum(fd_idx) > 0: 231 | FD_name = np.array(poss_names)[fd_idx][0] #poss_names[fd_idx == True] 232 | if sum(df_orig[FD_name].isnull()) > 0: 233 | df_orig[FD_name] = df_orig[FD_name].fillna(np.mean(df_orig[FD_name])) 234 | y = df_orig[FD_name].values 235 | Nremove = [] 236 | sc_idx = [] 237 | for thr_idx, thr in enumerate(FD_thr): 238 | idx = y >= thr 239 | sc_idx.append(copy.deepcopy(idx)) 240 | for iidx in np.where(idx)[0]: 241 | for buffer in sc_range: 242 | curr_idx = iidx + buffer 243 | if curr_idx >= 0 and curr_idx <= len(idx): 244 | sc_idx[thr_idx][curr_idx] = True 245 | Nremove.append(np.sum(sc_idx[thr_idx])) 246 | 247 | Nplots = len(FD_thr) 248 | sns.set(font_scale=1.5) 249 | sns.set_style('ticks') 250 | fig, axes = plt.subplots(Nplots, 1, figsize=(def_img_size * 1.5, def_img_size / 2), squeeze=False) 251 | sns.despine() 252 | bound = .4 253 | fd_mean = np.mean(y) 254 | for curr in np.arange(0, Nplots): 255 | axes[curr, 0].plot(y) 256 | axes[curr, 0].plot((-bound, Ntrs + bound), FD_thr[curr] * np.ones((1, 2))[0], '--', color='black') 257 | axes[curr, 0].scatter(np.arange(0, Ntrs), y, s=20) 258 | 259 | if Nremove[curr] > 0: 260 | info = scipy.ndimage.measurements.label(sc_idx[curr]) 261 | for cluster in np.arange(1, info[1] + 1): 262 | temp = np.where(info[0] == cluster)[0] 263 | axes[curr, 0].axvspan(temp.min() - bound, temp.max() + bound, alpha=.5, color='red') 264 | 265 | axes[curr, 0].set_ylabel('Framewise Disp. (' + FD + ')') 266 | axes[curr, 0].set_title(FD + ': ' + str(100 * Nremove[curr] / Ntrs)[0:4] 267 | + '% of scan (' + str(Nremove[curr]) + ' volumes) would be scrubbed (FD thr.= ' + 268 | str(FD_thr[curr]) + ')') 269 | plt.text(Ntrs + 1, FD_thr[curr] - .01, FD + ' = ' + str(FD_thr[curr]), fontsize=fontsize) 270 | plt.text(Ntrs, fd_mean - .01, 'avg = ' + str(fd_mean), fontsize=fontsize) 271 | axes[curr, 0].set_xlim((-bound, Ntrs + 8)) 272 | 273 | plt.tight_layout() 274 | axes[curr, 0].set_xlabel(tr_label) 275 | file_fd_plot = FD + '_timeseries' + png_append 276 | fig.savefig(pjoin(out_figure_path, file_fd_plot)) 277 | plt.close(fig) 278 | del fig, axes 279 | print(FD + ' timeseries plot saved') 280 | 281 | else: 282 | print(FD + ' not found: ' + FD + ' timeseries not plotted') 283 | file_fd_plot = None 284 | 285 | # Carpet and DVARS plots - before & after nuisance regression 286 | 287 | # need to create mask file to input to DVARS function 288 | mask_file = pjoin(out_figure_path, 'mask_temp.nii.gz') 289 | nifti_masker = NiftiMasker(mask_strategy='epi', standardize=False) 290 | nifti_masker.fit(img) 291 | nifti_masker.mask_img_.to_filename(mask_file) 292 | 293 | # create 2 or 3 carpet plots, depending on if LP filter is also applied 294 | Ncarpet = 2 295 | total_sz = int(16) 296 | carpet_scale = 840 297 | y_labels = ['Input (voxels)', 'Output \'cleaned\''] 298 | imgs = [img, new_img] 299 | img_files = [img_file, save_img_file] 300 | color = ['red', 'salmon'] 301 | labels = ['input', 'cleaned'] 302 | if lp_filter: 303 | Ncarpet = 3 304 | total_sz = int(20) 305 | carpet_scale = carpet_scale * (9/8) 306 | y_labels = ['Input', 'Clean Pre-LP', 'Clean LP'] 307 | imgs.insert(1, temp_img) 308 | img_files.insert(1, temp_img_file) 309 | color.insert(1, 'firebrick') 310 | labels.insert(1, 'clean pre-LP') 311 | labels[-1] = 'clean LP' 312 | 313 | dvars = [] 314 | print('Computing dvars...') 315 | for in_file in img_files: 316 | temp = nac.compute_dvars(in_file=in_file, in_mask=mask_file)[1] 317 | dvars.append(np.hstack((temp.mean(), temp))) 318 | del temp 319 | 320 | small_sz = 2 321 | fig = plt.figure(figsize=(def_img_size * 1.5, def_img_size + ((Ncarpet - 2) * 1))) 322 | row_used = 0 323 | if np.sum(fd_idx) > 0: # if FD data is available 324 | row_used = row_used + small_sz 325 | ax0 = plt.subplot2grid((total_sz, 1), (0, 0), rowspan=small_sz) 326 | ax0.plot(y) 327 | ax0.scatter(np.arange(0, Ntrs), y, s=10) 328 | curr = 0 329 | if Nremove[curr] > 0: 330 | info = scipy.ndimage.measurements.label(sc_idx[curr]) 331 | for cluster in np.arange(1, info[1] + 1): 332 | temp = np.where(info[0] == cluster)[0] 333 | ax0.axvspan(temp.min() - bound, temp.max() + bound, alpha=.5, color='red') 334 | ax0.set_ylabel(FD) 335 | 336 | for side in ["top", "right", "bottom"]: 337 | ax0.spines[side].set_color('none') 338 | ax0.spines[side].set_visible(False) 339 | 340 | ax0.set_xticks([]) 341 | ax0.set_xlim((-.5, Ntrs - .5)) 342 | ax0.spines["left"].set_position(('outward', 10)) 343 | 344 | ax_d = plt.subplot2grid((total_sz, 1), (row_used, 0), rowspan=small_sz) 345 | for iplot in np.arange(len(dvars)): 346 | ax_d.plot(dvars[iplot], color=color[iplot], label=labels[iplot]) 347 | ax_d.set_ylabel('DVARS') 348 | for side in ["top", "right", "bottom"]: 349 | ax_d.spines[side].set_color('none') 350 | ax_d.spines[side].set_visible(False) 351 | ax_d.set_xticks([]) 352 | ax_d.set_xlim((-.5, Ntrs - .5)) 353 | ax_d.spines["left"].set_position(('outward', 10)) 354 | ax_d.legend(fontsize=fontsize - 2) 355 | row_used = row_used + small_sz 356 | 357 | st = 0 358 | carpet_each = int((total_sz - row_used) / Ncarpet) 359 | for idx, img_curr in enumerate(imgs): 360 | ax_curr = plt.subplot2grid((total_sz, 1), (row_used + st, 0), rowspan=carpet_each) 361 | fig = plotting.plot_carpet(img_curr, figure=fig, axes=ax_curr) 362 | ax_curr.set_ylabel(y_labels[idx]) 363 | for side in ["bottom", "left"]: 364 | ax_curr.spines[side].set_position(('outward', 10)) 365 | 366 | if idx < len(imgs)-1: 367 | ax_curr.spines["bottom"].set_visible(False) 368 | ax_curr.set_xticklabels('') 369 | ax_curr.set_xlabel('') 370 | st = st + carpet_each 371 | 372 | file_carpet_plot = 'Carpet_plots' + png_append 373 | fig.savefig(pjoin(out_figure_path, file_carpet_plot)) 374 | plt.close() 375 | del fig, ax0, ax_curr, ax_d, dvars 376 | os.remove(mask_file) 377 | print('Carpet/DVARS plots saved') 378 | if lp_filter: 379 | os.remove(temp_img_file) 380 | del temp_img 381 | 382 | # Display T-stat maps for nuisance regressors 383 | # create mean img 384 | img_size = (img.shape[0], img.shape[1], img.shape[2]) 385 | mean_img = nb.Nifti1Image(np.reshape(data_mean, img_size), img.affine) 386 | mx = [] 387 | for idx, col in enumerate(df.columns): 388 | if not 'drift' in col and not constant in col: 389 | con_vector = np.zeros((1, df.shape[1])) 390 | con_vector[0, idx] = 1 391 | con = results.Tcontrast(con_vector) 392 | mx.append(np.max(np.absolute([con.t.min(), con.t.max()]))) 393 | mx = .8 * np.max(mx) 394 | t_png = 'Tstat_' 395 | file_tstat = [] 396 | for idx, col in enumerate(df.columns): 397 | if not 'drift' in col and not constant in col: 398 | con_vector = np.zeros((1, df.shape[1])) 399 | con_vector[0, idx] = 1 400 | con = results.Tcontrast(con_vector) 401 | m_img = nb.Nifti1Image(np.reshape(con, img_size), img.affine) 402 | 403 | title_str = col + ' Tstat' 404 | fig = plotting.plot_stat_map(m_img, mean_img, threshold=3, colorbar=True, display_mode='z', vmax=mx, 405 | title=title_str, 406 | cut_coords=7) 407 | file_temp = t_png + col + png_append 408 | fig.savefig(pjoin(out_figure_path, file_temp)) 409 | file_tstat.append({'name': col, 'file': file_temp}) 410 | plt.close() 411 | del fig, file_temp 412 | print(title_str + ' map saved') 413 | 414 | # Display R-sq map for nuisance regressors 415 | m_img = nb.Nifti1Image(np.reshape(rsquare, img_size), img.affine) 416 | title_str = 'Nuisance Rsq' 417 | mx = .95 * rsquare.max() 418 | fig = plotting.plot_stat_map(m_img, mean_img, threshold=.2, colorbar=True, display_mode='z', vmax=mx, 419 | title=title_str, 420 | cut_coords=7) 421 | file_rsq_map = 'Rsquared' + png_append 422 | fig.savefig(pjoin(out_figure_path, file_rsq_map)) 423 | plt.close() 424 | del fig 425 | print(title_str + ' map saved') 426 | 427 | ######### html report 428 | templateLoader = jinja2.FileSystemLoader(searchpath="/") 429 | templateEnv = jinja2.Environment(loader=templateLoader) 430 | 431 | templateVars = {"img_file": img_file, 432 | "save_img_file": save_img_file, 433 | "Ntrs": Ntrs, 434 | "tsv_file": tsv_file, 435 | "col_names": col_names, 436 | "hp_filter": hp_filter, 437 | "lp_filter": lp_filter, 438 | "file_design_matrix": file_design_matrix, 439 | "file_corr_matrix": file_corr_matrix, 440 | "file_fd_plot": file_fd_plot, 441 | "file_rsq_map": file_rsq_map, 442 | "file_tstat": file_tstat, 443 | "x_scale": x_scale_html, 444 | "mtx_scale": mtx_scale, 445 | "file_carpet_plot": file_carpet_plot, 446 | "carpet_scale": carpet_scale 447 | } 448 | 449 | TEMPLATE_FILE = pjoin(os.getcwd(), "report_template.html") 450 | template = templateEnv.get_template(TEMPLATE_FILE) 451 | 452 | outputText = template.render(templateVars) 453 | 454 | html_file = pjoin(out_figure_path, img_name[0:img_name.find('.')] + '.html') 455 | with open(html_file, "w") as f: 456 | f.write(outputText) 457 | 458 | print('') 459 | print('HTML report: ' + html_file) 460 | return new_img 461 | 462 | denoise(img_file, tsv_file, out_path, col_names, hp_filter, lp_filter, out_figure_path) 463 | --------------------------------------------------------------------------------