This notebook provides examples of analysis of resting fMRI.

To grab the data, you should first do the following:

bash ~/fmri-analysis-vm/get_resting.sh

This will grab 4 sessions of resting data from ses-105, along with the field maps for this session. These data have been motion-corrected to a common target so that they are aligned to one another. The motion parameter files are derived separately from each session, rather than using the common target.

Credit:


In [2]:
import os,glob
import nibabel
import numpy
import sklearn
import nilearn.input_data
from nilearn.plotting import plot_roi
from nilearn.image.image import mean_img
from nilearn.plotting import plot_stat_map, show
from nilearn.image import index_img,clean_img
from nilearn.decomposition import CanICA
from sklearn.decomposition import FastICA,PCA

import matplotlib.pyplot as plt
from nipype.interfaces import fsl, nipy
from nipype.caching import Memory
mem = Memory(base_dir='.')

import sys
sys.path.append('/home/vagrant/fmri-analysis-vm/analysis/utils')
from compute_fd_dvars import compute_fd,compute_dvars

%matplotlib inline

Load the data, clean it, and compute a mask using the nilearn NiftiMasker function


In [13]:
rsfmri_basedir='/home/vagrant/data/ds031/sub-01/ses-105/mcflirt'
rsfmri_files=glob.glob(os.path.join(rsfmri_basedir,'sub*.nii.gz'))

rsfmri_files.sort()

# load the first image and create the masker object
rsfmri_img=nibabel.load(rsfmri_files[0])
masker= nilearn.input_data.NiftiMasker(mask_strategy='epi')
masker.fit(rsfmri_img)
mask_img = masker.mask_img_

rsfmri={}  # nifti handle to cleaned image
fmri_masked=None
# load and clean each image
for f in rsfmri_files:
    rsfmri_img=nibabel.load(f)
    runnum=int(f.split('_')[3].split('-')[1])
    rsfmri[runnum]=nilearn.image.smooth_img(nilearn.image.clean_img(rsfmri_img),'fast')
    print('loaded run',runnum)
    motparfile=f.replace('nii.gz','par')
    mp=numpy.loadtxt(motparfile)
    if fmri_masked is None:
        fmri_masked=masker.transform(rsfmri[runnum])
        motpars=mp
    else:
        fmri_masked=numpy.vstack((fmri_masked,masker.transform(rsfmri[runnum])))
        motpars=numpy.vstack((motpars,mp))


loaded run 1
loaded run 2
loaded run 3
loaded run 4

Visualize the mask


In [8]:
# calculate mean image for the background
mean_func_img = '/home/vagrant/data/ds031/sub-01/ses-105/mcflirt/mcflirt_target.nii.gz'

plot_roi(mask_img, mean_func_img, display_mode='y', 
         cut_coords=4, title="Mask")


Out[8]:
<nilearn.plotting.displays.YSlicer at 0x7f4f174327f0>

Compute framewise displacement and plot it.


In [9]:
fd=compute_fd(motpars)
numpy.where(fd>1)
plt.figure(figsize=(12,4))
# remove first timepoint from each session
fd[240]=0
fd[480]=0
fd[720]=0
plt.plot(fd)
for c in [240,480,720]:
    plt.plot([c,c],
             [0,numpy.max(fd)*1.1],'k--')


Run FastICA and PCA on the masked data and compare the components.


In [14]:
ica=FastICA(n_components=5,max_iter=1000)
pca=PCA(n_components=5)
ica.fit(fmri_masked)
pca.fit(fmri_masked)
ica_components_img=masker.inverse_transform(ica.components_)
pca_components_img=masker.inverse_transform(pca.components_)


/home/vagrant/miniconda3/lib/python3.5/site-packages/sklearn/decomposition/fastica_.py:116: UserWarning: FastICA did not converge. Consider increasing tolerance or the maximum number of iterations.
  warnings.warn('FastICA did not converge. Consider increasing '

In [15]:
for i in range(5):
    img=index_img(ica_components_img, i)
    plot_stat_map(img, mean_func_img,
              display_mode='z', cut_coords=4, 
              title="ICA Component %d"%i)
        
for i in range(5):
    img=index_img(pca_components_img, i)
    plot_stat_map(img, mean_func_img,
              display_mode='z', cut_coords=4, 
              title="PCA Component %d"%i)


Run ICA on the masked data, using the CanICA tool from nilearn. Just arbitrarily set 10 components for now.


In [10]:
n_components=10

canica = CanICA(n_components=n_components, smoothing_fwhm=6.,
                memory="nilearn_cache", memory_level=2,
                threshold=3., verbose=10, random_state=0)
canica.fit(rsfmri_files)

# Retrieve the independent components in brain space
components_img = canica.masker_.inverse_transform(canica.components_)


[MultiNiftiMasker.fit] Loading data from [/home/vagrant/data/ds031/sub-01/ses-105/mcflirt/sub-01_ses-105_task-rest_run-001_bold_mcf.nii.gz, /home/vagrant/data/ds031/sub-01/ses-105/mcflirt/sub-01_ses-105_task-rest_run-002_bold_mcf.nii.gz, /ho
[MultiNiftiMasker.fit] Computing mask
[Memory]    0.0s, 0.0min: Loading compute_multi_epi_mask from nilearn_cache/joblib/nilearn/masking/compute_multi_epi_mask/ae6e74c9990abc60822c4b443c4e6454
______________________________compute_multi_epi_mask cache loaded - 0.0s, 0.0min
[MultiNiftiMasker.transform] Resampling mask
[Memory]    0.1s, 0.0min: Loading resample_img from nilearn_cache/joblib/nilearn/image/resampling/resample_img/c136ecb36b63b74dc023722ba869e75b
________________________________________resample_img cache loaded - 0.0s, 0.0min
[Memory]    0.1s, 0.0min: Loading filter_and_mask from nilearn_cache/joblib/nilearn/input_data/nifti_masker/filter_and_mask/12b980b302db1fa1774b2971dd047c61
_____________________________________filter_and_mask cache loaded - 0.2s, 0.0min
[Memory]    1.9s, 0.0min: Loading filter_and_mask from nilearn_cache/joblib/nilearn/input_data/nifti_masker/filter_and_mask/de0c491ae17b2161d90e2fd5b605a1ab
_____________________________________filter_and_mask cache loaded - 0.1s, 0.0min
[Memory]    3.4s, 0.1min: Loading filter_and_mask from nilearn_cache/joblib/nilearn/input_data/nifti_masker/filter_and_mask/c75353d6d277c46a34190cd3459515f6
_____________________________________filter_and_mask cache loaded - 0.1s, 0.0min
[Memory]    4.0s, 0.1min: Loading filter_and_mask from nilearn_cache/joblib/nilearn/input_data/nifti_masker/filter_and_mask/d8489c08570bc75d9539397d5ed9f215
_____________________________________filter_and_mask cache loaded - 0.1s, 0.0min
[Memory]    0.0s, 0.0min: Loading randomized_svd from nilearn_cache/joblib/sklearn/utils/extmath/randomized_svd/c0f2b45c0252c2ca01ee545c1f0113e8
______________________________________randomized_svd cache loaded - 0.0s, 0.0min
[Memory]    0.0s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/e40ffdbf57c0c212b2d00f2a6aa90c6f
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.1s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/cb5cb4e4bc86c0cb5484aec0a92756f8
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.1s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/d07b69d5113edf3bed0e702175ca051c
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.1s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/1125a1c7d46d62def5d0bed86cb64219
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.1s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/cbc774b27dce7f7e50adac2ffb6d88f9
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.1s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/85a96c8750e7e7e9e93aa547a5e12717
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.2s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/8a0920b01e005fd5b10f79980da13f6b
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.2s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/aef2c025e445a22c860be4385ea23c67
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.2s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/38ba51670568c7f9aac8d9ebf757de4b
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    0.2s, 0.0min: Loading fastica from nilearn_cache/joblib/sklearn/decomposition/fastica_/fastica/0752c449c59f761e853a8e69fe8992a9
[Parallel(n_jobs=1)]: Done   1 out of   1 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   2 out of   2 | elapsed:    0.0s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   3 out of   3 | elapsed:    0.1s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   4 out of   4 | elapsed:    0.1s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   5 out of   5 | elapsed:    0.1s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   6 out of   6 | elapsed:    0.1s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   7 out of   7 | elapsed:    0.1s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   8 out of   8 | elapsed:    0.2s remaining:    0.0s
[Parallel(n_jobs=1)]: Done   9 out of   9 | elapsed:    0.2s remaining:    0.0s
[Parallel(n_jobs=1)]: Done  10 out of  10 | elapsed:    0.2s finished
_____________________________________________fastica cache loaded - 0.0s, 0.0min
[Memory]    5.0s, 0.1min: Loading unmask from nilearn_cache/joblib/nilearn/masking/unmask/a096eb942ca39afe26c2bcfd4ff8fde2
______________________________________________unmask cache loaded - 0.1s, 0.0min

In [11]:
# Visualize results
for i in range(n_components):
    img=index_img(components_img, i)
    img_masked=masker.transform(img)
    ts=fmri_masked.dot(img_masked.T)
    plot_stat_map(img, mean_func_img,
              display_mode='z', cut_coords=4, threshold=0.01,
              title="Component %d"%i)
    plt.figure(figsize=(8,3))
    plt.plot(ts)
    for c in [240,480,720]:
        plt.plot([c,c],
                 [numpy.min(ts)*1.1,
                  numpy.max(ts)*1.1],
                'k--')



In [ ]: