08_fslpy.md 46.5 KB
Newer Older
1
2
# `fslpy`

3

Paul McCarthy's avatar
Paul McCarthy committed
4
5
6
7
**Important:** Portions of this practical require `fslpy` 2.9.0, due to be
released with FSL 6.0.4, in Spring 2020.


Paul McCarthy's avatar
Paul McCarthy committed
8
9
[`fslpy`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/) is a
Python library which is built into FSL, and contains a range of functionality
Paul McCarthy's avatar
Paul McCarthy committed
10
for working with FSL and with neuroimaging data from Python.
11

12
13
14
15
16
17
18

This practical highlights some of the most useful features provided by
`fslpy`. You may find `fslpy` useful if you are writing Python code to
perform analyses and image processing in conjunction with FSL.


* [The `Image` class, and other data types](#the-image-class-and-other-data-types)
Paul McCarthy's avatar
Paul McCarthy committed
19
20
21
  * [Creating images](#creating-images)
  * [Working with image data](#working-with-image-data)
  * [Loading other file types](#loading-other-file-types)
Paul McCarthy's avatar
Paul McCarthy committed
22
  * [NIfTI coordinate systems](#nifti-coordinate-systems)
23
  * [Transformations and resampling](#transformations-and-resampling)
24
* [FSL wrapper functions](#fsl-wrapper-functions)
Paul McCarthy's avatar
Paul McCarthy committed
25
26
27
  * [In-memory images](#in-memory-images)
  * [Loading outputs into Python](#loading-outputs-into-python)
  * [The `fslmaths` wrapper](#the-fslmaths-wrapper)
Paul McCarthy's avatar
Paul McCarthy committed
28
29
30
31
32
* [The `FileTree`](#the-filetree)
  * [Describing your data](#describing-your-data)
  * [Using the `FileTree`](#using-the-filetree)
  * [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree)
  * [The `FileTreeQuery`](#the-filetreequery)
Paul McCarthy's avatar
Paul McCarthy committed
33
* [Calling shell commands](#calling-shell-commands)
Paul McCarthy's avatar
Paul McCarthy committed
34
35
  * [The `runfsl` function](#the-runfsl-function)
  * [Submitting to the cluster](#submitting-to-the-cluster)
Paul McCarthy's avatar
Paul McCarthy committed
36
  * [Redirecting output](#redirecting-output)
Paul McCarthy's avatar
Paul McCarthy committed
37
38
39
40
41
42
* [FSL atlases](#fsl-atlases)
  * [Querying atlases](#querying-atlases)
  * [Loading atlas images](#loading-atlas-images)
  * [Working with atlases](#working-with-atlases)


Paul McCarthy's avatar
Paul McCarthy committed
43
44
45
46
47
> **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python
> environment that is baked into FSL. `fslpy` is a Python library which is
> installed into the `fslpython` environment.


Paul McCarthy's avatar
Paul McCarthy committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Let's start with some standard imports and environment set-up:


```
%matplotlib inline
import matplotlib.pyplot as plt
import os
import os.path as op
import nibabel as nib
import numpy as np
import warnings
warnings.filterwarnings("ignore")
```


And a little function that we can use to generate a simple orthographic plot:


```
Paul McCarthy's avatar
Paul McCarthy committed
67
def ortho(data, voxel, fig=None, cursor=False, **kwargs):
Paul McCarthy's avatar
Paul McCarthy committed
68
69
    """Simple orthographic plot of a 3D array using matplotlib.

Paul McCarthy's avatar
Paul McCarthy committed
70
71
72
73
    :arg data:   3D numpy array
    :arg voxel:  XYZ coordinates for each slice
    :arg fig:    Existing figure and axes for overlay plotting
    :arg cursor: Show a cursor at the `voxel`
Paul McCarthy's avatar
Paul McCarthy committed
74
75
76

    All other arguments are passed through to the `imshow` function.

Paul McCarthy's avatar
Paul McCarthy committed
77
    :returns:   The figure and orthogaxes (which can be passed back in as the
Paul McCarthy's avatar
Paul McCarthy committed
78
79
                `fig` argument to plot overlays).
    """
Paul McCarthy's avatar
Paul McCarthy committed
80

81
82
    voxel = [int(round(v)) for v in voxel]

Paul McCarthy's avatar
Paul McCarthy committed
83
84
85
    data            = np.asanyarray(data, dtype=np.float)
    data[data <= 0] = np.nan

Paul McCarthy's avatar
Paul McCarthy committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    x, y, z = voxel
    xslice  = np.flipud(data[x, :, :].T)
    yslice  = np.flipud(data[:, y, :].T)
    zslice  = np.flipud(data[:, :, z].T)

    if fig is None:
        fig = plt.figure()
        xax = fig.add_subplot(1, 3, 1)
        yax = fig.add_subplot(1, 3, 2)
        zax = fig.add_subplot(1, 3, 3)
    else:
        fig, xax, yax, zax = fig

    xax.imshow(xslice, **kwargs)
    yax.imshow(yslice, **kwargs)
    zax.imshow(zslice, **kwargs)

Paul McCarthy's avatar
Paul McCarthy committed
103
104
105
106
107
108
109
110
111
    if cursor:
        cargs = {'color' : (0, 1, 0), 'linewidth' : 1}
        xax.axvline(                y, **cargs)
        xax.axhline(data.shape[2] - z, **cargs)
        yax.axvline(                x, **cargs)
        yax.axhline(data.shape[2] - z, **cargs)
        zax.axvline(                x, **cargs)
        zax.axhline(data.shape[1] - y, **cargs)

Paul McCarthy's avatar
Paul McCarthy committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    for ax in (xax, yax, zax):
        ax.set_xticks([])
        ax.set_yticks([])
    fig.tight_layout(pad=0)

    return (fig, xax, yax, zax)
```


And another function which uses FSLeyes for more complex plots:


```
def render(cmdline):
126
127
128
129

    import shlex
    import IPython.display as display

Paul McCarthy's avatar
Paul McCarthy committed
130
    prefix = '-of screenshot.png -hl -c 2 '
131
132
133
134
135
136
137
138
139
140
141
142

    try:
        from fsleyes.render import main
        main(shlex.split(prefix + cmdline))

    except ImportError:
        # fall-back for macOS - we have to run
        # FSLeyes render in a separate process
        from fsl.utils.run import runfsl
        prefix = 'render ' + prefix
        runfsl(prefix + cmdline, env={})

Paul McCarthy's avatar
Paul McCarthy committed
143
144
    return display.Image('screenshot.png')
```
145
146
147
148
149
150


<a class="anchor" id="the-image-class-and-other-data-types"></a>
## The `Image` class, and other data types


Paul McCarthy's avatar
Paul McCarthy committed
151
152
153
154
155
156
The
[`fsl.data.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)
module provides the `Image` class, which sits on top of `nibabel` and contains
some handy functionality if you need to work with coordinate transformations,
or do some FSL-specific processing. The `Image` class provides features such
as:
157
158
159
160
161
162

- Support for NIFTI1, NIFTI2, and ANALYZE image files
- Access to affine transformations between the voxel, FSL and world coordinate
  systems
- Ability to load metadata from BIDS sidecar files

Paul McCarthy's avatar
Paul McCarthy committed
163

164
165
166
167
168
169
170
171
> The `Image` class behaves differently to the `nibabel.Nifti1Image`. For
> example, when you create an `Image` object, the default behaviour is to load
> the image data into memory. This is configurable however; take a look at
> [the
> documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)
> to explore all of the options.


172
173
174
175
Some simple image processing routines are also provided - these are covered
[below](#image-processing).


Paul McCarthy's avatar
Paul McCarthy committed
176
<a class="anchor" id="creating-images"></a>
177
178
### Creating images

Paul McCarthy's avatar
Paul McCarthy committed
179

180
181
It's easy to create an `Image` - you can create one from a file name:

Paul McCarthy's avatar
Paul McCarthy committed
182

183
184
```
from fsl.data.image import Image
Paul McCarthy's avatar
Paul McCarthy committed
185

186
187
188
189
190
stddir = op.expandvars('${FSLDIR}/data/standard/')

# load a FSL image - the file
# suffix is optional, just like
# in real FSL-land!
Paul McCarthy's avatar
Paul McCarthy committed
191
192
std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))
print(std1mm)
193
194
```

Paul McCarthy's avatar
Paul McCarthy committed
195
196
197

You can create an `Image` from an existing `nibabel` image:

198
199
200
201
202

```
# load a nibabel image, and
# convert it into an FSL image
nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz'))
Paul McCarthy's avatar
Paul McCarthy committed
203
std1mm = Image(nibimg)
Paul McCarthy's avatar
Paul McCarthy committed
204
205
```

206
207
208

Or you can create an `Image` from a `numpy` array:

Paul McCarthy's avatar
Paul McCarthy committed
209

210
```
Paul McCarthy's avatar
Paul McCarthy committed
211
data = np.zeros((182, 218, 182))
212
213
214
img = Image(data, xform=np.eye(4))
```

Paul McCarthy's avatar
Paul McCarthy committed
215
216
217
218
219
220
221
222
223
224
If you have generated some data from another `Image` (or from a
`nibabel.Nifti1Image`) you can use the `header` option to set
the header information on the new image:


```
img = Image(data, header=std1mm.header)
```


Paul McCarthy's avatar
Paul McCarthy committed
225
226
227
228
You can save an image to file via the `save` method:


```
Paul McCarthy's avatar
Paul McCarthy committed
229
230
img.save('empty')
!ls
Paul McCarthy's avatar
Paul McCarthy committed
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
```


`Image` objects have all of the attributes you might expect:


```
stddir = op.expandvars('${FSLDIR}/data/standard/')
std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))

print('name:         ', std1mm.name)
print('file:         ', std1mm.dataSource)
print('NIfTI version:', std1mm.niftiVersion)
print('ndim:         ', std1mm.ndim)
print('shape:        ', std1mm.shape)
print('dtype:        ', std1mm.dtype)
print('nvals:        ', std1mm.nvals)
print('pixdim:       ', std1mm.pixdim)
```


and a number of useful methods:


```
std2mm  = Image(op.join(stddir, 'MNI152_T1_2mm'))
Paul McCarthy's avatar
Paul McCarthy committed
257
mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask'))
Paul McCarthy's avatar
Paul McCarthy committed
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

print(std1mm.sameSpace(std2mm))
print(std2mm.sameSpace(mask2mm))
print(std2mm.getAffine('voxel', 'world'))
```


An `Image` object is a high-level wrapper around a `nibabel` image object -
you can always work directly with the `nibabel` object via the `nibImage`
attribute:


```
print(std2mm)
print(std2mm.nibImage)
```


<a class="anchor" id="working-with-image-data"></a>
### Working with image data


You can get the image data as a `numpy` array via the `data` attribute:


```
data = std2mm.data
Paul McCarthy's avatar
Paul McCarthy committed
285
print(data.min(), data.max())
Paul McCarthy's avatar
Paul McCarthy committed
286
ortho(data, (45, 54, 45))
Paul McCarthy's avatar
Paul McCarthy committed
287
288
```

Paul McCarthy's avatar
Paul McCarthy committed
289
290
291

> Note that `Image.data` will give you the data in its underlying type, unlike
> the `nibabel.get_fdata` method, which up-casts image data to floating-point.
Paul McCarthy's avatar
Paul McCarthy committed
292
293
294
295
296
297
298


You can also read and write data directly via the `Image` object:


```
slc = std2mm[:, :, 45]
Paul McCarthy's avatar
Paul McCarthy committed
299
std2mm[0:10, :, :] *= 2
Paul McCarthy's avatar
Paul McCarthy committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
```


Doing so has some advantages that may or may not be useful, depending on your
use-case:
 - The image data will be kept on disk - only the parts that you access will
   be loaded into RAM (you will also need to pass`loadData=False` when creating
   the `Image` to achieve this).
 - The `Image` object will keep track of modifications to the data - this can
   be queried via the `saveState` attribute.


<a class="anchor" id="loading-other-file-types"></a>
### Loading other file types


The
[`fsl.data`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.html#module-fsl.data)
package has a number of other classes for working with different types of FSL
and neuroimaging data. Most of these are higher-level wrappers around the
corresponding `nibabel` types:
321

Paul McCarthy's avatar
Paul McCarthy committed
322
323
324
325
326
327
328
329
330
* The
  [`fsl.data.bitmap.Bitmap`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.bitmap.html)
  class can be used to load a bitmap image (e.g. `jpg, `png`, etc) and
  convert it to a NIfTI image.
* The
  [`fsl.data.dicom.DicomImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dicom.html)
  class uses `dcm2niix` to load NIfTI images contained within a DICOM
  directory<sup>*</sup>.
* The
331
  [`fsl.data.mghimage.MGHImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.mghimage.html)
Paul McCarthy's avatar
Paul McCarthy committed
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
  class can be used too load `.mgh`/`.mgz` images (they are converted into
  NIfTI images).
* The
  [`fsl.data.dtifit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dtifit.html)
  module contains functions for loading and working with the output of the
  FSL `dtifit` tool.
* The
  [`fsl.data.featanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featanalysis.html),
  [`fsl.data.featimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featimage.html),
  and
  [`fsl.data.featdesign`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featdesign.html)
  modules contain classes and functions for loading data from FEAT
  directories.
* Similarly, the
  [`fsl.data.melodicanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicanalysis.html)
  and
  [`fsl.data.melodicimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicimage.html)
  modules contain classes and functions for loading data from MELODIC
  directories.
* The
  [`fsl.data.gifti`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.gifti.html),
  [`fsl.data.freesurfer`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.freesurfer.html),
  and
  [`fsl.data.vtk`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.vtk.html)
  modules contain functionality form loading surface data from GIfTI,
357
  freesurfer, and ASCII VTK files respectively.
358
359


360
361
362
> <sup>*</sup>You must make sure that
> [`dcm2niix`](https://github.com/rordenlab/dcm2niix/) is installed on your
> system in order to use this class.
Paul McCarthy's avatar
Paul McCarthy committed
363

364

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
<a class="anchor" id="nifti-coordinate-systems"></a>
### NIfTI coordinate systems


The `Image.getAffine` method gives you access to affine transformations which
can be used to convert coordinates between the different coordinate systems
associated with a NIfTI image. Have some MNI coordinates you'd like to convert
to voxels? Easy!


```
stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))

mnicoords = np.array([[0,   0,  0],
                      [0, -18, 18]])

world2vox = std2mm.getAffine('world', 'voxel')
vox2world = std2mm.getAffine('voxel', 'world')

# Apply the world->voxel
# affine to the coordinates
voxcoords = (np.dot(world2vox[:3, :3], mnicoords.T)).T + world2vox[:3, 3]
388
389
```

Paul McCarthy's avatar
Paul McCarthy committed
390

391
392
393
394
395
396
397
The code above is a bit fiddly, so instead of figuring it out, you can just
use the
[`affine.transform`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.affine.html#fsl.transform.affine.transform)
function:


```
Paul McCarthy's avatar
Paul McCarthy committed
398
from fsl.transform.affine import transform
399

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
425
426
427
428
429
430
431
432
433
voxcoords = transform(mnicoords, world2vox)

# just to double check, let's transform
# those voxel coordinates back into world
# coordinates
backtomni = transform(voxcoords, vox2world)

for m, v, b in zip(mnicoords, voxcoords, backtomni):
    print(m, '->', v, '->', b)
```


> The `Image.getAffine` method can give you transformation matrices
> between any of these coordinate systems:
>
>  - `'voxel'`: Image data voxel coordinates
>  - `'world'`: mm coordinates, defined by the sform/qform of an image
>  - `'fsl'`: The FSL coordinate system, used internally by many FSL tools
>    (e.g. FLIRT)


Oh, that example was too easy I hear you say? Try this one on for size. Let's
say we have run FEAT on some task fMRI data, and want to get the MNI
coordinates of the voxel with peak activation.


> This is what people used to use `Featquery` for, back in the un-enlightened
> days.


Let's start by identifying the voxel with the biggest t-statistic:


```
Paul McCarthy's avatar
Paul McCarthy committed
434
featdir = op.join('08_fslpy', 'fmri.feat')
Paul McCarthy's avatar
Paul McCarthy committed
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
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
500

tstat1 = Image(op.join(featdir, 'stats', 'tstat1')).data

# Recall from the numpy practical that
# argmax gives us a 1D index into a
# flattened view of the array. We can
# use the unravel_index function to
# convert it into a 3D index.
peakvox = np.abs(tstat1).argmax()
peakvox = np.unravel_index(peakvox, tstat1.shape)
print('Peak voxel coordinates for tstat1:', peakvox, tstat1[peakvox])
```


Now that we've got the voxel coordinates in functional space, we need to
transform them into MNI space. FEAT provides a transformation which goes
directly from functional to standard space, in the `reg` directory:


```
func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))
```


But ... wait a minute ... this is a FLIRT matrix! We can't just plug voxel
coordinates into a FLIRT matrix and expect to get sensible results, because
FLIRT works in an internal FSL coordinate system, which is not quite
`'voxel'`, and not quite `'world'`. So we need to do a little more work.
Let's start by loading our functional image, and the MNI152 template (the
source and reference images of our FLIRT matrix):


```
func = Image(op.join(featdir, 'reg', 'example_func'))
std  = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
```


Now we can use them to get affines which convert between all of the different
coordinate systems - we're going to combine them into a single uber-affine,
which transforms our functional-space voxels into MNI world coordinates via:

   1. functional voxels -> FLIRT source space
   2. FLIRT source space -> FLIRT reference space
   3. FLIRT referece space -> MNI world coordinates


```
vox2fsl = func.getAffine('voxel', 'fsl')
fsl2mni = std .getAffine('fsl',   'world')
```


Combining two affines into one is just a simple dot-product. There is a
`concat()` function which does this for us, for any number of affines:


```
from fsl.transform.affine import concat

# To combine affines together, we
# have to list them in reverse -
# linear algebra is *weird*.
funcvox2mni = concat(fsl2mni, func2std, vox2fsl)
```

501
> In the next section we will use the
502
503
504
> [`fsl.transform.flirt.fromFlirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html#fsl.transform.flirt.fromFlirt)
> function, which does all of the above for us.

Paul McCarthy's avatar
Paul McCarthy committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518

So we've now got some voxel coordinates from our functional data, and an
affine to transform into MNI world coordinates. The rest is easy:


```
mnicoords = transform(peakvox, funcvox2mni)
mnivoxels = transform(mnicoords, std.getAffine('world', 'voxel'))
mnivoxels = [int(round(v)) for v in mnivoxels]
print('Peak activation (MNI coordinates):', mnicoords)
print('Peak activation (MNI voxels):     ', mnivoxels)
```


519
520
521
522
Note that in the above example we are only applying a linear transformation
into MNI space - in reality you would also want to apply your non-linear
structural-to-standard transformation too. This is covered in the next
section.
Paul McCarthy's avatar
Paul McCarthy committed
523
524


525
526
<a class="anchor" id="transformations-and-resampling"></a>
### Transformations and resampling
Paul McCarthy's avatar
Paul McCarthy committed
527
528
529
530
531
532
533
534


Now, it's all well and good to look at t-statistic values and voxel
coordinates and so on and so forth, but let's spice things up a bit and look
at some images. Let's display our peak activation location in MNI space. To do
this, we're going to resample our functional image into MNI space, so we can
overlay it on the MNI template. This can be done using some handy functions
from the
535
536
[`fsl.transform.flirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html)
and
Paul McCarthy's avatar
Paul McCarthy committed
537
[`fsl.utils.image.resample`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.resample.html)
538
modules.
Paul McCarthy's avatar
Paul McCarthy committed
539
540


541
542
Let's make sure we've got our source and reference images loaded:

Paul McCarthy's avatar
Paul McCarthy committed
543

544
```
Paul McCarthy's avatar
Paul McCarthy committed
545
546
547
featdir = op.join(op.join('08_fslpy', 'fmri.feat'))
tstat1  = Image(op.join(featdir, 'stats', 'tstat1'))
std     = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
548
549
550
551
552
553
554
555
556
557
558
```


Now we'll load the `example_func2standard` FLIRT matrix, and adjust it so that
it transforms from functional *world* coordinates into standard *world*
coordinates - this is what is expected by the `resampleToReference` function,
used below:


```
from fsl.transform.flirt import fromFlirt
Paul McCarthy's avatar
Paul McCarthy committed
559
560
561

func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))
func2std = fromFlirt(func2std, tstat1, std, 'world', 'world')
562
563
564
565
566
567
568
569
570
571
```


Now we can use `resampleToReference` to resample our functional data into
MNI152 space. This function returns a `numpy` array containing the resampled
data, and an adjusted voxel-to-world affine transformation. But in this case,
we know that the data will be aligned to MNI152, so we can ignore the affine:

```
from fsl.utils.image.resample import resampleToReference
Paul McCarthy's avatar
Paul McCarthy committed
572
573
574
575
576
577
578
579
580
581
582
583
584
585

std_tstat1 = resampleToReference(tstat1, std, func2std)[0]
std_tstat1 = Image(std_tstat1, header=std.header)
```


Now that we have our t-statistic image in MNI152 space, we can plot it in
standard space using `matplotlib`:


```
stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))

Paul McCarthy's avatar
Paul McCarthy committed
586
587
std_tstat1                 = std_tstat1.data
std_tstat1[std_tstat1 < 3] = 0
Paul McCarthy's avatar
Paul McCarthy committed
588

Paul McCarthy's avatar
Paul McCarthy committed
589
fig = ortho(std2mm.data, mnivoxels, cmap=plt.cm.gray)
Paul McCarthy's avatar
Paul McCarthy committed
590
fig = ortho(std_tstat1,  mnivoxels, cmap=plt.cm.inferno, fig=fig, cursor=True)
Paul McCarthy's avatar
Paul McCarthy committed
591
592
593
```


594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
In the example above, we resampled some data from functional space into
standard space using a linear transformation. But we all know that this is not
how things work in the real world - linear transformations are for kids. The
real world is full of lions and tigers and bears and warp fields.


The
[`fsl.transform.fnirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.fnirt.html#fsl.transform.fnirt.fromFnirt)
and
[`fsl.transform.nonlinear`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.nonlinear.html)
modules contain classes and functions for working with FNIRT-style warp fields
(modules for working with lions, tigers, and bears are still under
development).


Let's imagine that we have defined an ROI in MNI152 space, and we want to
project it into the space of our functional data.  We can do this by combining
the nonlinear structural to standard registration produced by FNIRT with the
linear functional to structural registration generated by FLIRT.  First of
all, we'll load images from each of the functional, structural, and standard
spaces:


```
featdir = op.join('08_fslpy', 'fmri.feat')
func    = Image(op.join(featdir, 'reg', 'example_func'))
struc   = Image(op.join(featdir, 'reg', 'highres'))
std     = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
```


Now, let's say we have obtained our seed location in MNI152 coordinates. Let's
convert them to MNI152 voxels just to double check:


```
seedmni    = [-48, -74, -9]
seedmnivox = transform(seedmni, std.getAffine('world', 'voxel'))
ortho(std.data, seedmnivox, cursor=True)
```


Now we'll load the FNIRT warp field, which encodes a nonlinear transformation
from structural space to standard space. FNIRT warp fields are often stored as
*coefficient* fields to reduce the file size, but in order to use it, we must
convert the coefficient field into a *deformation* (a.k.a. *displacement*)
field. This takes a few seconds:


```
from fsl.transform.fnirt     import readFnirt
from fsl.transform.nonlinear import coefficientFieldToDeformationField

struc2std = readFnirt(op.join(featdir, 'reg', 'highres2standard_warp'), struc, std)
struc2std = coefficientFieldToDeformationField(struc2std)
```

We'll also load our FLIRT functional to structural transformation, adjust it
so that it transforms between voxel coordinate systems instead of the FSL
coordinate system, and invert so it can transform from structural voxels to
functional voxels:


```
from fsl.transform.affine import invert
func2struc = np.loadtxt(op.join(featdir, 'reg', 'example_func2highres.mat'))
func2struc = fromFlirt(func2struc, func, struc, 'voxel', 'voxel')
struc2func = invert(func2struc)
```


Now we can transform our seed coordinates from MNI152 space into functional
space in two stages. First, we'll use our deformation field to transform from
MNI152 space into structural space:


```
seedstruc = struc2std.transform([seedmni], 'world', 'voxel')[0]
seedfunc  = transform(seedstruc, struc2func)

print('Seed location in MNI coordinates:  ', seedmni)
print('Seed location in functional voxels:', seedfunc)
ortho(func.data, seedfunc, cursor=True)
```


> FNIRT warp fields kind of work backwards - we can use them to transform
> reference coordinates into source coordinates, but would need to invert the
> warp field using `invwarp` if we wanted to transform from source coordinates
> into referemce coordinates.


Of course, we can also use our deformation field to resample an image from
structural space into MNI152 space. The `applyDeformation` function takes an
`Image` and a `DeformationField`, and returns a `numpy` array containing the
resampled data.


```
from fsl.transform.nonlinear import applyDeformation

strucmni = applyDeformation(struc, struc2std)

# remove low-valued voxels,
# just for visualisation below
strucmni[strucmni < 1] = 0

fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray)
fig = ortho(strucmni, [45, 54, 45], fig=fig)
```


The `premat` option to `applyDeformation` can be used to specify our linear
functional to structural transformation, and hence resample a functional image
into MNI152 space:


```
tstatmni = applyDeformation(tstat1, struc2std, premat=func2struc)
tstatmni[tstatmni < 3] = 0

fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray)
fig = ortho(tstatmni, [45, 54, 45], fig=fig)
```


Paul McCarthy's avatar
Paul McCarthy committed
720
There are a few other useful functions tucked away in the
721
722
723
724
[`fsl.utils.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.html)
and
[`fsl.transform`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.html)
packages, with more to be added in the future.
Paul McCarthy's avatar
Paul McCarthy committed
725
726
727
728
729
730
731
732
733
734
735
736
737


<a class="anchor" id="fsl-wrapper-functions"></a>
## FSL wrapper functions


The
[fsl.wrappers](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.wrappers.html)
package is the home of "wrapper" functions for a range of FSL tools. You can
use them to call an FSL tool from Python code, without having to worry about
constructing a command-line, or saving/loading input/output images.


Paul McCarthy's avatar
Paul McCarthy committed
738
739
740
741
> The `fsl.wrappers` functions also allow you to submit jobs to be run on the
> cluster - this is described [below](#submitting-to-the-cluster).


Paul McCarthy's avatar
Paul McCarthy committed
742
743
744
You can use the FSL wrapper functions with file names, similar to calling the
corresponding tool via the command-line:

Paul McCarthy's avatar
Paul McCarthy committed
745
746
747

```
from fsl.wrappers import bet, robustfov, LOAD
Paul McCarthy's avatar
Paul McCarthy committed
748
749
750
751
752
753
754

robustfov('08_fslpy/bighead', 'bighead_cropped')

render('08_fslpy/bighead bighead_cropped -cm blue')
```


Paul McCarthy's avatar
Paul McCarthy committed
755
The `fsl.wrappers` functions strive to provide an interface which is as close
Paul McCarthy's avatar
Paul McCarthy committed
756
757
758
759
760
761
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
as possible to the command-line tool - most functions use positional arguments
for required options, and keyword arguments for all other options, with
argument names equivalent to command line option names. For example, the usage
for the command-line `bet` tool is as follows:


> ```
> Usage:    bet <input> <output> [options]
>
> Main bet2 options:
>   -o          generate brain surface outline overlaid onto original image
>   -m          generate binary brain mask
>   -s          generate approximate skull image
>   -n          don't generate segmented brain image output
>   -f <f>      fractional intensity threshold (0->1); default=0.5; smaller values give larger brain outline estimates
>   -g <g>      vertical gradient in fractional intensity threshold (-1->1); default=0; positive values give larger brain outline at bottom, smaller at top
>   -r <r>      head radius (mm not voxels); initial surface sphere is set to half of this
>   -c <x y z>  centre-of-gravity (voxels not mm) of initial mesh surface.
> ...
> ```


So to use the `bet()` wrapper function, pass `<input>` and `<output>` as
positional arguments, and pass the additional options as keyword arguments:


```
bet('bighead_cropped', 'bighead_cropped_brain', f=0.3, m=True, s=True)

render('bighead_cropped             -b 40 '
       'bighead_cropped_brain       -cm hot '
       'bighead_cropped_brain_skull -ot mask -mc 0.4 0.4 1 '
       'bighead_cropped_brain_mask  -ot mask -mc 0   1   0 -o -w 5')
Paul McCarthy's avatar
Paul McCarthy committed
789
790
```

Paul McCarthy's avatar
Paul McCarthy committed
791
792
793
794
795
796
797
798
799
800

> Some FSL commands accept arguments which cannot be used as Python
> identifiers - for example, the `-2D` option to `flirt` cannot be used as an
> identifier in Python, because it begins with a number. In situations like
> this, an alias is used. So to set the `-2D` option to `flirt`, you can do this:
>
> ```
> # "twod" applies the -2D flag
> flirt('source.nii.gz', 'ref.nii.gz', omat='src2ref.mat', twod=True)
> ```
Paul McCarthy's avatar
Paul McCarthy committed
801
802
803
804
>
> Some of the `fsl.wrappers` functions also support aliases which may make
> your code more readable. For example, when calling `bet`, you can use either
> `m=True` or `mask=True` to apply the `-m` command line flag.
Paul McCarthy's avatar
Paul McCarthy committed
805
806
807
808
809
810
811


<a class="anchor" id="in-memory-images"></a>
### In-memory images


It can be quite awkward to combine image processing with FSL tools and image
Paul McCarthy's avatar
Paul McCarthy committed
812
processing in Python. The `fsl.wrappers` package tries to make this a little
Paul McCarthy's avatar
Paul McCarthy committed
813
easier for you - if you are working with image data in Python, you can pass
Paul McCarthy's avatar
Paul McCarthy committed
814
`Image` or `nibabel` objects directly into `fsl.wrappers` functions - they will
Paul McCarthy's avatar
Paul McCarthy committed
815
816
817
be automatically saved to temporary files and passed to the underlying FSL
command:

Paul McCarthy's avatar
Paul McCarthy committed
818
819
820
821

```
cropped = Image('bighead_cropped')

Paul McCarthy's avatar
Paul McCarthy committed
822
823
824
825
826
827
828
829
830
831
832
833
834
bet(cropped, 'bighead_cropped_brain')

betted = Image('bighead_cropped_brain')

fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)
fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
```


<a class="anchor" id="loading-outputs-into-python"></a>
### Loading outputs into Python


Paul McCarthy's avatar
Paul McCarthy committed
835
By using the special `fsl.wrappers.LOAD` symbol, you can also have any output
836
files produced by the tool automatically loaded into memory for you:
Paul McCarthy's avatar
Paul McCarthy committed
837
838
839
840


```
cropped = Image('bighead_cropped')
841
842
843
844
845

# The loaded result is called "output",
# because that is the name of the
# argument in the bet wrapper function.
betted  = bet(cropped, LOAD).output
Paul McCarthy's avatar
Paul McCarthy committed
846
847
848
849
850
851
852

fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)
fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
```


You can use the `LOAD` symbol for any output argument - any output files which
853
are loaded will be available through the return value of the wrapper function:
Paul McCarthy's avatar
Paul McCarthy committed
854
855
856
857
858
859
860
861
862
863
864


```
from fsl.wrappers import flirt

std2mm   = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
tstat1   = Image(op.join('08_fslpy', 'fmri.feat', 'stats', 'tstat1'))
func2std = np.loadtxt(op.join('08_fslpy', 'fmri.feat', 'reg', 'example_func2standard.mat'))

aligned = flirt(tstat1, std2mm, applyxfm=True, init=func2std, out=LOAD)

865
866
867
868
# Here the resampled tstat image
# is called "out", because that
# is the name of the flirt argument.
aligned = aligned.out.data
Paul McCarthy's avatar
Paul McCarthy committed
869
870
aligned[aligned < 1] = 0

Paul McCarthy's avatar
Paul McCarthy committed
871
872
873
874
875
peakvox = np.abs(aligned).argmax()
peakvox = np.unravel_index(peakvox, aligned.shape)

fig = ortho(std2mm .data, peakvox, cmap=plt.cm.gray)
fig = ortho(aligned.data, peakvox, cmap=plt.cm.inferno, fig=fig, cursor=True)
Paul McCarthy's avatar
Paul McCarthy committed
876
877
878
```


Paul McCarthy's avatar
Paul McCarthy committed
879
880
For tools like `bet` and `fast`, which expect an output *prefix* or
*basename*, you can just set the prefix to `LOAD` - all output files with that
881
prefix will be available in the object that is returned:
Paul McCarthy's avatar
Paul McCarthy committed
882
883
884
885


```
img    = Image('bighead_cropped')
Paul McCarthy's avatar
Paul McCarthy committed
886
betted = bet(img, LOAD, f=0.3, mask=True)
Paul McCarthy's avatar
Paul McCarthy committed
887

888
889
890
fig = ortho(img               .data, (80, 112, 85), cmap=plt.cm.gray)
fig = ortho(betted.output     .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
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
891
892
893
894
895
896
897
```


<a class="anchor" id="the-fslmaths-wrapper"></a>
### The `fslmaths` wrapper


Paul McCarthy's avatar
Paul McCarthy committed
898
*Most* of the `fsl.wrappers` functions aim to provide an interface which is as
Paul McCarthy's avatar
Paul McCarthy committed
899
900
901
902
903
904
905
close as possible to the underlying FSL tool. Ideally, if you read the
command-line help for a tool, you should be able to figure out how to use the
corresponding wrapper function. The wrapper for the `fslmaths` command is a
little different, however. It provides more of an object-oriented interface,
which is hopefully a little easier to use from within Python.


Paul McCarthy's avatar
Paul McCarthy committed
906
907
908
You can apply an `fslmaths` operation by specifying the input image,
*chaining* method calls together, and finally calling the `run()` method. For
example:
Paul McCarthy's avatar
Paul McCarthy committed
909
910
911


```
Paul McCarthy's avatar
Paul McCarthy committed
912
from fsl.wrappers import fslmaths
Paul McCarthy's avatar
Paul McCarthy committed
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
fslmaths('bighead_cropped')            \
  .mas(  'bighead_cropped_brain_mask') \
  .run(  'bighead_cropped_brain')

render('bighead_cropped bighead_cropped_brain -cm hot')
```


Of course, you can also use the `fslmaths` wrapper with in-memory images:


```
wholehead   = Image('bighead_cropped')
brainmask   = Image('bighead_cropped_brain_mask')

eroded      = fslmaths(brainmask).ero().ero().run()
erodedbrain = fslmaths(wholehead).mas(eroded).run()

fig = ortho(wholehead  .data, (80, 112, 85), cmap=plt.cm.gray)
fig = ortho(brainmask  .data, (80, 112, 85), cmap=plt.cm.summer,  fig=fig)
fig = ortho(erodedbrain.data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
Paul McCarthy's avatar
Paul McCarthy committed
934
935
936
```


Paul McCarthy's avatar
Paul McCarthy committed
937
<a class="anchor" id="the-filetree"></a>
Paul McCarthy's avatar
Paul McCarthy committed
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
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
989
990
991
992
993
994
995
996
997
998
999
1000
## The `FileTree`


The
[`fsl.utils.filetree`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html)
library provides functionality which allows you to work with *structured data
directories*, such as HCP or BIDS datasets. You can use `filetree` for both
reading and for creating datasets.


This practical gives a very brief introduction to the `filetree` library -
refer to the [full
documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html)
to get a feel for how powerful it can be.


<a class="anchor" id="describing-your-data"></a>
### Describing your data


To introduce `filetree`, we'll begin with a small example. Imagine that we
have a dataset which looks like this:


> ```
> mydata
> ├── sub_A
> │   ├── ses_1
> │   │   └── T1w.nii.gz
> │   ├── ses_2
> │   │   └── T1w.nii.gz
> │   └── T2w.nii.gz
> ├── sub_B
> │   ├── ses_1
> │   │   └── T1w.nii.gz
> │   ├── ses_2
> │   │   └── T1w.nii.gz
> │   └── T2w.nii.gz
> └── sub_C
>     ├── ses_1
>     │   └── T1w.nii.gz
>     ├── ses_2
>     │   └── T1w.nii.gz
>     └── T2w.nii.gz
> ```


(Run the code cell below to create a dummy data set with the above structure):


```
%%bash
for sub in A B C; do
  subdir=mydata/sub_$sub/
  mkdir -p $subdir
  cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $subdir/T2w.nii.gz
  for ses in 1 2; do
    sesdir=$subdir/ses_$ses/
    mkdir $sesdir
    cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $sesdir/T1w.nii.gz
  done
done
```
Paul McCarthy's avatar
Paul McCarthy committed
1001
1002


Paul McCarthy's avatar
Paul McCarthy committed
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
To use `filetree` with this dataset, we must first describe its structure - we
do this by creating a `.tree` file:


```
%%writefile mydata.tree
sub_{subject}
  T2w.nii.gz
  ses_{session}
    T1w.nii.gz
```


A `.tree` file is simply a description of the structure of your data
directory - it describes the *file types* (also known as *templates*) which
are present in the dataset (`T1w` and `T2w`), and the *variables* which are
implicitly present in the structure of the dataset (`subject` and `session`).


<a class="anchor" id="using-the-filetree"></a>
### Using the `FileTree`


Now that we have a `.tree` file which describe our data, we can create a
`FileTree` to work with it:


```
from fsl.utils.filetree import FileTree

Paul McCarthy's avatar
Paul McCarthy committed
1033
1034
1035
# Create a FileTree, giving
# it our tree specification,
# and the path to our data.
Paul McCarthy's avatar
Paul McCarthy committed
1036
1037
1038
1039
1040
tree = FileTree.read('mydata.tree', 'mydata')
```

We can list all of the T1 images via the `FileTree.get_all` method. The
`glob_vars='all'` option tells the `FileTree` to fill in the `T1w` template
Paul McCarthy's avatar
Paul McCarthy committed
1041
1042
1043
with all possible combinations of variables. The `FileTree.extract_variables`
method accepts a file path, and gives you back the variable values contained
within:
Paul McCarthy's avatar
Paul McCarthy committed
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


```
for t1file in tree.get_all('T1w', glob_vars='all'):
    fvars = tree.extract_variables('T1w', t1file)
    print(t1file, fvars)
```


The `FileTree.update` method allows you to "fill in" variable values; it
returns a new `FileTree` object which can be used on a selection of the
data set:


```
treeA = tree.update(subject='A')
for t1file in treeA.get_all('T1w', glob_vars='all'):
    fvars = treeA.extract_variables('T1w', t1file)
    print(t1file, fvars)
```


<a class="anchor" id="building-a-processing-pipeline-with-filetree"></a>
### Building a processing pipeline with `FileTree`


Let's say we want to run BET on all of our T1 images. Let's start by modifying
our `.tree` definition to include the BET outputs:


```
%%writefile mydata.tree
sub_{subject}
  T2w.nii.gz
  ses_{session}
    T1w.nii.gz
    T1w_brain.nii.gz
    T1w_brain_mask.nii.gz
```


Paul McCarthy's avatar
Paul McCarthy committed
1085
1086
1087
Now we can use the `FileTree` to generate the relevant file names for us,
which we can then pass on to BET.  Here we'll use the `FileTree.get_all_trees`
method to create a sub-tree for each subject and each session:
Paul McCarthy's avatar
Paul McCarthy committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100


```
from fsl.wrappers import bet
tree = FileTree.read('mydata.tree', 'mydata')
for subtree in tree.get_all_trees('T1w', glob_vars='all'):
    t1file  = subtree.get('T1w')
    t1brain = subtree.get('T1w_brain')
    print('Running BET: {} -> {} ...'.format(t1file, t1brain))
    bet(t1file, t1brain, mask=True)
print('Done!')

example = tree.update(subject='A', session='1')
Paul McCarthy's avatar
Paul McCarthy committed
1101
render('{} {} -ot mask -o -w 2 -mc 0 1 0'.format(
Paul McCarthy's avatar
Paul McCarthy committed
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
    example.get('T1w'),
    example.get('T1w_brain_mask')))

```


<a class="anchor" id="the-filetreequery"></a>
### The `FileTreeQuery`


The `filetree` module contains another class called the
[`FileTreeQuery`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.query.html),
which provides an interface that is more convenient if you are reading data
from large datasets with many different file types and variables.


When you create a `FileTreeQuery`, it scans the entire data directory and
identifies all of the values that are present for each variable defined in the
`.tree` file:


```
from fsl.utils.filetree import FileTreeQuery
tree = FileTree.read('mydata.tree', 'mydata')
query = FileTreeQuery(tree)
print('T1w variables:', query.variables('T1w'))
print('T2w variables:', query.variables('T2w'))
```


The `FileTreeQuery.query` method will return the paths to all existing files
which match a set of variable values:


```
Paul McCarthy's avatar
Paul McCarthy committed
1137
print('All files for subject A')
Paul McCarthy's avatar
Paul McCarthy committed
1138
for template in query.templates:
Paul McCarthy's avatar
Paul McCarthy committed
1139
1140
1141
    print('  {} files:'.format(template))
    for match in query.query(template, subject='A'):
        print('   ', match.filename)
Paul McCarthy's avatar
Paul McCarthy committed
1142
1143
```

Paul McCarthy's avatar
Paul McCarthy committed
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
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
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235

<a class="anchor" id="calling-shell-commands"></a>
## Calling shell commands


The
[`fsl.utils.run`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.run.html)
module provides the `run` and `runfsl` functions, which are wrappers around
the built-in [`subprocess`
library](https://docs.python.org/3/library/subprocess.html).


The default behaviour of `run` is to return the standard output of the
command:


```
from fsl.utils.run import run

# You can pass the command
# and its arguments as a single
# string, or as a sequence
print('Lines in this notebook:', run('wc -l 08_fslpy.md').strip())
print('Words in this notebook:', run(['wc', '-w', '08_fslpy.md']).strip())
```


But you can control what `run` returns, depending on your needs. Let's create
a little script to demonstrate the options:


```
%%writefile mycmd
#!/usr/bin/env bash
exitcode=$1

echo "Standard output!"
echo "Standard error :(" >&2

exit $exitcode
```


And let's not forget to make it executable:


```
!chmod a+x mycmd
```


You can use the `stdout`, `stderr` and `exitcode` arguments to control the
return value:


```
print('run("./mycmd 0"):                                          ',
       run("./mycmd 0").strip())
print('run("./mycmd 0", stdout=False):                            ',
       run("./mycmd 0", stdout=False))
print('run("./mycmd 0",                            exitcode=True):',
       run("./mycmd 0",                            exitcode=True))
print('run("./mycmd 0", stdout=False,              exitcode=True):',
       run("./mycmd 0", stdout=False,              exitcode=True))
print('run("./mycmd 0",               stderr=True):               ',
       run("./mycmd 0",               stderr=True))
print('run("./mycmd 0", stdout=False, stderr=True):               ',
       run("./mycmd 0", stdout=False, stderr=True).strip())
print('run("./mycmd 0",               stderr=True, exitcode=True):',
       run("./mycmd 0",               stderr=True, exitcode=True))

print('run("./mycmd 1",                            exitcode=True):',
       run("./mycmd 1",                            exitcode=True))
print('run("./mycmd 1", stdout=False,              exitcode=True):',
       run("./mycmd 1", stdout=False,              exitcode=True))
```


So if only one of `stdout`, `stderr`, or `exitcode` is `True`, `run` will only
return the corresponding value. Otherwise `run` will return a tuple which
contains the requested outputs.


If you run a command which returns a non-0 exit code, the default behaviour
(if you don't set `exitcode=True`) is for a `RuntimeError` to be raised:


```
run("./mycmd 99")
```


Paul McCarthy's avatar
Paul McCarthy committed
1236
1237
<a class="anchor" id="the-runfsl-function"></a>
### The `runfsl` function
Paul McCarthy's avatar
Paul McCarthy committed
1238
1239
1240
1241
1242
1243
1244
1245
1246


The `runfsl` function is a wrapper around `run` which simply makes sure that
the command you are calling is inside the `$FSLDIR/bin/` directory. It has the
same usage as the `run` function:


```
from fsl.utils.run import runfsl
Paul McCarthy's avatar
Paul McCarthy committed
1247
runfsl('bet bighead_cropped bighead_cropped_brain')
Paul McCarthy's avatar
Paul McCarthy committed
1248
runfsl('fslroi bighead_cropped_brain bighead_slices 0 -1 0 -1 90 3')
Paul McCarthy's avatar
Paul McCarthy committed
1249
runfsl('fast -o bighead_fast bighead_slices')
Paul McCarthy's avatar
Paul McCarthy committed
1250
1251

render('-vl 80 112 91 -xh -yh '
Paul McCarthy's avatar
Paul McCarthy committed
1252
       'bighead_cropped '
Paul McCarthy's avatar
Paul McCarthy committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
       'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '
       'bighead_fast_seg.nii.gz -ot label -o')
```


<a class="anchor" id="submitting-to-the-cluster"></a>
### Submitting to the cluster


Both the `run` and `runfsl` accept an argument called `submit`, which allows
you to submit jobs to be executed on the cluster via the FSL `fsl_sub`
command.


> Cluster submission is handled by the
> [`fsl.utils.fslsub`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html)
> module - it contains lower level functions for managing and querying jobs
> that have been submitted to the cluster. The functions defined in this
> module can be used directly if you have more complicated requirements.


The semantics of the `run` and `runfsl` functions are slightly different when
Paul McCarthy's avatar
Paul McCarthy committed
1275
1276
1277
you use the `submit` option - when you submit a job, the `run`/`runfsl`
functions will return immediately, and will return a string containing the job
ID:
Paul McCarthy's avatar
Paul McCarthy committed
1278
1279
1280
1281
1282


```
jobid  = run('ls', submit=True)
print('Job ID:', jobid)
Paul McCarthy's avatar
Paul McCarthy committed
1283
1284
1285
```


Paul McCarthy's avatar
Paul McCarthy committed
1286
Once the job finishes, we should be able to read the usual `.o` and `.e`
Paul McCarthy's avatar
Paul McCarthy committed
1287
1288
1289
1290
files:


```
Paul McCarthy's avatar
Paul McCarthy committed
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
stdout = f'ls.o{jobid}'
print('Job output')
print(open(stdout).read())
```


All of the `fsl.wrappers` functions also accept the `submit` argument:


```
jobid = bet('08_fslpy/bighead', 'bighead_brain', submit=True)
print('Job ID:', jobid)
```


> But an error will occur if you try to pass in-memory images, or `LOAD` any
> outputs when you call a wrapper function with `submit=True`.


After submitting a job, you can use the `wait` function to wait until a job
has completed:


```
from fsl.utils.run import wait
jobid = bet('08_fslpy/bighead', 'bighead_brain', submit=True)
print('Job ID:', jobid)
wait(jobid)
print('Done!')
render('08_fslpy/bighead bighead_brain -cm hot')
Paul McCarthy's avatar
Paul McCarthy committed
1321
1322
1323
```


Paul McCarthy's avatar
Paul McCarthy committed
1324
When you use `submit=True`, you can also specify cluster submission options -
Paul McCarthy's avatar
Paul McCarthy committed
1325
you can include any arguments that are accepted by the
Paul McCarthy's avatar
Paul McCarthy committed
1326
[`fslsub.submit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html#fsl.utils.fslsub.submit)
Paul McCarthy's avatar
Paul McCarthy committed
1327
function
Paul McCarthy's avatar
Paul McCarthy committed
1328
1329
1330


```
Paul McCarthy's avatar
Paul McCarthy committed
1331
1332
1333
1334
1335
1336
1337
jobs = []
jobs.append(runfsl('robustfov -i 08_fslpy/bighead -r bighead_cropped',    submit=True, queue='short.q'))
jobs.append(runfsl('bet bighead_cropped bighead_brain',                   submit=True, queue='short.q', wait_for=jobs[-1]))
jobs.append(runfsl('fslroi bighead_brain bighead_slices 0 -1 111 3 0 -1', submit=True, queue='short.q', wait_for=jobs[-1]))
jobs.append(runfsl('fast -o bighead_fast bighead_slices',                 submit=True, queue='short.q', wait_for=jobs[-1]))
print('Waiting for', jobs, '...')
wait(jobs)
Paul McCarthy's avatar
Paul McCarthy committed
1338
1339
1340
1341
1342
1343
1344

render('-vl 80 112 91 -xh -zh -hc '
       'bighead_brain '
       'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '
       'bighead_fast_seg.nii.gz -ot label -o')
```

Paul McCarthy's avatar
Paul McCarthy committed
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

<a class="anchor" id="redirecting-output"></a>
### Redirecting output


The `log` option, accepted by both `run` and `fslrun`, allows for more
fine-grained control over what is done with the standard output and error
streams.


You can use `'tee'` to redirect the standard output and error streams of the
command to the standard output and error streams of the calling command (your
python script):


```
print('Teeing:')
_ = run('./mycmd 0', log={'tee' : True})
```


Or you can use `'stdout'` and `'stderr'` to redirect the standard output and
error streams of the command to files:


```
with open('stdout.log', 'wt') as o, \
     open('stderr.log', 'wt') as e:
     run('./mycmd 0', log={'stdout' : o, 'stderr' : e})
print('\nRedirected stdout:')
!cat stdout.log
print('\nRedirected stderr:')
!cat stderr.log
```


Finally, you can use `'cmd'` to log the command itself to a file (useful for
pipeline logging):


```
with open('commands.log', 'wt') as cmdlog:
     run('./mycmd 0',         log={'cmd' : cmdlog})
     run('wc -l 08_fslpy.md', log={'cmd' : cmdlog})

print('\nCommand log:')
!cat commands.log
```


1395
1396
1397
<a class="anchor" id="fsl-atlases"></a>
## FSL atlases

Paul McCarthy's avatar
Paul McCarthy committed
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414

The
[`fsl.data.atlases`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.atlases.html)
module provides access to all of the atlas images that are stored in the
`$FSLDIR/data/atlases/` directory of a standard FSL installation. It can be
used to load and query probabilistic and label-based atlases.


The `atlases` module needs to be initialised using the `rescanAtlases` function:


```
import fsl.data.atlases as atlases
atlases.rescanAtlases()
```


Paul McCarthy's avatar
Paul McCarthy committed
1415
1416
1417
1418
<a class="anchor" id="querying-atlases"></a>
### Querying atlases


Paul McCarthy's avatar
Paul McCarthy committed
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
You can list all of the available atlases using `listAtlases`:


```
for desc in atlases.listAtlases():
    print(desc)
```


`listAtlases` returns a list of `AtlasDescription` objects, each of which
contains descriptive information about one atlas. You can retrieve the
`AtlasDescription` for a specific atlas via the `getAtlasDescription`
function:


```
desc = atlases.getAtlasDescription('harvardoxford-cortical')
print(desc.name)
print(desc.atlasID)
print(desc.specPath)
print(desc.atlasType)
```


Each `AtlasDescription` maintains a list of `AtlasLabel` objects, each of
which represents one region that is defined in the atlas. You can access all
of the `AtlasLabel` objects via the `labels` attribute:


```
for lbl in desc.labels[:5]:
    print(lbl)
```


Or you can retrieve a specific label using the `find` method:


```
# search by region name
print(desc.find(name='Occipital Pole'))

# or by label value
print(desc.find(value=48))
```


Paul McCarthy's avatar
Paul McCarthy committed
1466
1467
1468
1469
<a class="anchor" id="loading-atlas-images"></a>
### Loading atlas images


Paul McCarthy's avatar
Paul McCarthy committed
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
The `loadAtlas` function can be used to load the atlas image:


```
# For probabilistic atlases, you
# can ask for the 3D ROI image
# by setting loadSummary=True.
# You can also request a
# resolution - by default the
# highest resolution version
# will be loaded.
lblatlas = atlases.loadAtlas('harvardoxford-cortical',
                             loadSummary=True,
                             resolution=2)

# By default you will get the 4D
# probabilistic atlas image (for
# atlases for which this is
# available).
probatlas = atlases.loadAtlas('harvardoxford-cortical',
                              resolution=2)

print(lblatlas)
print(probatlas)
```


Paul McCarthy's avatar
Paul McCarthy committed
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
<a class="anchor" id="working-with-atlases"></a>
### Working with atlases


Both `LabelAtlas` and `ProbabilisticAtlas` objects have a method called `get`,
which can be used to extract ROI images for a specific region:


```
stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))

frontal = lblatlas.get(name='Frontal Pole').data
frontal = np.ma.masked_where(frontal < 1, frontal)

1512
1513
fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)
fig = ortho(frontal,     (45, 54, 45), cmap=plt.cm.winter, fig=fig)
Paul McCarthy's avatar
Paul McCarthy committed
1514
1515
1516
```


Paul McCarthy's avatar
Paul McCarthy committed
1517
Calling `get` on a `ProbabilisticAtlas` will return a probability image:
Paul McCarthy's avatar
Paul McCarthy committed
1518
1519
1520
1521
1522
1523


```
stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))

Paul McCarthy's avatar
Paul McCarthy committed
1524
frontal = probatlas.get(name='Frontal Pole').data
Paul McCarthy's avatar
Paul McCarthy committed
1525
1526
frontal = np.ma.masked_where(frontal < 1, frontal)

1527
1528
fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)
fig = ortho(frontal,     (45, 54, 45), cmap=plt.cm.inferno, fig=fig)
Paul McCarthy's avatar
Paul McCarthy committed
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
```


The `get` method can be used to retrieve an image for a region by:
- an `AtlasLabel` object
- The region index
- The region value
- The region name


Paul McCarthy's avatar
Paul McCarthy committed
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
`LabelAtlas` objects have a method called `label`, which can be used to
interrogate the atlas at specific locations:


```
# The label method accepts 3D
# voxel or world coordinates
val = lblatlas.label((25, 52, 43), voxel=True)
lbl = lblatlas.find(value=val)
print('Region at voxel [25, 52, 43]: {} [{}]'.format(val, lbl.name))


# or a 3D weighted or binary mask
mask = np.zeros(lblatlas.shape)
mask[30:60, 30:60, 30:60] = 1
mask = Image(mask, header=lblatlas.header)

lbls, props = lblatlas.label(mask)
print('Labels in mask:')
for lbl, prop in zip(lbls, props):
    lblname = lblatlas.find(value=lbl).name
    print('  {} [{}]: {:0.2f}%'.format(lbl, lblname, prop))
```


`ProbabilisticAtlas` objects have an analogous method called `values`:


```
vals = probatlas.values((25, 52, 43), voxel=True)
print('Regions at voxel [25, 52, 43]:')
for idx, val in enumerate(vals):
    if val > 0:
        lbl = probatlas.find(index=idx)
        print('  {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val))

print('Average proportions of regions within mask:')
vals = probatlas.values(mask)
for idx, val in enumerate(vals):
    if val > 0:
        lbl = probatlas.find(index=idx)
        print('  {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val))
```