nilearn.ipynb 15.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `nilearn`\n",
    "\n",
    "\n",
    "\n",
11
    "`nilearn` is a python package that provides **statistical** and **machine learning** tools for working with neuroimaging data.\n",
12
13
14
15
16
17
18
    "\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",
19
    "However, `nilearn` also provides a very convenient set of visualisation routines for neuroimaging data.  This notebook will focus on these visualisation tools.\n",
20
    "\n",
21
    "`nilearn` has very good documentation, and the examples below borrow heavily from the visualisation documentation: https://nilearn.github.io/plotting/index.html\n",
22
23
24
25
26
    "\n",
    "## This notebook\n",
    "\n",
    "1. Plotting an anatomical image\n",
    "2. Plotting a statistical map\n",
27
28
    "3. 2D maximum intensity projection\n",
    "4. Surfaces\n",
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    "\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",
43
    "import nibabel as nb\n",
44
    "%matplotlib inline\n",
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
    "\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",
133
    "In this instance, we give `cut_coords` a scalar integer that indicates the number of slices to show in the axial view. "
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
   ]
  },
  {
   "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": [
155
    "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",
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    "\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')"
   ]
  },
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
  {
   "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')"
   ]
  },
228
229
230
231
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    ">\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",
255
256
    "## Plotting a statistical map\n",
    "\n",
257
    "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",
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    "\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 "
   ]
  },
474
475
476
477
478
479
480
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">\n",
    "> **Exercise:**\n",
    "> \n",
481
    "> Visualise thee **Harvard-Oxford** atlas on a surface in the web browser"
482
483
484
485
486
487
488
489
490
491
492
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# YOUR CODE HERE"
   ]
  },
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
  {
   "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",
517
   "version": "3.7.6"
518
519
520
521
522
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}