08_fslpy.ipynb 60 KB
Newer Older
Paul McCarthy's avatar
Paul McCarthy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `fslpy`\n",
    "\n",
    "\n",
    "[`fslpy`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/) is a\n",
    "Python library which is built into FSL, and contains a range of functionality\n",
    "for working with neuroimaging data from Python.\n",
    "\n",
    "\n",
    "This practical highlights some of the most useful features provided by\n",
    "`fslpy`. You may find `fslpy` useful if you are writing Python code to\n",
    "perform analyses and image processing in conjunction with FSL.\n",
    "\n",
    "\n",
    "> **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python\n",
    "> environment that is baked into FSL. `fslpy` is a Python library which is\n",
    "> installed into the `fslpython` environment.\n",
    "\n",
    "\n",
    "* [The `Image` class, and other data types](#the-image-class-and-other-data-types)\n",
    "  * [Creating images](#creating-images)\n",
    "  * [Working with image data](#working-with-image-data)\n",
    "  * [Loading other file types](#loading-other-file-types)\n",
Paul McCarthy's avatar
Paul McCarthy committed
29
30
    "  * [NIfTI coordinate systems](#nifti-coordinate-systems)\n",
    "  * [Image processing](#image-processing)\n",
Paul McCarthy's avatar
Paul McCarthy committed
31
    "* [FSL wrapper functions](#fsl-wrapper-functions)\n",
Paul McCarthy's avatar
Paul McCarthy committed
32
33
34
    "  * [In-memory images](#in-memory-images)\n",
    "  * [Loading outputs into Python](#loading-outputs-into-python)\n",
    "  * [The `fslmaths` wrapper](#the-fslmaths-wrapper)\n",
Paul McCarthy's avatar
Paul McCarthy committed
35
36
37
38
39
    "* [The `FileTree`](#the-filetree)\n",
    "  * [Describing your data](#describing-your-data)\n",
    "  * [Using the `FileTree`](#using-the-filetree)\n",
    "  * [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree)\n",
    "  * [The `FileTreeQuery`](#the-filetreequery)\n",
Paul McCarthy's avatar
Paul McCarthy committed
40
    "* [Calling shell commands](#calling-shell-commands)\n",
Paul McCarthy's avatar
Paul McCarthy committed
41
42
    "  * [The `runfsl` function](#the-runfsl-function)\n",
    "  * [Submitting to the cluster](#submitting-to-the-cluster)\n",
Paul McCarthy's avatar
Paul McCarthy committed
43
    "  * [Redirecting output](#redirecting-output)\n",
Paul McCarthy's avatar
Paul McCarthy committed
44
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
    "* [FSL atlases](#fsl-atlases)\n",
    "  * [Querying atlases](#querying-atlases)\n",
    "  * [Loading atlas images](#loading-atlas-images)\n",
    "  * [Working with atlases](#working-with-atlases)\n",
    "\n",
    "\n",
    "Let's start with some standard imports and environment set-up:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "import os.path as op\n",
    "import nibabel as nib\n",
    "import numpy as np\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And a little function that we can use to generate a simple orthographic plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def ortho(data, voxel, fig=None, **kwargs):\n",
    "    \"\"\"Simple orthographic plot of a 3D array using matplotlib.\n",
    "\n",
    "    :arg data:  3D numpy array\n",
    "    :arg voxel: XYZ coordinates for each slice\n",
    "    :arg fig:   Existing figure and axes for overlay plotting\n",
Paul McCarthy's avatar
Paul McCarthy committed
88
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
89
    "    All other arguments are passed through to the `imshow` function.\n",
Paul McCarthy's avatar
Paul McCarthy committed
90
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
91
92
93
    "    :returns:   The figure and axes (which can be passed back in as the\n",
    "                `fig` argument to plot overlays).\n",
    "    \"\"\"\n",
Paul McCarthy's avatar
Paul McCarthy committed
94
95
96
97
    "\n",
    "    data            = np.asanyarray(data, dtype=np.float)\n",
    "    data[data <= 0] = np.nan\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
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
133
134
135
136
    "    x, y, z = voxel\n",
    "    xslice  = np.flipud(data[x, :, :].T)\n",
    "    yslice  = np.flipud(data[:, y, :].T)\n",
    "    zslice  = np.flipud(data[:, :, z].T)\n",
    "\n",
    "    if fig is None:\n",
    "        fig = plt.figure()\n",
    "        xax = fig.add_subplot(1, 3, 1)\n",
    "        yax = fig.add_subplot(1, 3, 2)\n",
    "        zax = fig.add_subplot(1, 3, 3)\n",
    "    else:\n",
    "        fig, xax, yax, zax = fig\n",
    "\n",
    "    xax.imshow(xslice, **kwargs)\n",
    "    yax.imshow(yslice, **kwargs)\n",
    "    zax.imshow(zslice, **kwargs)\n",
    "\n",
    "    for ax in (xax, yax, zax):\n",
    "        ax.set_xticks([])\n",
    "        ax.set_yticks([])\n",
    "    fig.tight_layout(pad=0)\n",
    "\n",
    "    return (fig, xax, yax, zax)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And another function which uses FSLeyes for more complex plots:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def render(cmdline):\n",
Paul McCarthy's avatar
Paul McCarthy committed
137
138
139
140
    "\n",
    "    import shlex\n",
    "    import IPython.display as display\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
141
    "    prefix = '-of screenshot.png -hl -c 2 '\n",
Paul McCarthy's avatar
Paul McCarthy committed
142
143
144
145
146
147
148
149
150
151
152
153
    "\n",
    "    try:\n",
    "        from fsleyes.render import main\n",
    "        main(shlex.split(prefix + cmdline))\n",
    "\n",
    "    except ImportError:\n",
    "        # fall-back for macOS - we have to run\n",
    "        # FSLeyes render in a separate process\n",
    "        from fsl.utils.run import runfsl\n",
    "        prefix = 'render ' + prefix\n",
    "        runfsl(prefix + cmdline, env={})\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
154
155
156
157
158
159
160
    "    return display.Image('screenshot.png')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
    "<a class=\"anchor\" id=\"the-image-class-and-other-data-types\"></a>\n",
    "## The `Image` class, and other data types\n",
    "\n",
    "\n",
    "The\n",
    "[`fsl.data.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)\n",
    "module provides the `Image` class, which sits on top of `nibabel` and contains\n",
    "some handy functionality if you need to work with coordinate transformations,\n",
    "or do some FSL-specific processing. The `Image` class provides features such\n",
    "as:\n",
    "\n",
    "- Support for NIFTI1, NIFTI2, and ANALYZE image files\n",
    "- Access to affine transformations between the voxel, FSL and world coordinate\n",
    "  systems\n",
    "- Ability to load metadata from BIDS sidecar files\n",
    "\n",
    "\n",
    "Some simple image processing routines are also provided - these are covered\n",
    "[below](#image-processing).\n",
    "\n",
    "\n",
    "<a class=\"anchor\" id=\"creating-images\"></a>\n",
    "### Creating images\n",
    "\n",
    "\n",
    "It's easy to create an `Image` - you can create one from a file name:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.data.image import Image\n",
    "\n",
    "stddir = op.expandvars('${FSLDIR}/data/standard/')\n",
    "\n",
    "# load a FSL image - the file\n",
    "# suffix is optional, just like\n",
    "# in real FSL-land!\n",
    "img = Image(op.join(stddir, 'MNI152_T1_1mm'))\n",
    "print(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can create an `Image` from an existing `nibabel` image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load a nibabel image, and\n",
    "# convert it into an FSL image\n",
    "nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz'))\n",
    "img    = Image(nibimg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or you can create an `Image` from a `numpy` array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = np.zeros((100, 100, 100))\n",
    "img = Image(data, xform=np.eye(4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can save an image to file via the `save` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img.save('empty.nii.gz')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Image` objects have all of the attributes you might expect:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stddir = op.expandvars('${FSLDIR}/data/standard/')\n",
    "std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))\n",
    "\n",
    "print('name:         ', std1mm.name)\n",
    "print('file:         ', std1mm.dataSource)\n",
    "print('NIfTI version:', std1mm.niftiVersion)\n",
    "print('ndim:         ', std1mm.ndim)\n",
    "print('shape:        ', std1mm.shape)\n",
    "print('dtype:        ', std1mm.dtype)\n",
    "print('nvals:        ', std1mm.nvals)\n",
    "print('pixdim:       ', std1mm.pixdim)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and a number of useful methods:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "std2mm  = Image(op.join(stddir, 'MNI152_T1_2mm'))\n",
Paul McCarthy's avatar
Paul McCarthy committed
298
    "mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask'))\n",
Paul McCarthy's avatar
Paul McCarthy committed
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
    "\n",
    "print(std1mm.sameSpace(std2mm))\n",
    "print(std2mm.sameSpace(mask2mm))\n",
    "print(std2mm.getAffine('voxel', 'world'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An `Image` object is a high-level wrapper around a `nibabel` image object -\n",
    "you can always work directly with the `nibabel` object via the `nibImage`\n",
    "attribute:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(std2mm)\n",
    "print(std2mm.nibImage)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"working-with-image-data\"></a>\n",
    "### Working with image data\n",
    "\n",
    "\n",
    "You can get the image data as a `numpy` array via the `data` attribute:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = std2mm.data\n",
Paul McCarthy's avatar
Paul McCarthy committed
342
343
    "print(data.min(), data.max())\n",
    "ortho(data, (45, 54, 45))"
Paul McCarthy's avatar
Paul McCarthy committed
344
345
346
347
348
349
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
350
351
    "> Note that `Image.data` will give you the data in its underlying type, unlike\n",
    "> the `nibabel.get_fdata` method, which up-casts image data to floating-point.\n",
Paul McCarthy's avatar
Paul McCarthy committed
352
353
354
355
356
357
358
359
360
361
362
363
    "\n",
    "\n",
    "You can also read and write data directly via the `Image` object:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "slc = std2mm[:, :, 45]\n",
Paul McCarthy's avatar
Paul McCarthy committed
364
    "std2mm[0:10, :, :] *= 2"
Paul McCarthy's avatar
Paul McCarthy committed
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
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Doing so has some advantages that may or may not be useful, depending on your\n",
    "use-case:\n",
    " - The image data will be kept on disk - only the parts that you access will\n",
    "   be loaded into RAM (you will also need to pass`loadData=False` when creating\n",
    "   the `Image` to achieve this).\n",
    " - The `Image` object will keep track of modifications to the data - this can\n",
    "   be queried via the `saveState` attribute.\n",
    "\n",
    "\n",
    "<a class=\"anchor\" id=\"loading-other-file-types\"></a>\n",
    "### Loading other file types\n",
    "\n",
    "\n",
    "The\n",
    "[`fsl.data`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.html#module-fsl.data)\n",
    "package has a number of other classes for working with different types of FSL\n",
    "and neuroimaging data. Most of these are higher-level wrappers around the\n",
    "corresponding `nibabel` types:\n",
    "\n",
    "* The\n",
    "  [`fsl.data.bitmap.Bitmap`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.bitmap.html)\n",
    "  class can be used to load a bitmap image (e.g. `jpg, `png`, etc) and\n",
    "  convert it to a NIfTI image.\n",
    "* The\n",
    "  [`fsl.data.dicom.DicomImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dicom.html)\n",
    "  class uses `dcm2niix` to load NIfTI images contained within a DICOM\n",
    "  directory<sup>*</sup>.\n",
    "* The\n",
Paul McCarthy's avatar
Paul McCarthy committed
399
    "  [`fsl.data.mghimage.MGHImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.mghimage.html)\n",
Paul McCarthy's avatar
Paul McCarthy committed
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
    "  class can be used too load `.mgh`/`.mgz` images (they are converted into\n",
    "  NIfTI images).\n",
    "* The\n",
    "  [`fsl.data.dtifit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dtifit.html)\n",
    "  module contains functions for loading and working with the output of the\n",
    "  FSL `dtifit` tool.\n",
    "* The\n",
    "  [`fsl.data.featanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featanalysis.html),\n",
    "  [`fsl.data.featimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featimage.html),\n",
    "  and\n",
    "  [`fsl.data.featdesign`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featdesign.html)\n",
    "  modules contain classes and functions for loading data from FEAT\n",
    "  directories.\n",
    "* Similarly, the\n",
    "  [`fsl.data.melodicanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicanalysis.html)\n",
    "  and\n",
    "  [`fsl.data.melodicimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicimage.html)\n",
    "  modules contain classes and functions for loading data from MELODIC\n",
    "  directories.\n",
    "* The\n",
    "  [`fsl.data.gifti`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.gifti.html),\n",
    "  [`fsl.data.freesurfer`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.freesurfer.html),\n",
    "  and\n",
    "  [`fsl.data.vtk`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.vtk.html)\n",
    "  modules contain functionality form loading surface data from GIfTI,\n",
Paul McCarthy's avatar
Paul McCarthy committed
425
    "  freesurfer, and ASCII VTK files respectively.\n",
Paul McCarthy's avatar
Paul McCarthy committed
426
427
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
428
429
430
    "> <sup>*</sup>You must make sure that\n",
    "> [`dcm2niix`](https://github.com/rordenlab/dcm2niix/) is installed on your\n",
    "> system in order to use this class.\n",
Paul McCarthy's avatar
Paul McCarthy committed
431
432
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
433
434
    "<a class=\"anchor\" id=\"nifti-coordinate-systems\"></a>\n",
    "### NIfTI coordinate systems\n",
Paul McCarthy's avatar
Paul McCarthy committed
435
436
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
    "The `Image.getAffine` method gives you access to affine transformations which\n",
    "can be used to convert coordinates between the different coordinate systems\n",
    "associated with a NIfTI image. Have some MNI coordinates you'd like to convert\n",
    "to voxels? Easy!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stddir = op.expandvars('${FSLDIR}/data/standard/')\n",
    "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n",
    "\n",
    "mnicoords = np.array([[0,   0,  0],\n",
    "                      [0, -18, 18]])\n",
Paul McCarthy's avatar
Paul McCarthy committed
454
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
455
456
    "world2vox = std2mm.getAffine('world', 'voxel')\n",
    "vox2world = std2mm.getAffine('voxel', 'world')\n",
Paul McCarthy's avatar
Paul McCarthy committed
457
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    "# Apply the world->voxel\n",
    "# affine to the coordinates\n",
    "voxcoords = (np.dot(world2vox[:3, :3], mnicoords.T)).T + world2vox[:3, 3]\n",
    "\n",
    "# The code above is a bit fiddly, so\n",
    "# instead of figuring it out, you can\n",
    "# just use the transform() function:\n",
    "from fsl.transform.affine import transform\n",
    "voxcoords = transform(mnicoords, world2vox)\n",
    "\n",
    "# just to double check, let's transform\n",
    "# those voxel coordinates back into world\n",
    "# coordinates\n",
    "backtomni = transform(voxcoords, vox2world)\n",
    "\n",
    "for m, v, b in zip(mnicoords, voxcoords, backtomni):\n",
    "    print(m, '->', v, '->', b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> The `Image.getAffine` method can give you transformation matrices\n",
    "> between any of these coordinate systems:\n",
    ">\n",
    ">  - `'voxel'`: Image data voxel coordinates\n",
    ">  - `'world'`: mm coordinates, defined by the sform/qform of an image\n",
    ">  - `'fsl'`: The FSL coordinate system, used internally by many FSL tools\n",
    ">    (e.g. FLIRT)\n",
    "\n",
    "\n",
    "Oh, that example was too easy I hear you say? Try this one on for size. Let's\n",
    "say we have run FEAT on some task fMRI data, and want to get the MNI\n",
    "coordinates of the voxel with peak activation.\n",
    "\n",
    "\n",
    "> This is what people used to use `Featquery` for, back in the un-enlightened\n",
    "> days.\n",
    "\n",
    "\n",
    "Let's start by identifying the voxel with the biggest t-statistic:"
Paul McCarthy's avatar
Paul McCarthy committed
500
501
502
503
504
505
506
507
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
508
    "featdir = op.join('08_fslpy', 'fmri.feat')\n",
Paul McCarthy's avatar
Paul McCarthy committed
509
510
511
512
513
514
515
516
517
518
519
    "\n",
    "tstat1 = Image(op.join(featdir, 'stats', 'tstat1')).data\n",
    "\n",
    "# Recall from the numpy practical that\n",
    "# argmax gives us a 1D index into a\n",
    "# flattened view of the array. We can\n",
    "# use the unravel_index function to\n",
    "# convert it into a 3D index.\n",
    "peakvox = np.abs(tstat1).argmax()\n",
    "peakvox = np.unravel_index(peakvox, tstat1.shape)\n",
    "print('Peak voxel coordinates for tstat1:', peakvox, tstat1[peakvox])"
Paul McCarthy's avatar
Paul McCarthy committed
520
521
522
523
524
525
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
526
527
528
    "Now that we've got the voxel coordinates in functional space, we need to\n",
    "transform them into MNI space. FEAT provides a transformation which goes\n",
    "directly from functional to standard space, in the `reg` directory:"
Paul McCarthy's avatar
Paul McCarthy committed
529
530
531
532
533
534
535
536
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
537
    "func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))"
Paul McCarthy's avatar
Paul McCarthy committed
538
539
540
541
542
543
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
544
545
546
547
548
549
    "But ... wait a minute ... this is a FLIRT matrix! We can't just plug voxel\n",
    "coordinates into a FLIRT matrix and expect to get sensible results, because\n",
    "FLIRT works in an internal FSL coordinate system, which is not quite\n",
    "`'voxel'`, and not quite `'world'`. So we need to do a little more work.\n",
    "Let's start by loading our functional image, and the MNI152 template (the\n",
    "source and reference images of our FLIRT matrix):"
Paul McCarthy's avatar
Paul McCarthy committed
550
551
552
553
554
555
556
557
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
558
559
    "func = Image(op.join(featdir, 'reg', 'example_func'))\n",
    "std  = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))"
Paul McCarthy's avatar
Paul McCarthy committed
560
561
562
563
564
565
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
566
567
568
569
570
571
572
    "Now we can use them to get affines which convert between all of the different\n",
    "coordinate systems - we're going to combine them into a single uber-affine,\n",
    "which transforms our functional-space voxels into MNI world coordinates via:\n",
    "\n",
    "   1. functional voxels -> FLIRT source space\n",
    "   2. FLIRT source space -> FLIRT reference space\n",
    "   3. FLIRT referece space -> MNI world coordinates"
Paul McCarthy's avatar
Paul McCarthy committed
573
574
575
576
577
578
579
580
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
581
582
    "vox2fsl = func.getAffine('voxel', 'fsl')\n",
    "fsl2mni = std .getAffine('fsl',   'world')"
Paul McCarthy's avatar
Paul McCarthy committed
583
584
585
586
587
588
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
589
590
    "Combining two affines into one is just a simple dot-product. There is a\n",
    "`concat()` function which does this for us, for any number of affines:"
Paul McCarthy's avatar
Paul McCarthy committed
591
592
593
594
595
596
597
598
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
599
    "from fsl.transform.affine import concat\n",
Paul McCarthy's avatar
Paul McCarthy committed
600
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
601
602
603
604
    "# To combine affines together, we\n",
    "# have to list them in reverse -\n",
    "# linear algebra is *weird*.\n",
    "funcvox2mni = concat(fsl2mni, func2std, vox2fsl)"
Paul McCarthy's avatar
Paul McCarthy committed
605
606
607
608
609
610
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
611
612
613
614
615
    "> Below we will use the\n",
    "> [`fsl.transform.flirt.fromFlirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html#fsl.transform.flirt.fromFlirt)\n",
    "> function, which does all of the above for us.\n",
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
616
617
    "So we've now got some voxel coordinates from our functional data, and an\n",
    "affine to transform into MNI world coordinates. The rest is easy:"
Paul McCarthy's avatar
Paul McCarthy committed
618
619
620
621
622
623
624
625
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
626
627
628
629
630
    "mnicoords = transform(peakvox, funcvox2mni)\n",
    "mnivoxels = transform(mnicoords, std.getAffine('world', 'voxel'))\n",
    "mnivoxels = [int(round(v)) for v in mnivoxels]\n",
    "print('Peak activation (MNI coordinates):', mnicoords)\n",
    "print('Peak activation (MNI voxels):     ', mnivoxels)"
Paul McCarthy's avatar
Paul McCarthy committed
631
632
633
634
635
636
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    "> Note that in the above example we are only applying a linear transformation\n",
    "> into MNI space - in reality you would also want to apply your non-linear\n",
    "> structural-to-standard transformation too. But this is left as [an exercise\n",
    "> for the\n",
    "> reader](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.fnirt.html).\n",
    "\n",
    "\n",
    "<a class=\"anchor\" id=\"image-processing\"></a>\n",
    "### Image processing\n",
    "\n",
    "\n",
    "Now, it's all well and good to look at t-statistic values and voxel\n",
    "coordinates and so on and so forth, but let's spice things up a bit and look\n",
    "at some images. Let's display our peak activation location in MNI space. To do\n",
    "this, we're going to resample our functional image into MNI space, so we can\n",
    "overlay it on the MNI template. This can be done using some handy functions\n",
    "from the\n",
    "[`fsl.utils.image.resample`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.resample.html)\n",
    "module:"
Paul McCarthy's avatar
Paul McCarthy committed
656
657
658
659
660
661
662
663
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
664
665
    "from fsl.transform.flirt import fromFlirt\n",
    "from fsl.utils.image.resample import resampleToReference\n",
Paul McCarthy's avatar
Paul McCarthy committed
666
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
667
668
669
    "featdir = op.join(op.join('08_fslpy', 'fmri.feat'))\n",
    "tstat1  = Image(op.join(featdir, 'stats', 'tstat1'))\n",
    "std     = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))\n",
Paul McCarthy's avatar
Paul McCarthy committed
670
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
671
672
673
674
675
676
677
    "# Load the func2standard FLIRT matrix, and adjust it\n",
    "# so that it transforms from functional *world*\n",
    "# coordinates into standard *world* coordinates -\n",
    "# this is what is expected by the resampleToReference\n",
    "# function, used below\n",
    "func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))\n",
    "func2std = fromFlirt(func2std, tstat1, std, 'world', 'world')\n",
Paul McCarthy's avatar
Paul McCarthy committed
678
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
679
680
681
682
683
684
685
686
687
    "# All of the functions in the resample module\n",
    "# return a numpy array containing the resampled\n",
    "# data, and an adjusted voxel-to-world affine\n",
    "# transformation. But when using the\n",
    "# resampleToReference function, the affine will\n",
    "# be the same as the MNI152 2mm affine, so we\n",
    "# can ignore it.\n",
    "std_tstat1 = resampleToReference(tstat1, std, func2std)[0]\n",
    "std_tstat1 = Image(std_tstat1, header=std.header)"
Paul McCarthy's avatar
Paul McCarthy committed
688
689
690
691
692
693
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
694
695
    "Now that we have our t-statistic image in MNI152 space, we can plot it in\n",
    "standard space using `matplotlib`:"
Paul McCarthy's avatar
Paul McCarthy committed
696
697
698
699
700
701
702
703
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
704
705
    "stddir = op.expandvars('${FSLDIR}/data/standard/')\n",
    "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n",
Paul McCarthy's avatar
Paul McCarthy committed
706
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
707
708
    "std_tstat1                 = std_tstat1.data\n",
    "std_tstat1[std_tstat1 < 3] = 0\n",
Paul McCarthy's avatar
Paul McCarthy committed
709
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
710
711
    "fig = ortho(std2mm.data, mnivoxels, cmap=plt.cm.gray)\n",
    "fig = ortho(std_tstat1,  mnivoxels, cmap=plt.cm.inferno, fig=fig)"
Paul McCarthy's avatar
Paul McCarthy committed
712
713
714
715
716
717
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
718
719
720
721
722
723
724
    "There are a few other useful functions tucked away in the\n",
    "[fsl.utils.image](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.html)\n",
    "package, with more to be added in the future. The [`fsl.transform`]() package\n",
    "also contains a wealth of functionality for working with linear (FLIRT) and\n",
    "non-linear (FNIRT) transformations.\n",
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
725
726
727
728
    "<a class=\"anchor\" id=\"fsl-wrapper-functions\"></a>\n",
    "## FSL wrapper functions\n",
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
729
730
731
732
733
    "The\n",
    "[fsl.wrappers](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.wrappers.html)\n",
    "package is the home of \"wrapper\" functions for a range of FSL tools. You can\n",
    "use them to call an FSL tool from Python code, without having to worry about\n",
    "constructing a command-line, or saving/loading input/output images.\n",
Paul McCarthy's avatar
Paul McCarthy committed
734
735
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
736
737
738
739
    "> The `fsl.wrappers` functions also allow you to submit jobs to be run on the\n",
    "> cluster - this is described [below](#submitting-to-the-cluster).\n",
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
740
741
    "You can use the FSL wrapper functions with file names, similar to calling the\n",
    "corresponding tool via the command-line:"
Paul McCarthy's avatar
Paul McCarthy committed
742
743
744
745
746
747
748
749
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
750
    "from fsl.wrappers import bet, robustfov, LOAD\n",
Paul McCarthy's avatar
Paul McCarthy committed
751
752
753
754
755
756
757
758
759
760
    "\n",
    "robustfov('08_fslpy/bighead', 'bighead_cropped')\n",
    "\n",
    "render('08_fslpy/bighead bighead_cropped -cm blue')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
761
    "The `fsl.wrappers` functions strive to provide an interface which is as close\n",
Paul McCarthy's avatar
Paul McCarthy committed
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
    "as possible to the command-line tool - most functions use positional arguments\n",
    "for required options, and keyword arguments for all other options, with\n",
    "argument names equivalent to command line option names. For example, the usage\n",
    "for the command-line `bet` tool is as follows:\n",
    "\n",
    "\n",
    "> ```\n",
    "> Usage:    bet <input> <output> [options]\n",
    ">\n",
    "> Main bet2 options:\n",
    ">   -o          generate brain surface outline overlaid onto original image\n",
    ">   -m          generate binary brain mask\n",
    ">   -s          generate approximate skull image\n",
    ">   -n          don't generate segmented brain image output\n",
    ">   -f <f>      fractional intensity threshold (0->1); default=0.5; smaller values give larger brain outline estimates\n",
    ">   -g <g>      vertical gradient in fractional intensity threshold (-1->1); default=0; positive values give larger brain outline at bottom, smaller at top\n",
    ">   -r <r>      head radius (mm not voxels); initial surface sphere is set to half of this\n",
    ">   -c <x y z>  centre-of-gravity (voxels not mm) of initial mesh surface.\n",
    "> ...\n",
    "> ```\n",
    "\n",
    "\n",
    "So to use the `bet()` wrapper function, pass `<input>` and `<output>` as\n",
    "positional arguments, and pass the additional options as keyword arguments:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bet('bighead_cropped', 'bighead_cropped_brain', f=0.3, m=True, s=True)\n",
    "\n",
    "render('bighead_cropped             -b 40 '\n",
    "       'bighead_cropped_brain       -cm hot '\n",
    "       'bighead_cropped_brain_skull -ot mask -mc 0.4 0.4 1 '\n",
    "       'bighead_cropped_brain_mask  -ot mask -mc 0   1   0 -o -w 5')"
Paul McCarthy's avatar
Paul McCarthy committed
800
801
802
803
804
805
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
806
807
808
809
810
811
812
813
814
    "> Some FSL commands accept arguments which cannot be used as Python\n",
    "> identifiers - for example, the `-2D` option to `flirt` cannot be used as an\n",
    "> identifier in Python, because it begins with a number. In situations like\n",
    "> this, an alias is used. So to set the `-2D` option to `flirt`, you can do this:\n",
    ">\n",
    "> ```\n",
    "> # \"twod\" applies the -2D flag\n",
    "> flirt('source.nii.gz', 'ref.nii.gz', omat='src2ref.mat', twod=True)\n",
    "> ```\n",
Paul McCarthy's avatar
Paul McCarthy committed
815
816
817
818
    ">\n",
    "> Some of the `fsl.wrappers` functions also support aliases which may make\n",
    "> your code more readable. For example, when calling `bet`, you can use either\n",
    "> `m=True` or `mask=True` to apply the `-m` command line flag.\n",
Paul McCarthy's avatar
Paul McCarthy committed
819
820
821
822
823
824
825
    "\n",
    "\n",
    "<a class=\"anchor\" id=\"in-memory-images\"></a>\n",
    "### In-memory images\n",
    "\n",
    "\n",
    "It can be quite awkward to combine image processing with FSL tools and image\n",
Paul McCarthy's avatar
Paul McCarthy committed
826
    "processing in Python. The `fsl.wrappers` package tries to make this a little\n",
Paul McCarthy's avatar
Paul McCarthy committed
827
    "easier for you - if you are working with image data in Python, you can pass\n",
Paul McCarthy's avatar
Paul McCarthy committed
828
    "`Image` or `nibabel` objects directly into `fsl.wrappers` functions - they will\n",
Paul McCarthy's avatar
Paul McCarthy committed
829
830
    "be automatically saved to temporary files and passed to the underlying FSL\n",
    "command:"
Paul McCarthy's avatar
Paul McCarthy committed
831
832
833
834
835
836
837
838
839
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cropped = Image('bighead_cropped')\n",
Paul McCarthy's avatar
Paul McCarthy committed
840
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
    "bet(cropped, 'bighead_cropped_brain')\n",
    "\n",
    "betted = Image('bighead_cropped_brain')\n",
    "\n",
    "fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)\n",
    "fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"loading-outputs-into-python\"></a>\n",
    "### Loading outputs into Python\n",
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
857
    "By using the special `fsl.wrappers.LOAD` symbol, you can also have any output\n",
Paul McCarthy's avatar
Paul McCarthy committed
858
    "files produced by the tool automatically loaded into memory for you:"
Paul McCarthy's avatar
Paul McCarthy committed
859
860
861
862
863
864
865
866
867
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cropped = Image('bighead_cropped')\n",
Paul McCarthy's avatar
Paul McCarthy committed
868
869
870
871
872
    "\n",
    "# The loaded result is called \"output\",\n",
    "# because that is the name of the\n",
    "# argument in the bet wrapper function.\n",
    "betted  = bet(cropped, LOAD).output\n",
Paul McCarthy's avatar
Paul McCarthy committed
873
874
875
876
877
878
879
880
881
882
    "\n",
    "fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)\n",
    "fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use the `LOAD` symbol for any output argument - any output files which\n",
Paul McCarthy's avatar
Paul McCarthy committed
883
    "are loaded will be available through the return value of the wrapper function:"
Paul McCarthy's avatar
Paul McCarthy committed
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.wrappers import flirt\n",
    "\n",
    "std2mm   = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))\n",
    "tstat1   = Image(op.join('08_fslpy', 'fmri.feat', 'stats', 'tstat1'))\n",
    "func2std = np.loadtxt(op.join('08_fslpy', 'fmri.feat', 'reg', 'example_func2standard.mat'))\n",
    "\n",
    "aligned = flirt(tstat1, std2mm, applyxfm=True, init=func2std, out=LOAD)\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
900
901
902
903
    "# Here the resampled tstat image\n",
    "# is called \"out\", because that\n",
    "# is the name of the flirt argument.\n",
    "aligned = aligned.out.data\n",
Paul McCarthy's avatar
Paul McCarthy committed
904
905
906
907
908
909
910
911
912
913
    "aligned[aligned < 1] = 0\n",
    "\n",
    "fig = ortho(std2mm .data, (45, 54, 45), cmap=plt.cm.gray)\n",
    "fig = ortho(aligned.data, (45, 54, 45), cmap=plt.cm.inferno, fig=fig)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
914
915
    "For tools like `bet` and `fast`, which expect an output *prefix* or\n",
    "*basename*, you can just set the prefix to `LOAD` - all output files with that\n",
Paul McCarthy's avatar
Paul McCarthy committed
916
    "prefix will be available in the object that is returned:"
Paul McCarthy's avatar
Paul McCarthy committed
917
918
919
920
921
922
923
924
925
926
927
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img    = Image('bighead_cropped')\n",
    "betted = bet(img, LOAD, f=0.3, m=True)\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
928
929
930
    "fig = ortho(img               .data, (80, 112, 85), cmap=plt.cm.gray)\n",
    "fig = ortho(betted.output     .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)\n",
    "fig = ortho(betted.output_mask.data, (80, 112, 85), cmap=plt.cm.summer,  fig=fig, alpha=0.5)"
Paul McCarthy's avatar
Paul McCarthy committed
931
932
933
934
935
936
937
938
939
940
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"the-fslmaths-wrapper\"></a>\n",
    "### The `fslmaths` wrapper\n",
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
941
    "*Most* of the `fsl.wrappers` functions aim to provide an interface which is as\n",
Paul McCarthy's avatar
Paul McCarthy committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
    "close as possible to the underlying FSL tool. Ideally, if you read the\n",
    "command-line help for a tool, you should be able to figure out how to use the\n",
    "corresponding wrapper function. The wrapper for the `fslmaths` command is a\n",
    "little different, however. It provides more of an object-oriented interface,\n",
    "which is hopefully a little easier to use from within Python.\n",
    "\n",
    "\n",
    "You can apply an `fslmaths` operation by specifying the input file, *chaining*\n",
    "method calls together, and finally calling the `run()` method. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
959
    "from fsl.wrappers import fslmaths\n",
Paul McCarthy's avatar
Paul McCarthy committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
    "fslmaths('bighead_cropped')            \\\n",
    "  .mas(  'bighead_cropped_brain_mask') \\\n",
    "  .run(  'bighead_cropped_brain')\n",
    "\n",
    "render('bighead_cropped bighead_cropped_brain -cm hot')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Of course, you can also use the `fslmaths` wrapper with in-memory images:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wholehead   = Image('bighead_cropped')\n",
    "brainmask   = Image('bighead_cropped_brain_mask')\n",
    "\n",
    "eroded      = fslmaths(brainmask).ero().ero().run()\n",
    "erodedbrain = fslmaths(wholehead).mas(eroded).run()\n",
    "\n",
    "fig = ortho(wholehead  .data, (80, 112, 85), cmap=plt.cm.gray)\n",
    "fig = ortho(brainmask  .data, (80, 112, 85), cmap=plt.cm.summer,  fig=fig)\n",
    "fig = ortho(erodedbrain.data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)"
Paul McCarthy's avatar
Paul McCarthy committed
989
990
   ]
  },
Paul McCarthy's avatar
Paul McCarthy committed
991
992
993
994
995
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"the-filetree\"></a>\n",
Paul McCarthy's avatar
Paul McCarthy committed
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
    "## The `FileTree`\n",
    "\n",
    "\n",
    "The\n",
    "[`fsl.utils.filetree`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html)\n",
    "library provides functionality which allows you to work with *structured data\n",
    "directories*, such as HCP or BIDS datasets. You can use `filetree` for both\n",
    "reading and for creating datasets.\n",
    "\n",
    "\n",
    "This practical gives a very brief introduction to the `filetree` library -\n",
    "refer to the [full\n",
    "documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html)\n",
    "to get a feel for how powerful it can be.\n",
    "\n",
    "\n",
    "<a class=\"anchor\" id=\"describing-your-data\"></a>\n",
    "### Describing your data\n",
    "\n",
    "\n",
    "To introduce `filetree`, we'll begin with a small example. Imagine that we\n",
    "have a dataset which looks like this:\n",
    "\n",
    "\n",
    "> ```\n",
    "> mydata\n",
    "> ├── sub_A\n",
    "> │   ├── ses_1\n",
    "> │   │   └── T1w.nii.gz\n",
    "> │   ├── ses_2\n",
    "> │   │   └── T1w.nii.gz\n",
    "> │   └── T2w.nii.gz\n",
    "> ├── sub_B\n",
    "> │   ├── ses_1\n",
    "> │   │   └── T1w.nii.gz\n",
    "> │   ├── ses_2\n",
    "> │   │   └── T1w.nii.gz\n",
    "> │   └── T2w.nii.gz\n",
    "> └── sub_C\n",
    ">     ├── ses_1\n",
    ">     │   └── T1w.nii.gz\n",
    ">     ├── ses_2\n",
    ">     │   └── T1w.nii.gz\n",
    ">     └── T2w.nii.gz\n",
    "> ```\n",
    "\n",
    "\n",
    "(Run the code cell below to create a dummy data set with the above structure):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "for sub in A B C; do\n",
    "  subdir=mydata/sub_$sub/\n",
    "  mkdir -p $subdir\n",
    "  cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $subdir/T2w.nii.gz\n",
    "  for ses in 1 2; do\n",
    "    sesdir=$subdir/ses_$ses/\n",
    "    mkdir $sesdir\n",
    "    cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $sesdir/T1w.nii.gz\n",
    "  done\n",
    "done"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To use `filetree` with this dataset, we must first describe its structure - we\n",
    "do this by creating a `.tree` file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile mydata.tree\n",
    "sub_{subject}\n",
    "  T2w.nii.gz\n",
    "  ses_{session}\n",
    "    T1w.nii.gz"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A `.tree` file is simply a description of the structure of your data\n",
    "directory - it describes the *file types* (also known as *templates*) which\n",
    "are present in the dataset (`T1w` and `T2w`), and the *variables* which are\n",
    "implicitly present in the structure of the dataset (`subject` and `session`).\n",
    "\n",
    "\n",
    "<a class=\"anchor\" id=\"using-the-filetree\"></a>\n",
    "### Using the `FileTree`\n",
    "\n",
    "\n",
    "Now that we have a `.tree` file which describe our data, we can create a\n",
    "`FileTree` to work with it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.utils.filetree import FileTree\n",
    "\n",
    "tree = FileTree.read('mydata.tree', 'mydata')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can list all of the T1 images via the `FileTree.get_all` method. The\n",
    "`glob_vars='all'` option tells the `FileTree` to fill in the `T1w` template\n",
    "with all possible combinations of variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for t1file in tree.get_all('T1w', glob_vars='all'):\n",
    "    fvars = tree.extract_variables('T1w', t1file)\n",
    "    print(t1file, fvars)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `FileTree.update` method allows you to \"fill in\" variable values; it\n",
    "returns a new `FileTree` object which can be used on a selection of the\n",
    "data set:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "treeA = tree.update(subject='A')\n",
    "for t1file in treeA.get_all('T1w', glob_vars='all'):\n",
    "    fvars = treeA.extract_variables('T1w', t1file)\n",
    "    print(t1file, fvars)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"building-a-processing-pipeline-with-filetree\"></a>\n",
    "### Building a processing pipeline with `FileTree`\n",
Paul McCarthy's avatar
Paul McCarthy committed
1162
1163
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
    "Let's say we want to run BET on all of our T1 images. Let's start by modifying\n",
    "our `.tree` definition to include the BET outputs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile mydata.tree\n",
    "sub_{subject}\n",
    "  T2w.nii.gz\n",
    "  ses_{session}\n",
    "    T1w.nii.gz\n",
    "    T1w_brain.nii.gz\n",
    "    T1w_brain_mask.nii.gz"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can use the `FileTree` to generate the relevant file names for us.\n",
    "Here we'll use the `FileTree.get_all_trees` method to create a sub-tree for\n",
    "each subject and each session:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.wrappers import bet\n",
    "tree = FileTree.read('mydata.tree', 'mydata')\n",
    "for subtree in tree.get_all_trees('T1w', glob_vars='all'):\n",
    "    t1file  = subtree.get('T1w')\n",
    "    t1brain = subtree.get('T1w_brain')\n",
    "    print('Running BET: {} -> {} ...'.format(t1file, t1brain))\n",
    "    bet(t1file, t1brain, mask=True)\n",
    "print('Done!')\n",
    "\n",
    "example = tree.update(subject='A', session='1')\n",
    "render('{} {} -ot mask -ol -w 2 -mc 0 1 0'.format(\n",
    "    example.get('T1w'),\n",
    "    example.get('T1w_brain_mask')))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"the-filetreequery\"></a>\n",
    "### The `FileTreeQuery`\n",
Paul McCarthy's avatar
Paul McCarthy committed
1219
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1220
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
    "The `filetree` module contains another class called the\n",
    "[`FileTreeQuery`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.query.html),\n",
    "which provides an interface that is more convenient if you are reading data\n",
    "from large datasets with many different file types and variables.\n",
    "\n",
    "\n",
    "When you create a `FileTreeQuery`, it scans the entire data directory and\n",
    "identifies all of the values that are present for each variable defined in the\n",
    "`.tree` file:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.utils.filetree import FileTreeQuery\n",
    "tree = FileTree.read('mydata.tree', 'mydata')\n",
    "query = FileTreeQuery(tree)\n",
    "print('T1w variables:', query.variables('T1w'))\n",
    "print('T2w variables:', query.variables('T2w'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `FileTreeQuery.query` method will return the paths to all existing files\n",
    "which match a set of variable values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('All T1w images for subject A')\n",
    "for template in query.templates:\n",
    "    print('  ', template)\n",
    "    for file in query.query(template, subject='A'):\n",
    "        print(file)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
    "<a class=\"anchor\" id=\"calling-shell-commands\"></a>\n",
    "## Calling shell commands\n",
    "\n",
    "\n",
    "The\n",
    "[`fsl.utils.run`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.run.html)\n",
    "module provides the `run` and `runfsl` functions, which are wrappers around\n",
    "the built-in [`subprocess`\n",
    "library](https://docs.python.org/3/library/subprocess.html).\n",
    "\n",
    "\n",
    "The default behaviour of `run` is to return the standard output of the\n",
    "command:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.utils.run import run\n",
    "\n",
    "# You can pass the command\n",
    "# and its arguments as a single\n",
    "# string, or as a sequence\n",
    "print('Lines in this notebook:', run('wc -l 08_fslpy.md').strip())\n",
    "print('Words in this notebook:', run(['wc', '-w', '08_fslpy.md']).strip())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But you can control what `run` returns, depending on your needs. Let's create\n",
    "a little script to demonstrate the options:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%writefile mycmd\n",
    "#!/usr/bin/env bash\n",
    "exitcode=$1\n",
    "\n",
    "echo \"Standard output!\"\n",
    "echo \"Standard error :(\" >&2\n",
    "\n",
    "exit $exitcode"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And let's not forget to make it executable:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!chmod a+x mycmd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use the `stdout`, `stderr` and `exitcode` arguments to control the\n",
    "return value:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('run(\"./mycmd 0\"):                                          ',\n",
    "       run(\"./mycmd 0\").strip())\n",
    "print('run(\"./mycmd 0\", stdout=False):                            ',\n",
    "       run(\"./mycmd 0\", stdout=False))\n",
    "print('run(\"./mycmd 0\",                            exitcode=True):',\n",
    "       run(\"./mycmd 0\",                            exitcode=True))\n",
    "print('run(\"./mycmd 0\", stdout=False,              exitcode=True):',\n",
    "       run(\"./mycmd 0\", stdout=False,              exitcode=True))\n",
    "print('run(\"./mycmd 0\",               stderr=True):               ',\n",
    "       run(\"./mycmd 0\",               stderr=True))\n",
    "print('run(\"./mycmd 0\", stdout=False, stderr=True):               ',\n",
    "       run(\"./mycmd 0\", stdout=False, stderr=True).strip())\n",
    "print('run(\"./mycmd 0\",               stderr=True, exitcode=True):',\n",
    "       run(\"./mycmd 0\",               stderr=True, exitcode=True))\n",
    "\n",
    "print('run(\"./mycmd 1\",                            exitcode=True):',\n",
    "       run(\"./mycmd 1\",                            exitcode=True))\n",
    "print('run(\"./mycmd 1\", stdout=False,              exitcode=True):',\n",
    "       run(\"./mycmd 1\", stdout=False,              exitcode=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So if only one of `stdout`, `stderr`, or `exitcode` is `True`, `run` will only\n",
    "return the corresponding value. Otherwise `run` will return a tuple which\n",
    "contains the requested outputs.\n",
    "\n",
    "\n",
    "If you run a command which returns a non-0 exit code, the default behaviour\n",
    "(if you don't set `exitcode=True`) is for a `RuntimeError` to be raised:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run(\"./mycmd 99\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1401
1402
    "<a class=\"anchor\" id=\"the-runfsl-function\"></a>\n",
    "### The `runfsl` function\n",
Paul McCarthy's avatar
Paul McCarthy committed
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
    "\n",
    "\n",
    "The `runfsl` function is a wrapper around `run` which simply makes sure that\n",
    "the command you are calling is inside the `$FSLDIR/bin/` directory. It has the\n",
    "same usage as the `run` function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.utils.run import runfsl\n",
Paul McCarthy's avatar
Paul McCarthy committed
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
    "runfsl('bet 08_fslpy/bighead_cropped bighead_cropped_brain')\n",
    "runfsl('fslroi bighead_cropped_brain bighead_slices 0 -1 0 -1 90 3')\n",
    "runfsl('fast -o bighead_fast bighead_slices')\n",
    "\n",
    "render('-vl 80 112 91 -xh -yh '\n",
    "       '08_fslpy/bighead_cropped '\n",
    "       'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '\n",
    "       'bighead_fast_seg.nii.gz -ot label -o')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"submitting-to-the-cluster\"></a>\n",
    "### Submitting to the cluster\n",
    "\n",
    "\n",
    "Both the `run` and `runfsl` accept an argument called `submit`, which allows\n",
    "you to submit jobs to be executed on the cluster via the FSL `fsl_sub`\n",
    "command.\n",
    "\n",
    "\n",
    "> Cluster submission is handled by the\n",
    "> [`fsl.utils.fslsub`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html)\n",
    "> module - it contains lower level functions for managing and querying jobs\n",
    "> that have been submitted to the cluster. The functions defined in this\n",
    "> module can be used directly if you have more complicated requirements.\n",
    "\n",
    "\n",
    "The semantics of the `run` and `runfsl` functions are slightly different when\n",
    "you use the `submit` option - when you submit a job, the `run`/`runfsl` will\n",
    "return immediately, and will return a string containing the job ID:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jobid  = run('ls', submit=True)\n",
    "print('Job ID:', jobid)\n",
    "stdout = f'ls.o{jobid}'\n",
    "print('Job output')\n",
    "print(open(stdout).read())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All of the `fsl.wrappers` functions also accept the `submit` argument:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jobid = bet('08_fslpy/bighead', 'bighead_brain', submit=True)\n",
    "print('Job ID:', jobid)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> But an error will occur if you try to pass in-memory images, or `LOAD` any\n",
    "> outputs when you call a wrapper function with `submit=True`.\n",
    "\n",
    "\n",
    "After submitting a job, you can use the `wait` function to wait until a job\n",
    "has completed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fsl.utils.run import wait\n",
    "jobid = bet('08_fslpy/bighead', 'bighead_brain', submit=True)\n",
    "print('Job ID:', jobid)\n",
    "wait(jobid)\n",
    "print('Done!')\n",
    "render('08_fslpy/bighead bighead_brain -cm hot')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you submit a job, instead of passing `submit=True`, you can pass in a\n",
    "dict which contains cluster submission options - you can include any arguments\n",
    "to the\n",
    "[`fslsub.submit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html#fsl.utils.fslsub.submit)\n",
    "function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "jid = runfsl('robustfov -i 08_fslpy/bighead -r bighead_cropped',    submit=dict(queue='short.q'))\n",
    "jid = runfsl('bet bighead_cropped bighead_brain',                   submit=dict(queue='short.q', wait_for=jid))\n",
    "jid = runfsl('fslroi bighead_brain bighead_slices 0 -1 111 3 0 -1', submit=dict(queue='short.q', wait_for=jid))\n",
    "jid = runfsl('fast -o bighead_fast bighead_slices',                 submit=dict(queue='short.q', wait_for=jid))\n",
    "\n",
    "wait(jid)\n",
    "\n",
    "render('-vl 80 112 91 -xh -zh -hc '\n",
    "       'bighead_brain '\n",
    "       'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '\n",
    "       'bighead_fast_seg.nii.gz -ot label -o')"
Paul McCarthy's avatar
Paul McCarthy committed
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"redirecting-output\"></a>\n",
    "### Redirecting output\n",
    "\n",
    "\n",
    "The `log` option, accepted by both `run` and `fslrun`, allows for more\n",
    "fine-grained control over what is done with the standard output and error\n",
    "streams.\n",
    "\n",
    "\n",
    "You can use `'tee'` to redirect the standard output and error streams of the\n",
    "command to the standard output and error streams of the calling command (your\n",
    "python script):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Teeing:')\n",
    "_ = run('./mycmd 0', log={'tee' : True})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or you can use `'stdout'` and `'stderr'` to redirect the standard output and\n",
    "error streams of the command to files:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('stdout.log', 'wt') as o, \\\n",
    "     open('stderr.log', 'wt') as e:\n",
    "     run('./mycmd 0', log={'stdout' : o, 'stderr' : e})\n",
    "print('\\nRedirected stdout:')\n",
    "!cat stdout.log\n",
    "print('\\nRedirected stderr:')\n",
    "!cat stderr.log"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, you can use `'cmd'` to log the command itself to a file (useful for\n",
    "pipeline logging):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('commands.log', 'wt') as cmdlog:\n",
    "     run('./mycmd 0',         log={'cmd' : cmdlog})\n",
    "     run('wc -l 08_fslpy.md', log={'cmd' : cmdlog})\n",
    "\n",
    "print('\\nCommand log:')\n",
    "!cat commands.log"
   ]
  },
Paul McCarthy's avatar
Paul McCarthy committed
1611
1612
1613
1614
1615
1616
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"fsl-atlases\"></a>\n",
    "## FSL atlases\n",
Paul McCarthy's avatar
Paul McCarthy committed
1617
1618
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1619
1620
1621
1622
1623
    "The\n",
    "[`fsl.data.atlases`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.atlases.html)\n",
    "module provides access to all of the atlas images that are stored in the\n",
    "`$FSLDIR/data/atlases/` directory of a standard FSL installation. It can be\n",
    "used to load and query probabilistic and label-based atlases.\n",
Paul McCarthy's avatar
Paul McCarthy committed
1624
1625
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1626
    "The `atlases` module needs to be initialised using the `rescanAtlases` function:"
Paul McCarthy's avatar
Paul McCarthy committed
1627
1628
1629
1630
1631
1632
1633
1634
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
    "import fsl.data.atlases as atlases\n",
    "atlases.rescanAtlases()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a class=\"anchor\" id=\"querying-atlases\"></a>\n",
    "### Querying atlases\n",
Paul McCarthy's avatar
Paul McCarthy committed
1645
1646
    "\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
    "You can list all of the available atlases using `listAtlases`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for desc in atlases.listAtlases():\n",
    "    print(desc)"
Paul McCarthy's avatar
Paul McCarthy committed
1658
1659
1660
1661
1662
1663
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1664
1665
1666
1667
    "`listAtlases` returns a list of `AtlasDescription` objects, each of which\n",
    "contains descriptive information about one atlas. You can retrieve the\n",
    "`AtlasDescription` for a specific atlas via the `getAtlasDescription`\n",
    "function:"
Paul McCarthy's avatar
Paul McCarthy committed
1668
1669
1670
1671
1672
1673
1674
1675
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1676
1677
1678
1679
1680
    "desc = atlases.getAtlasDescription('harvardoxford-cortical')\n",
    "print(desc.name)\n",
    "print(desc.atlasID)\n",
    "print(desc.specPath)\n",
    "print(desc.atlasType)"
Paul McCarthy's avatar
Paul McCarthy committed
1681
1682
1683
1684
1685
1686
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1687
1688
1689
    "Each `AtlasDescription` maintains a list of `AtlasLabel` objects, each of\n",
    "which represents one region that is defined in the atlas. You can access all\n",
    "of the `AtlasLabel` objects via the `labels` attribute:"
Paul McCarthy's avatar
Paul McCarthy committed
1690
1691
1692
1693
1694
1695
1696
1697
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1698
1699
    "for lbl in desc.labels[:5]:\n",
    "    print(lbl)"
Paul McCarthy's avatar
Paul McCarthy committed
1700
1701
1702
1703
1704
1705
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1706
    "Or you can retrieve a specific label using the `find` method:"
Paul McCarthy's avatar
Paul McCarthy committed
1707
1708
1709
1710
1711
1712
1713
1714
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1715
1716
1717
1718
1719
    "# search by region name\n",
    "print(desc.find(name='Occipital Pole'))\n",
    "\n",
    "# or by label value\n",
    "print(desc.find(value=48))"
Paul McCarthy's avatar
Paul McCarthy committed
1720
1721
1722
1723
1724
1725
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1726
1727
1728
1729
1730
    "<a class=\"anchor\" id=\"loading-atlas-images\"></a>\n",
    "### Loading atlas images\n",
    "\n",
    "\n",
    "The `loadAtlas` function can be used to load the atlas image:"
Paul McCarthy's avatar
Paul McCarthy committed
1731
1732
1733
1734
1735
1736
1737
1738
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
    "# For probabilistic atlases, you\n",
    "# can ask for the 3D ROI image\n",
    "# by setting loadSummary=True.\n",
    "# You can also request a\n",
    "# resolution - by default the\n",
    "# highest resolution version\n",
    "# will be loaded.\n",
    "lblatlas = atlases.loadAtlas('harvardoxford-cortical',\n",
    "                             loadSummary=True,\n",
    "                             resolution=2)\n",
Paul McCarthy's avatar
Paul McCarthy committed
1749
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1750
1751
1752
1753
1754
1755
1756
1757
1758
    "# By default you will get the 4D\n",
    "# probabilistic atlas image (for\n",
    "# atlases for which this is\n",
    "# available).\n",
    "probatlas = atlases.loadAtlas('harvardoxford-cortical',\n",
    "                              resolution=2)\n",
    "\n",
    "print(lblatlas)\n",
    "print(probatlas)"
Paul McCarthy's avatar
Paul McCarthy committed
1759
1760
1761
1762
1763
1764
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1765
1766
1767
1768
1769
1770
    "<a class=\"anchor\" id=\"working-with-atlases\"></a>\n",
    "### Working with atlases\n",
    "\n",
    "\n",
    "Both `LabelAtlas` and `ProbabilisticAtlas` objects have a method called `get`,\n",
    "which can be used to extract ROI images for a specific region:"
Paul McCarthy's avatar
Paul McCarthy committed
1771
1772
1773
1774
1775
1776
1777
1778
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1779
1780
1781
1782
1783
1784
    "stddir = op.expandvars('${FSLDIR}/data/standard/')\n",
    "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n",
    "\n",
    "frontal = lblatlas.get(name='Frontal Pole').data\n",
    "frontal = np.ma.masked_where(frontal < 1, frontal)\n",
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1785
1786
    "fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)\n",
    "fig = ortho(frontal,     (45, 54, 45), cmap=plt.cm.winter, fig=fig)"
Paul McCarthy's avatar
Paul McCarthy committed
1787
1788
1789
1790
1791
1792
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
    "Calling `get` on a :meth:`ProbabilisticAtlas` will return a probability image:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "stddir = op.expandvars('${FSLDIR}/data/standard/')\n",
    "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n",
Paul McCarthy's avatar
Paul McCarthy committed
1804
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1805
1806
    "frontal = probatlas.get(name='Frontal Pole')\n",
    "frontal = np.ma.masked_where(frontal < 1, frontal)\n",
Paul McCarthy's avatar
Paul McCarthy committed
1807
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1808
1809
    "fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)\n",
    "fig = ortho(frontal,     (45, 54, 45), cmap=plt.cm.inferno, fig=fig)"
Paul McCarthy's avatar
Paul McCarthy committed
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `get` method can be used to retrieve an image for a region by:\n",
    "- an `AtlasLabel` object\n",
    "- The region index\n",
    "- The region value\n",
    "- The region name\n",
Paul McCarthy's avatar
Paul McCarthy committed
1821
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1822
1823
1824
    "\n",
    "`LabelAtlas` objects have a method called `label`, which can be used to\n",
    "interrogate the atlas at specific locations:"
Paul McCarthy's avatar
Paul McCarthy committed
1825
1826
1827
1828
1829
1830
1831
1832
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
    "# The label method accepts 3D\n",
    "# voxel or world coordinates\n",
    "val = lblatlas.label((25, 52, 43), voxel=True)\n",
    "lbl = lblatlas.find(value=val)\n",
    "print('Region at voxel [25, 52, 43]: {} [{}]'.format(val, lbl.name))\n",
    "\n",
    "\n",
    "# or a 3D weighted or binary mask\n",
    "mask = np.zeros(lblatlas.shape)\n",
    "mask[30:60, 30:60, 30:60] = 1\n",
    "mask = Image(mask, header=lblatlas.header)\n",
    "\n",
    "lbls, props = lblatlas.label(mask)\n",
    "print('Labels in mask:')\n",
    "for lbl, prop in zip(lbls, props):\n",
    "    lblname = lblatlas.find(value=lbl).name\n",
    "    print('  {} [{}]: {:0.2f}%'.format(lbl, lblname, prop))"
Paul McCarthy's avatar
Paul McCarthy committed
1850
1851
1852
1853
1854
1855
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Paul McCarthy's avatar
Paul McCarthy committed
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
    "`ProbabilisticAtlas` objects have an analogous method called `values`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vals = probatlas.values((25, 52, 43), voxel=True)\n",
    "print('Regions at voxel [25, 52, 43]:')\n",
    "for idx, val in enumerate(vals):\n",
    "    if val > 0:\n",
    "        lbl = probatlas.find(index=idx)\n",
    "        print('  {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val))\n",
Paul McCarthy's avatar
Paul McCarthy committed
1871
    "\n",
Paul McCarthy's avatar
Paul McCarthy committed
1872
1873
1874
1875
1876
1877
    "print('Average proportions of regions within mask:')\n",
    "vals = probatlas.values(mask)\n",
    "for idx, val in enumerate(vals):\n",
    "    if val > 0:\n",
    "        lbl = probatlas.find(index=idx)\n",
    "        print('  {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val))"
Paul McCarthy's avatar
Paul McCarthy committed
1878
1879
1880
1881
1882
1883
1884
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}