From 798511ea4d9ada44e18ee9a175d81ccf34af5d8e Mon Sep 17 00:00:00 2001 From: Sean Fitzgibbon Date: Tue, 27 Apr 2021 23:30:06 +0100 Subject: [PATCH 1/3] First pass at nilearn visualisation practical --- applications/nilearn/nilearn.ipynb | 435 +++++++++++++++++++++++++++++ 1 file changed, 435 insertions(+) create mode 100644 applications/nilearn/nilearn.ipynb diff --git a/applications/nilearn/nilearn.ipynb b/applications/nilearn/nilearn.ipynb new file mode 100644 index 0000000..723d5f4 --- /dev/null +++ b/applications/nilearn/nilearn.ipynb @@ -0,0 +1,435 @@ +{ + "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 +} -- GitLab From f1a842eaafb4dd009251e30938657479d45af19a Mon Sep 17 00:00:00 2001 From: Saad Jbabdi Date: Wed, 28 Apr 2021 10:17:22 +0100 Subject: [PATCH 2/3] corrected typos and added 2 exercises --- applications/nilearn/nilearn.ipynb | 61 +++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 9 deletions(-) diff --git a/applications/nilearn/nilearn.ipynb b/applications/nilearn/nilearn.ipynb index 723d5f4..08f1cc8 100644 --- a/applications/nilearn/nilearn.ipynb +++ b/applications/nilearn/nilearn.ipynb @@ -8,7 +8,7 @@ "\n", "\n", "\n", - "`nilearn` is python package that provides **statistical** and **machine learning** tools for working with neurimaging data.\n", + "`nilearn` is a python package that provides **statistical** and **machine learning** tools for working with neuroimaging data.\n", "\n", "According to https://nilearn.github.io/: \n", ">\n", @@ -16,16 +16,16 @@ ">\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", + "However, `nilearn` also provides a very convenient set of visualisation routines for neuroimaging 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", + "`nilearn` has very good documentation, and the examples below borrow heavily from the visualisation 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", + "3. 2D maximum intensity projection\n", + "4. Surfaces\n", "\n", "Firstly we will import the necessary packages for this notebook: " ] @@ -40,6 +40,7 @@ "from nilearn import plotting, datasets, surface\n", "import matplotlib as mpl\n", "import matplotlib.pyplot as plt\n", + "%matplotlib inline\n", "\n", "# get path to FSL installation for the FSLDIR environment variable\n", "FSLDIR = os.environ['FSLDIR']\n", @@ -128,7 +129,7 @@ "- `'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. " + "In this instance, we give `cut_coords` a scalar integer that indicates the number of slices to show in the axial view. " ] }, { @@ -150,7 +151,7 @@ "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", + "In the example below, 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." ] @@ -184,9 +185,32 @@ "cell_type": "markdown", "metadata": {}, "source": [ + ">\n", + "> **Exercise:**\n", + ">\n", + "> Create a PNG figure that displays the same **Harvard-Oxford** parcellation, using a different colormap, and axial images in a 3x5 grid.\n", + ">\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# YOUR CODE HERE" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + "\n", "## 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", + "The examples in this section demonstrate how to plot a 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", @@ -403,6 +427,25 @@ "view.open_in_browser() # view interactive plot inline " ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + ">\n", + "> **Exercise:**\n", + "> \n", + "> Visualise thee **Harvard-Oxford** atlas on a surface in the weeb Browser" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# YOUR CODE HERE" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -427,7 +470,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.6" + "version": "3.7.9" } }, "nbformat": 4, -- GitLab From f55e0b1edd4063d574eef63f04abc5919b25f49b Mon Sep 17 00:00:00 2001 From: Sean Fitzgibbon Date: Wed, 28 Apr 2021 20:16:14 +0100 Subject: [PATCH 3/3] Added example combining matplotlib and nilearn --- applications/nilearn/nilearn.ipynb | 48 ++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/applications/nilearn/nilearn.ipynb b/applications/nilearn/nilearn.ipynb index 08f1cc8..7d966e2 100644 --- a/applications/nilearn/nilearn.ipynb +++ b/applications/nilearn/nilearn.ipynb @@ -40,6 +40,7 @@ "from nilearn import plotting, datasets, surface\n", "import matplotlib as mpl\n", "import matplotlib.pyplot as plt\n", + "import nibabel as nb\n", "%matplotlib inline\n", "\n", "# get path to FSL installation for the FSLDIR environment variable\n", @@ -181,6 +182,49 @@ "display.savefig('myplot.png')" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "`nilearn` plotting is built upon `matplotlib`, so we can use constructs from `matplotlib` to help us create more complex figures. \n", + "\n", + "In this example we:\n", + "1. create a 1x2 grid of subplots using `subplots` from `matplotlib`\n", + "2. plot a single slice of the MNI152 T1w in the first subplot using `plot_anat` from `nilearn`\n", + "3. plot a histogram of the intensities of the MNI152 T12 in the second subplot using `hist` from `matplotlib`\n", + "4. style the histogram by setting the x/y labels\n", + "\n", + "> **NOTE:** Here we use `load` and `get_fdata` from the [`nibabel`](https://nipy.org/nibabel/) package to load the data from the MNI152 T1w nifti for the histogram." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# create matplotlib figure with 1x2 subplots\n", + "fig, ax = plt.subplots(1, 2, figsize=(10, 5))\n", + "\n", + "# plot MNI T1w slice in first subplot\n", + "mni_t1 = f'{FSLDIR}/data/standard/MNI152_T1_1mm.nii.gz'\n", + "\n", + "display = plotting.plot_anat(\n", + " mni_t1, \n", + " dim=-0.5, \n", + " axes=ax[0],\n", + " display_mode='z', \n", + " cut_coords=[15]\n", + ")\n", + "\n", + "# plot histogram of MNI T1w intensity in second subplot\n", + "mni_t1_data = nb.load(mni_t1).get_fdata().ravel()\n", + "\n", + "ax[1].hist(mni_t1_data, bins=25)\n", + "ax[1].set_ylabel('count')\n", + "ax[1].set_xlabel('intensity')" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -434,7 +478,7 @@ ">\n", "> **Exercise:**\n", "> \n", - "> Visualise thee **Harvard-Oxford** atlas on a surface in the weeb Browser" + "> Visualise thee **Harvard-Oxford** atlas on a surface in the web browser" ] }, { @@ -470,7 +514,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.7.9" + "version": "3.7.6" } }, "nbformat": 4, -- GitLab