Commit fa01bf5f authored by Sean Fitzgibbon's avatar Sean Fitzgibbon
Browse files

Merge branch 'sean-migp' into 'master'

Sean migp

See merge request fsl/pytreat-practicals-2020!22
parents 4d5dfc9a a09d7348
% MIGP - MELODIC's Incremental Group-PCA
%% MIGP - MELODIC's Incremental Group-PCA
% Steve Smith, FMRIB, 2012-2013
% not yet finally tweaked/evaluated, or published - please do not pass on.
% adapted by Sean Fitz, 2020
%%%%%%%%%%%%%%%%%%%%%%%%%% USER OPTIONS
%% User Options (equivalent to melodic defaults)
INlist=dir('data/cobre/fmri_*.nii.gz'); % list of input 4D NIFTI standard space datasets
INmask='data/brain_mask.nii.gz'; % 3D NIFTI mask image
GO='matMIGP'; % output filename
dPCAint=550; % internal number of components - typically 2-4 times number of timepoints in each run (if you have enough RAM for that)
dPCAout=100; % number of eigenvectors to output - should be less than dPCAint and more than the final ICA dimensionality
INlist=dir('~/nilearn_data/cobre/fmri_*_smooth.nii.gz'); % list of input 4D NIFTI standard space datasets
INmask='~/nilearn_data/brain_mask.nii.gz'; % 3D NIFTI mask image
GO='matMIGP'; % output filename
dPCAint=299; % internal number of components - typically 2-4 times number of timepoints in each run (if you have enough RAM for that)
dPCAout=299; % number of eigenvectors to output - should be less than dPCAint and more than the final ICA dimensionality
sep_vn=false; % switch on separate variance nomalisation for each input dataset
%%%%%%%%%%%%%%%%%%%%%%%%%% END OF USER OPTIONS
%% Run MIGP
Nsub=length(INlist); [~,r]=sort(rand(Nsub,1)); % will process subjects in random order
mask=read_avw(INmask);
......@@ -21,32 +20,38 @@ masksize=size(mask);
mask=reshape(mask,prod(masksize),1);
demean = @(x) x - repmat(mean(x,1),[size(x,1), 1, 1]);
ss_svds = @(x,n) svds(x, n);
for i = 1:Nsub
% read data
filename=[INlist(r(i)).folder, '/', INlist(r(i)).name];
fprintf('Reading data file %s\n', filename);
grot=double(read_avw(filename));
grot=reshape(grot,prod(masksize),size(grot,4));
% demean
fprintf('\tRemoving mean image\n');
grot=demean(grot(mask~=0,:)');
% var-norm
[uu,ss,vv]=ss_svds(grot,30);
vv(abs(vv)<2.3*std(vv(:)))=0;
stddevs=max(std(grot-uu*ss*vv'),0.001);
grot=grot./repmat(stddevs,size(grot,1),1);
% var-norm separately for each subject
if sep_vn==true
fprintf('\tNormalising by voxel-wise variance\r');
[uu,ss,vv]=svds(grot,30);
vv(abs(vv)<2.3*std(vv(:)))=0;
stddevs=max(std(grot-uu*ss*vv'),0.001);
grot=grot./repmat(stddevs,size(grot,1),1);
end
if (i==1)
W=demean(grot); clear grot;
else
% concat
W=[W; demean(grot)]; clear grot;
% reduce W to dPCAint eigenvectors
if size(W,1)-10 > dPCAint
fprintf('\tReducing data matrix to a %i dimensional subspace\n', dPCAint);
[uu,dd]=eigs(W*W',dPCAint);
W=uu'*W;
clear uu;
......@@ -56,8 +61,11 @@ for i = 1:Nsub
end
%% Reshape and save
grot=zeros(prod(masksize),dPCAout);
grot(mask~=0,:)=W(1:dPCAout,:)'; grot=reshape(grot,[masksize ,dPCAout]);
fprintf('Save to %s.nii.gz\n', GO)
save_avw(grot,GO,'f',[1 1 1 1]);
system(sprintf('fslcpgeom %s %s -d',filename,GO));
{
"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",
"* [Plot group ICs](#plot-group-ics)\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": [
"<a class=\"anchor\" id=\"download-the-data\"></a>\n",
"## Download the data\n",
"\n",
"Create a directory in the users home directory to store the downloaded data:\n",
"\n",
"> **NOTE:** `expanduser` will expand the `~` to the be users home directory:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data_dir = op.expanduser('~/nilearn_data')\n",
"\n",
"if not op.exists(data_dir):\n",
" os.makedirs(data_dir)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Download the data (if not already downloaded):\n",
"\n",
"> **Note:** 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": [
"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",
"Regress confounds from the data and to spatially smooth the data with a gaussian filter of 10mm FWHM.\n",
"\n",
"> **Note:**\n",
"> 1. We use `clean_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to regress confounds from the data\n",
"> 2. We use `smooth_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to spatially smooth the data\n",
"> 3. `zip` takes iterables and aggregates them in a tuple. Here it is used to iterate through four lists simultaneously\n",
"> 4. We use list comprehension to loop through all the filenames and append suffixes\n"
]
},
{
"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",
" print(f'{img}: regress confounds: ', end='')\n",
" image.clean_img(img, confounds=conf).to_filename(cleaned)\n",
" print(f'smooth.')\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. \n",
"\n",
"> **Note:**\n",
"> 1. We use `load_mni152_brain_mask` from the [`nilearn`](https://nilearn.github.io/index.html) package to load the MNI152 mask\n",
"> 2. We use `resample_to_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to resample the mask to the resolution of the fMRI \n",
"> 3. We use `math_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to binarize the resample mask\n",
"> 4. The mask is plotted using `plot_anat` from the [`nilearn`](https://nilearn.github.io/index.html) package"
]
},
{
"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:\n",
"\n",
"> **Note**: \n",
"> 1. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting\n",
"> 2. `op.join` will join path strings using the platform-specific directory separator\n",
"> 3. `','.join(smooth)` will create a comma seprated string of all the items in the list `smooth`"
]
},
{
"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 -o cobre.gica \"\n",
"print(melodic_cmd)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> **Note:** \n",
"> 1. Here we use the `!` operator to execute the command in the shell\n",
"> 2. The `{}` will expand the contained python variable in the shell"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# run melodic\n",
"! {melodic_cmd}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"plot-group-ics\"></a>\n",
"### Plot group ICs\n",
"\n",
"Now we can load and plot the group ICs generated by ```melodic```.\n",
"\n",
"This function will be used to plot ICs:\n",
"\n",
"> **NOTE:**\n",
"> 1. Here we use `plot_stat_map` from the `nilearn` package to plot the orthographic images\n",
"> 2. `subplots` from `matplotlib.pyplot` creates a figure and multiple subplots\n",
"> 3. `find_xyz_cut_coords` from the `nilearn` package will find the image coordinates of the center of the largest activation connected component\n",
"> 4. `zip` takes iterables and aggregates them in a tuple. Here it is used to iterate through two lists simultaneously\n",
"> 5. `iter_img` from the `nilearn` package creates an iterator from an image that steps through each volume/time-point of the image"
]
},
{
"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=3.5)\n",
" plotting.plot_stat_map(img, cut_coords=coord, vmax=10, axes=ax0)\n",
" \n",
" return fig"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Hopefully you can see some familiar looking RSN spatial patterns:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Load ICs\n",
"ics = nb.load('cobre.gica/melodic_IC.nii.gz')\n",
"\n",
"# plot\n",
"fig = map_plot(ics)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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)
* [Plot group ICs](#plot-group-ics)
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:
<a class="anchor" id="download-the-data"></a>
## Download the data
Create a directory in the users home directory to store the downloaded data:
> **NOTE:** `expanduser` will expand the `~` to the be users home directory:
%% Cell type:code id: tags:
``` python
data_dir = op.expanduser('~/nilearn_data')
if not op.exists(data_dir):
os.makedirs(data_dir)
```
%% Cell type:markdown id: tags:
Download the data (if not already downloaded):
> **Note:** 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
d = datasets.fetch_cobre(data_dir=data_dir)
```
%% Cell type:markdown id: tags:
<a class="anchor" id="clean-the-data"></a>
## Clean the data
Regress confounds from the data and to spatially smooth the data with a gaussian filter of 10mm FWHM.
> **Note:**
> 1. We use `clean_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to regress confounds from the data
> 2. We use `smooth_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to spatially smooth the data
> 3. `zip` takes iterables and aggregates them in a tuple. Here it is used to iterate through four lists simultaneously
> 4. We use list comprehension to loop through all the filenames and append suffixes
%% 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):
print(f'{img}: regress confounds: ', end='')
image.clean_img(img, confounds=conf).to_filename(cleaned)
print(f'smooth.')
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.
> **Note:**
> 1. We use `load_mni152_brain_mask` from the [`nilearn`](https://nilearn.github.io/index.html) package to load the MNI152 mask
> 2. We use `resample_to_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to resample the mask to the resolution of the fMRI
> 3. We use `math_img` from the [`nilearn`](https://nilearn.github.io/index.html) package to binarize the resample mask
> 4. The mask is plotted using `plot_anat` from the [`nilearn`](https://nilearn.github.io/index.html) package
%% 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:
> **Note**:
> 1. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting
> 2. `op.join` will join path strings using the platform-specific directory separator
> 3. `','.join(smooth)` will create a comma seprated string of all the items in the list `smooth`
%% 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 -o cobre.gica "
print(melodic_cmd)
```
%% Cell type:markdown id: tags:
> **Note:**
> 1. Here we use the `!` operator to execute the command in the shell
> 2. The `{}` will expand the contained python variable in the shell
%% Cell type:code id: tags:
``` python
# run melodic
! {melodic_cmd}
```
%% Cell type:markdown id: tags:
<a class="anchor" id="plot-group-ics"></a>
### Plot group ICs
Now we can load and plot the group ICs generated by ```melodic```.
This function will be used to plot ICs:
> **NOTE:**
> 1. Here we use `plot_stat_map` from the `nilearn` package to plot the orthographic images
> 2. `subplots` from `matplotlib.pyplot` creates a figure and multiple subplots
> 3. `find_xyz_cut_coords` from the `nilearn` package will find the image coordinates of the center of the largest activation connected component
> 4. `zip` takes iterables and aggregates them in a tuple. Here it is used to iterate through two lists simultaneously
> 5. `iter_img` from the `nilearn` package creates an iterator from an image that steps through each volume/time-point of the image
%% 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=3.5)
plotting.plot_stat_map(img, cut_coords=coord, vmax=10, axes=ax0)
return fig
```
%% Cell type:markdown id: tags:
Hopefully you can see some familiar looking RSN spatial patterns:
%% Cell type:code id: tags:
``` python
# Load ICs
ics = nb.load('cobre.gica/melodic_IC.nii.gz')
# plot
fig = map_plot(ics)
```
%% Cell type:code id: tags:
``` python
```
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Matlab MIGP\n",
"\n",
"This notebook will load the dimension reduced data from Matlab MIGP, run group ICA, and then plot the group ICs.\n",
"\n",
"* [Run `melodic`](#run-matlab-melodic)\n",
"* [Plot group ICs](#plot-matlab-group-ics)\n",
"\n",
"Firstly we will import the necessary packages for this notebook: "
]
},
{
"cell_type": "code",
"execution_count": null,
......@@ -10,7 +24,60 @@
"from nilearn import image\n",
"import nibabel as nb\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np"
"import numpy as np\n",
"import os.path as op"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It will be necessary to know the location where the data was stored so that we can load the brainmask:\n",
"\n",
"> **Note**: `expanduser` will expand the `~` to the be users home directory"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data_dir = op.expanduser('~/nilearn_data')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a class=\"anchor\" id=\"run-matlab-melodic\"></a>\n",
"### Run ```melodic```\n",
"\n",
"Generate a command line string and run group ```melodic``` on the Matlab MIGP dimension reduced data with a dimension of 10 components. We disable MIGP because it was already run separately in Matlab.\n",
"\n",
"> **Note**: \n",
"> 1. Here we use python [f-strings](https://www.python.org/dev/peps/pep-0498/), formally known as literal string interpolation, which allow for easy formatting\n",
"> 2. `op.join` will join path strings using the platform-specific directory separator"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# generate melodic command line string\n",
"melodic_cmd = f\"melodic -i matMIGP.nii.gz --mask={op.join(data_dir, 'brain_mask.nii.gz')} -d 10 -v --nobet --disableMigp -o matmigp.gica\"\n",
"print(melodic_cmd)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"> **Note:** \n",
"> 1. Here we use the `!` operator to execute the command in the shell\n",
"> 2. The `{}` will expand the contained python variable in the shell"
]
},
{
......@@ -19,16 +86,27 @@
"metadata": {},
"outputs": [],
"source": [
"%%bash\n",
"# run melodic\n",
"! {melodic_cmd}"
]
},
{
"cell_type": "markdown",