Commit 798511ea authored by Sean Fitzgibbon's avatar Sean Fitzgibbon Committed by Paul McCarthy
Browse files

First pass at nilearn visualisation practical

parent 4edc4f9c
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# `nilearn`\n",
"\n",
"\n",
"\n",
"`nilearn` is python package that provides **statistical** and **machine learning** tools for working with neurimaging data.\n",
"\n",
"According to https://nilearn.github.io/: \n",
">\n",
"> Nilearn enables approachable and versatile analyses of brain volumes. It provides **statistical** and **machine-learning** tools, with instructive documentation & open community.\n",
">\n",
"> It supports general linear model (GLM) based analysis and leverages the scikit-learn Python toolbox for multivariate statistics with applications such as predictive modelling, classification, decoding, or connectivity analysis.\n",
"\n",
"However, `nilearn` also provides a very convenient set of visualisation routines for neuorimaing data. This notebook will focus on these visualisation tools.\n",
"\n",
"`nilearn` has very good documentation, and the examples below borrow heavily from the visulisation documentation: https://nilearn.github.io/plotting/index.html\n",
"\n",
"## This notebook\n",
"\n",
"1. Plotting an anatomical image\n",
"2. Plotting a statistical map\n",
"4. 2D maximum intensity projection\n",
"5. Surfaces\n",
"\n",
"Firstly we will import the necessary packages for this notebook: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"from nilearn import plotting, datasets, surface\n",
"import matplotlib as mpl\n",
"import matplotlib.pyplot as plt\n",
"\n",
"# get path to FSL installation for the FSLDIR environment variable\n",
"FSLDIR = os.environ['FSLDIR']\n",
"\n",
"## figure styling\n",
"mpl.rcParams['figure.dpi'] = 150\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plotting an anatomical image\n",
"\n",
"In this section we will use `nilearn` to plot an anatomical volume. For these examples we will use the 1mm MNI152 T1w that is shipped with `FSL`. In these examples you will see differnet plotting layouts, as well as different styling options.\n",
"\n",
"First we will use the `plot_anat` function (with default values) to plot the MNI152 T1w in an **ortho** view.\n",
"\n",
"> **NOTE:**\n",
"> 1. Here we use [`plot_anat`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_anat.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images\n",
"> 2. 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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_anat(\n",
" f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we adjust the brightness of the image using the `dim` argument, and add a title to the plot with the `title` argument."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_anat(\n",
" f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', \n",
" dim=-0.5, \n",
" title='MNI T1 1mm'\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are going to use the `display_mode` argument to change to a **tiled** ortho view where the coronal and axial views are in a column, and the coronal and sagittal views are in a row."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_anat(\n",
" f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', \n",
" dim=-0.5, \n",
" title='MNI T1 1mm', \n",
" display_mode='tiled'\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are going to combine the `display_mode` and `cut_coords` arguments to create a row of 10 axial slices. \n",
"\n",
"Options for `display_mode` include:\n",
"- `'x'` - sagittal\n",
"- `'y'` - coronal\n",
"- `'z'` - axial\n",
"- `'ortho'` - three cuts are performed in orthogonal directions\n",
"- `'tiled'` - three cuts are performed and arranged in a 2x2 grid\n",
"\n",
"In this instance, we five `cut_coords` an scalar integer that indicates the number of slices to show in the axial view. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_anat(\n",
" f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', \n",
" dim=-0.5, \n",
" title='MNI T1 1mm', \n",
" display_mode='z', \n",
" cut_coords=10\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this example a `display` object is returned by `plot_anat`. We can use this object to update/amend the plot. Here we add an overlay of the *HarvardOxford* atlas that ships with `FSL` to the image. \n",
"\n",
"We also use the `display` object to save the plot as a `*.png` image."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# plot MNI152 T1w and return display object\n",
"\n",
"display = plotting.plot_anat(\n",
" f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz', \n",
" dim=-0.5, \n",
" title='MNI T1 1mm'\n",
")\n",
"\n",
"# overlay the HarvardOxford atlas\n",
"\n",
"display.add_contours(\n",
" f'{FSLDIR}/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr50-1mm.nii.gz', \n",
" filled=True\n",
")\n",
"\n",
"# save plot to file\n",
"display.savefig('myplot.png')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plotting a statistical map\n",
"\n",
"The examples in this section demonstrate how to plot an statistical map as an overlay on an anatomical image. Both images must be in the same space.\n",
"\n",
"First we will download a motor task statistical map from NeuroVault.\n",
"\n",
"> **Note:** We use a method from [`nilearn`](https://nilearn.github.io/index.html) called [`fetch_neurovault_motor_task`](https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_neurovault_motor_task.html) to download the statistical map."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"motor_images = datasets.fetch_neurovault_motor_task()\n",
"stat_img = motor_images.images[0]\n",
"\n",
"print(stat_img)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we can plot the statistical map as an overlay on the MNI152 T1w. We theshold the statistical map using the `threshold` argument.\n",
"\n",
"> **NOTE:** Here we use [`plot_stat_map`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_stat_map.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_stat_map(\n",
" stat_img,\n",
" threshold=3,\n",
" bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Like with the `plot_anat` examples earlier, we can style the plot and change the layout and views."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_stat_map(\n",
" stat_img,\n",
" threshold=3,\n",
" bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',\n",
" display_mode='z', \n",
" cut_coords=10,\n",
" title='motor-task',\n",
" dim=-0.5,\n",
" vmax=10\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this next example we first find the coordinate of the centre of the largest connected component in the statistical map, then we plot an ortho view that is centred on this coordinate. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# find the coordinate of the centre of the largest connected component in the statistical map\n",
"\n",
"coord = plotting.find_xyz_cut_coords(stat_img)\n",
"print(f'Center of the largest activation connected component = {coord}')\n",
"\n",
"# plot an ortho view that is centred on this coordinate\n",
"\n",
"plotting.plot_stat_map(\n",
" stat_img,\n",
" threshold=3,\n",
" bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',\n",
" display_mode='ortho', \n",
" cut_coords=coord,\n",
" title='motor-task',\n",
" dim=-0.5,\n",
" vmax=10\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`nilearn` has some support for **interactive** viewing of volumetic images with the `view_img` function. Try clicking on the plot and moving the cursor around!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"view = plotting.view_img(stat_img, threshold=3)\n",
"view # view interactive plot inline"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"view = plotting.view_img(stat_img, threshold=3)\n",
"view.open_in_browser() # open interactive plot in new web browser"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2D maximum intensity projection\n",
"\n",
"> Maximum intensity projection (MIP) is a method for 3D data that projects in the visualization plane the voxels with maximum intensity that fall in the way of parallel rays traced from the viewpoint to the plane of projection. https://en.wikipedia.org/wiki/Maximum_intensity_projection\n",
"\n",
"`nilearn` can plot a maximum intensity projection overlayed on a brain schematic referred to as the \"glass brain\". In this example, the MIP of the motor task statistical map used in the previous examples is plotted on the glass brain.\n",
"\n",
"> **NOTE:** Here we use [`plot_glass_brain`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_glass_brain.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the maximum intensity projection."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_glass_brain(\n",
" stat_img, \n",
" title='2D max-intensity projection',\n",
" threshold=3,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Surfaces\n",
"\n",
"`nilearn` has baked in functionality to project a volumetric image onto the surface and visualise it. \n",
"\n",
"Here we visualise the same volumetric motor task statistical map, from earlier examples, on the inflated surface.\n",
"\n",
"> **NOTE:** Here we use [`plot_img_on_surf`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_img_on_surf.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the volumetric statistical map on the surface."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plotting.plot_img_on_surf(\n",
" stat_img, \n",
" inflate=True, \n",
" threshold=0.5, \n",
" vmax=6\n",
");"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`nilearn` also has some support for **interactive** viewing of volumetic images on the surface with the `view_img_on_surf` function. Try clicking on the plot and moving the cursor around!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"view = plotting.view_img_on_surf(\n",
" stat_img, \n",
" threshold=0.5, \n",
" surf_mesh='fsaverage', \n",
" vmax=6\n",
") \n",
"\n",
"view # view interactive plot inline "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"view = plotting.view_img_on_surf(\n",
" stat_img, \n",
" threshold=0.5, \n",
" surf_mesh='fsaverage', \n",
" vmax=6\n",
") \n",
"\n",
"view.open_in_browser() # view interactive plot inline "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That's all folks...."
]
}
],
"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.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
%% Cell type:markdown id: tags:
# `nilearn`
`nilearn` is python package that provides **statistical** and **machine learning** tools for working with neurimaging data.
According to https://nilearn.github.io/:
>
> Nilearn enables approachable and versatile analyses of brain volumes. It provides **statistical** and **machine-learning** tools, with instructive documentation & open community.
>
> It supports general linear model (GLM) based analysis and leverages the scikit-learn Python toolbox for multivariate statistics with applications such as predictive modelling, classification, decoding, or connectivity analysis.
However, `nilearn` also provides a very convenient set of visualisation routines for neuorimaing data. This notebook will focus on these visualisation tools.
`nilearn` has very good documentation, and the examples below borrow heavily from the visulisation documentation: https://nilearn.github.io/plotting/index.html
## This notebook
1. Plotting an anatomical image
2. Plotting a statistical map
4. 2D maximum intensity projection
5. Surfaces
Firstly we will import the necessary packages for this notebook:
%% Cell type:code id: tags:
``` python
import os
from nilearn import plotting, datasets, surface
import matplotlib as mpl
import matplotlib.pyplot as plt
# get path to FSL installation for the FSLDIR environment variable
FSLDIR = os.environ['FSLDIR']
## figure styling
mpl.rcParams['figure.dpi'] = 150
```
%% Cell type:markdown id: tags:
## Plotting an anatomical image
In this section we will use `nilearn` to plot an anatomical volume. For these examples we will use the 1mm MNI152 T1w that is shipped with `FSL`. In these examples you will see differnet plotting layouts, as well as different styling options.
First we will use the `plot_anat` function (with default values) to plot the MNI152 T1w in an **ortho** view.
> **NOTE:**
> 1. Here we use [`plot_anat`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_anat.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images
> 2. 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
%% Cell type:code id: tags:
``` python
plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
)
```
%% Cell type:markdown id: tags:
Here we adjust the brightness of the image using the `dim` argument, and add a title to the plot with the `title` argument.
%% Cell type:code id: tags:
``` python
plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5,
title='MNI T1 1mm'
)
```
%% Cell type:markdown id: tags:
Now we are going to use the `display_mode` argument to change to a **tiled** ortho view where the coronal and axial views are in a column, and the coronal and sagittal views are in a row.
%% Cell type:code id: tags:
``` python
plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5,
title='MNI T1 1mm',
display_mode='tiled'
)
```
%% Cell type:markdown id: tags:
Now we are going to combine the `display_mode` and `cut_coords` arguments to create a row of 10 axial slices.
Options for `display_mode` include:
- `'x'` - sagittal
- `'y'` - coronal
- `'z'` - axial
- `'ortho'` - three cuts are performed in orthogonal directions
- `'tiled'` - three cuts are performed and arranged in a 2x2 grid
In this instance, we five `cut_coords` an scalar integer that indicates the number of slices to show in the axial view.
%% Cell type:code id: tags:
``` python
plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5,
title='MNI T1 1mm',
display_mode='z',
cut_coords=10
)
```
%% Cell type:markdown id: tags:
In this example a `display` object is returned by `plot_anat`. We can use this object to update/amend the plot. Here we add an overlay of the *HarvardOxford* atlas that ships with `FSL` to the image.
We also use the `display` object to save the plot as a `*.png` image.
%% Cell type:code id: tags:
``` python
# plot MNI152 T1w and return display object
display = plotting.plot_anat(
f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
dim=-0.5,
title='MNI T1 1mm'
)
# overlay the HarvardOxford atlas
display.add_contours(
f'{FSLDIR}/data/atlases/HarvardOxford/HarvardOxford-cort-maxprob-thr50-1mm.nii.gz',
filled=True
)
# save plot to file
display.savefig('myplot.png')
```
%% Cell type:markdown id: tags:
## Plotting a statistical map
The examples in this section demonstrate how to plot an statistical map as an overlay on an anatomical image. Both images must be in the same space.
First we will download a motor task statistical map from NeuroVault.
> **Note:** We use a method from [`nilearn`](https://nilearn.github.io/index.html) called [`fetch_neurovault_motor_task`](https://nilearn.github.io/modules/generated/nilearn.datasets.fetch_neurovault_motor_task.html) to download the statistical map.
%% Cell type:code id: tags:
``` python
motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0]
print(stat_img)
```
%% Cell type:markdown id: tags:
Now we can plot the statistical map as an overlay on the MNI152 T1w. We theshold the statistical map using the `threshold` argument.
> **NOTE:** Here we use [`plot_stat_map`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_stat_map.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the orthographic images
%% Cell type:code id: tags:
``` python
plotting.plot_stat_map(
stat_img,
threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'
)
```
%% Cell type:markdown id: tags:
Like with the `plot_anat` examples earlier, we can style the plot and change the layout and views.
%% Cell type:code id: tags:
``` python
plotting.plot_stat_map(
stat_img,
threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
display_mode='z',
cut_coords=10,
title='motor-task',
dim=-0.5,
vmax=10
)
```
%% Cell type:markdown id: tags:
In this next example we first find the coordinate of the centre of the largest connected component in the statistical map, then we plot an ortho view that is centred on this coordinate.
%% Cell type:code id: tags:
``` python
# find the coordinate of the centre of the largest connected component in the statistical map
coord = plotting.find_xyz_cut_coords(stat_img)
print(f'Center of the largest activation connected component = {coord}')
# plot an ortho view that is centred on this coordinate
plotting.plot_stat_map(
stat_img,
threshold=3,
bg_img=f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz',
display_mode='ortho',
cut_coords=coord,
title='motor-task',
dim=-0.5,
vmax=10
)
```
%% Cell type:markdown id: tags:
`nilearn` has some support for **interactive** viewing of volumetic images with the `view_img` function. Try clicking on the plot and moving the cursor around!
%% Cell type:code id: tags:
``` python
view = plotting.view_img(stat_img, threshold=3)
view # view interactive plot inline
```
%% Cell type:code id: tags:
``` python
view = plotting.view_img(stat_img, threshold=3)
view.open_in_browser() # open interactive plot in new web browser
```
%% Cell type:markdown id: tags:
## 2D maximum intensity projection
> Maximum intensity projection (MIP) is a method for 3D data that projects in the visualization plane the voxels with maximum intensity that fall in the way of parallel rays traced from the viewpoint to the plane of projection. https://en.wikipedia.org/wiki/Maximum_intensity_projection
`nilearn` can plot a maximum intensity projection overlayed on a brain schematic referred to as the "glass brain". In this example, the MIP of the motor task statistical map used in the previous examples is plotted on the glass brain.
> **NOTE:** Here we use [`plot_glass_brain`](https://nilearn.github.io/modules/generated/nilearn.plotting.plot_glass_brain.html) from the [`nilearn`](https://nilearn.github.io/index.html) package to plot the maximum intensity projection.
%% Cell type:code id: tags:
``` python
plotting.plot_glass_brain(
stat_img,
title='2D max-intensity projection',
threshold=3,
)
```
%% Cell type:markdown id: tags:
## Surfaces
`nilearn` has baked in functionality to project a volumetric image onto the surface and visualise it.