Commit 26fe0bef authored by Sean Fitzgibbon's avatar Sean Fitzgibbon
Browse files

added notebook to fecth data for MIGP practical

parent e471dc28
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Fetch Data\n",
"\n",
"This notebook will download an open fMRI dataset (~50MB) for use in the MIGP demo. It also regresses confounds from the data and performs spatial smoothing with 10mm FWHM.\n",
"\n",
"This data is a derivative from the COBRE sample found in the International Neuroimaging Data-sharing Initiative (http://fcon_1000.projects.nitrc.org/indi/retro/cobre.html), originally released under Creative Commons - Attribution Non-Commercial.\n",
"\n",
"It comprises 10 preprocessed resting-state fMRI selected from 72 patients diagnosed with schizophrenia and 74 healthy controls (6mm isotropic, TR=2s, 150 volumes).\n",
"\n",
"* [Download the data](#download-the-data)\n",
"* [Clean the data](#clean-the-data)\n",
"* [Run `melodic`](#run-melodic)\n",
"\n",
"Firstly we will import the necessary packages for this notebook: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nilearn import datasets\n",
"from nilearn import image\n",
"from nilearn import plotting\n",
"import nibabel as nb\n",
"import numpy as np\n",
"import os.path as op\n",
"import os\n",
"import glob\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This function will be used to plot ICs later:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def map_plot(d):\n",
"\n",
" N = d.shape[-1]\n",
"\n",
" fig, ax = plt.subplots(int(np.ceil((N/2))),2, figsize=(12, N))\n",
"\n",
" for img, ax0 in zip(image.iter_img(d), ax.ravel()):\n",
" coord = plotting.find_xyz_cut_coords(img, activation_threshold=2.3)\n",
" plotting.plot_stat_map(img, cut_coords=coord, vmax=10, axes=ax0)\n",
" \n",
" return fig"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"download-the-data\"></a>\n",
"## Download the data\n",
"\n",
"We use a method from [`nilearn`](https://nilearn.github.io/index.html) called `fetch_cobre` to download the fMRI data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a directory in the users home directory to store the downloaded data\n",
"data_dir = op.expanduser('~/nilearn_data')\n",
"\n",
"if not op.exists(data_dir):\n",
" os.makedirs(data_dir)\n",
" \n",
"# Download the data (if not already downloaded)\n",
"d = datasets.fetch_cobre(data_dir=data_dir) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"clean-the-data\"></a>\n",
"## Clean the data\n",
"\n",
"We use methods from [`nilearn`](https://nilearn.github.io/index.html) to regress confounds from the data (```clean_img```) and to spatially smooth the data with a gaussian filter of 10mm FWHM (```smooth_img```):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a list of filenames for cleaned and smoothed data\n",
"clean = [f.replace('.nii.gz', '_clean.nii.gz') for f in d.func]\n",
"smooth = [f.replace('.nii.gz', '_clean_smooth.nii.gz') for f in d.func]\n",
"\n",
"# loop through each subject, regress confounds and smooth\n",
"for img, cleaned, smoothed, conf in zip(d.func, clean, smooth, d.confounds):\n",
" image.clean_img(img, confounds=conf).to_filename(cleaned)\n",
" image.smooth_img(img, 10).to_filename(smoothed)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To run ```melodic``` we will need a brain mask in MNI152 space at the same resolution as the fMRI. Here we use [`nilearn`](https://nilearn.github.io/index.html) methods to load the MNI152 mask (```load_mni152_brain_mask```), resample to the resolution of the fMRI (```resample_to_img```), and binarize (```math_img```):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# load a single fMRI dataset (func0)\n",
"func0 = nb.load(d.func[0].replace('.nii.gz', '_clean_smooth.nii.gz'))\n",
"\n",
"# load MNI153 brainmask, resample to func0 resolution, binarize, and save to nifti\n",
"mask = datasets.load_mni152_brain_mask()\n",
"mask = image.resample_to_img(mask, func0)\n",
"mask = image.math_img('img > 0.5', img=mask)\n",
"mask.to_filename(op.join(data_dir, 'brain_mask.nii.gz'))\n",
"\n",
"# plot brainmask to make sure it looks OK\n",
"disp = plotting.plot_anat(image.index_img(func0, 0))\n",
"disp.add_contours(mask, threshold=0.5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"run-melodic\"></a>\n",
"### Run ```melodic```\n",
"\n",
"Generate a command line string and run group ```melodic``` on the smoothed fMRI with a dimension of 10 components:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# generate melodic command line string\n",
"melodic_cmd = f\"melodic -i {','.join(smooth)} --mask={op.join(data_dir, 'brain_mask.nii.gz')} -d 10 -v --Oall -o cobre.gica \"\n",
"print(melodic_cmd)\n",
"\n",
"# run melodic\n",
"! {melodic_cmd}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can load and plot the group ICs generated by ```melodic```.\n",
"\n",
"Hopefully you can see some familiar looking RSN spatial patterns:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ics = nb.load('cobre.gica/melodic_IC.nii.gz')\n",
"fig = map_plot(ics)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
%% Cell type:markdown id: tags:
# Fetch Data
This notebook will download an open fMRI dataset (~50MB) for use in the MIGP demo. It also regresses confounds from the data and performs spatial smoothing with 10mm FWHM.
This data is a derivative from the COBRE sample found in the International Neuroimaging Data-sharing Initiative (http://fcon_1000.projects.nitrc.org/indi/retro/cobre.html), originally released under Creative Commons - Attribution Non-Commercial.
It comprises 10 preprocessed resting-state fMRI selected from 72 patients diagnosed with schizophrenia and 74 healthy controls (6mm isotropic, TR=2s, 150 volumes).
* [Download the data](#download-the-data)
* [Clean the data](#clean-the-data)
* [Run `melodic`](#run-melodic)
Firstly we will import the necessary packages for this notebook:
%% Cell type:code id: tags:
``` python
from nilearn import datasets
from nilearn import image
from nilearn import plotting
import nibabel as nb
import numpy as np
import os.path as op
import os
import glob
import matplotlib.pyplot as plt
```
%% Cell type:markdown id: tags:
This function will be used to plot ICs later:
%% Cell type:code id: tags:
``` python
def map_plot(d):
N = d.shape[-1]
fig, ax = plt.subplots(int(np.ceil((N/2))),2, figsize=(12, N))
for img, ax0 in zip(image.iter_img(d), ax.ravel()):
coord = plotting.find_xyz_cut_coords(img, activation_threshold=2.3)
plotting.plot_stat_map(img, cut_coords=coord, vmax=10, axes=ax0)
return fig
```
%% Cell type:markdown id: tags:
<a class="anchor" id="download-the-data"></a>
## Download the data
We use a method from [`nilearn`](https://nilearn.github.io/index.html) called `fetch_cobre` to download the fMRI data:
%% Cell type:code id: tags:
``` python
# Create a directory in the users home directory to store the downloaded data
data_dir = op.expanduser('~/nilearn_data')
if not op.exists(data_dir):
os.makedirs(data_dir)
# Download the data (if not already downloaded)
d = datasets.fetch_cobre(data_dir=data_dir)
```
%% Cell type:markdown id: tags:
<a class="anchor" id="clean-the-data"></a>
## Clean the data
We use methods from [`nilearn`](https://nilearn.github.io/index.html) to regress confounds from the data (```clean_img```) and to spatially smooth the data with a gaussian filter of 10mm FWHM (```smooth_img```):
%% Cell type:code id: tags:
``` python
# Create a list of filenames for cleaned and smoothed data
clean = [f.replace('.nii.gz', '_clean.nii.gz') for f in d.func]
smooth = [f.replace('.nii.gz', '_clean_smooth.nii.gz') for f in d.func]
# loop through each subject, regress confounds and smooth
for img, cleaned, smoothed, conf in zip(d.func, clean, smooth, d.confounds):
image.clean_img(img, confounds=conf).to_filename(cleaned)
image.smooth_img(img, 10).to_filename(smoothed)
```
%% Cell type:markdown id: tags:
To run ```melodic``` we will need a brain mask in MNI152 space at the same resolution as the fMRI. Here we use [`nilearn`](https://nilearn.github.io/index.html) methods to load the MNI152 mask (```load_mni152_brain_mask```), resample to the resolution of the fMRI (```resample_to_img```), and binarize (```math_img```):
%% Cell type:code id: tags:
``` python
# load a single fMRI dataset (func0)
func0 = nb.load(d.func[0].replace('.nii.gz', '_clean_smooth.nii.gz'))
# load MNI153 brainmask, resample to func0 resolution, binarize, and save to nifti
mask = datasets.load_mni152_brain_mask()
mask = image.resample_to_img(mask, func0)
mask = image.math_img('img > 0.5', img=mask)
mask.to_filename(op.join(data_dir, 'brain_mask.nii.gz'))
# plot brainmask to make sure it looks OK
disp = plotting.plot_anat(image.index_img(func0, 0))
disp.add_contours(mask, threshold=0.5)
```
%% Cell type:markdown id: tags:
<a class="anchor" id="run-melodic"></a>
### Run ```melodic```
Generate a command line string and run group ```melodic``` on the smoothed fMRI with a dimension of 10 components:
%% Cell type:code id: tags:
``` python
# generate melodic command line string
melodic_cmd = f"melodic -i {','.join(smooth)} --mask={op.join(data_dir, 'brain_mask.nii.gz')} -d 10 -v --Oall -o cobre.gica "
print(melodic_cmd)
# run melodic
! {melodic_cmd}
```
%% Cell type:markdown id: tags:
Now we can load and plot the group ICs generated by ```melodic```.
Hopefully you can see some familiar looking RSN spatial patterns:
%% Cell type:code id: tags:
``` python
ics = nb.load('cobre.gica/melodic_IC.nii.gz')
fig = map_plot(ics)
```
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment