Skip to content
Snippets Groups Projects
Commit f2d47252 authored by Paul McCarthy's avatar Paul McCarthy :mountain_bicyclist:
Browse files

Merge branch 'mnt/fslpy' into 'master'

update fslpy practical

See merge request !27
parents e33656d1 49412bcf
No related branches found
No related tags found
1 merge request!27update fslpy practical
%% Cell type:markdown id: tags: %% Cell type:markdown id:d9547ad5 tags:
# `fslpy` # `fslpy`
> *Note*: This practical assumes that you have FSL 6.0.4 or newer installed. > *Note*: This practical assumes that you have FSL 6.0.5.1 or newer installed.
[`fslpy`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/) is a [`fslpy`](https://open.win.ox.ac.uk/pages/fsl/fslpy/) is a
Python library which is built into FSL, and contains a range of functionality Python library which is built into FSL, and contains a range of functionality
for working with FSL and with neuroimaging data from Python. for working with FSL and with neuroimaging data from Python.
This practical highlights some of the most useful features provided by This practical highlights some of the most useful features provided by
`fslpy`. You may find `fslpy` useful if you are writing Python code to `fslpy`. You may find `fslpy` useful if you are writing Python code to
perform analyses and image processing in conjunction with FSL. perform analyses and image processing in conjunction with FSL.
* [The `Image` class, and other data types](#the-image-class-and-other-data-types) * [The `Image` class, and other data types](#the-image-class-and-other-data-types)
* [Creating images](#creating-images) * [Creating images](#creating-images)
* [Working with image data](#working-with-image-data) * [Working with image data](#working-with-image-data)
* [Loading other file types](#loading-other-file-types) * [Loading other file types](#loading-other-file-types)
* [NIfTI coordinate systems](#nifti-coordinate-systems) * [NIfTI coordinate systems](#nifti-coordinate-systems)
* [Transformations and resampling](#transformations-and-resampling) * [Transformations and resampling](#transformations-and-resampling)
* [FSL wrapper functions](#fsl-wrapper-functions) * [FSL wrapper functions](#fsl-wrapper-functions)
* [In-memory images](#in-memory-images) * [In-memory images](#in-memory-images)
* [Loading outputs into Python](#loading-outputs-into-python) * [Loading outputs into Python](#loading-outputs-into-python)
* [The `fslmaths` wrapper](#the-fslmaths-wrapper) * [The `fslmaths` wrapper](#the-fslmaths-wrapper)
* [The `FileTree`](#the-filetree) * [The `FileTree`](#the-filetree)
* [Describing your data](#describing-your-data) * [Describing your data](#describing-your-data)
* [Using the `FileTree`](#using-the-filetree) * [Using the `FileTree`](#using-the-filetree)
* [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree) * [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree)
* [The `FileTreeQuery`](#the-filetreequery)
* [Calling shell commands](#calling-shell-commands) * [Calling shell commands](#calling-shell-commands)
* [The `runfsl` function](#the-runfsl-function) * [The `runfsl` function](#the-runfsl-function)
* [Submitting to the cluster](#submitting-to-the-cluster) * [Submitting to the cluster](#submitting-to-the-cluster)
* [Redirecting output](#redirecting-output) * [Redirecting output](#redirecting-output)
* [FSL atlases](#fsl-atlases) * [FSL atlases](#fsl-atlases)
* [Querying atlases](#querying-atlases) * [Querying atlases](#querying-atlases)
* [Loading atlas images](#loading-atlas-images) * [Loading atlas images](#loading-atlas-images)
* [Working with atlases](#working-with-atlases) * [Working with atlases](#working-with-atlases)
> **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python > **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python
> environment that is baked into FSL. `fslpy` is a Python library which is > environment that is baked into FSL. `fslpy` is a Python library which is
> installed into the `fslpython` environment. > installed into the `fslpython` environment.
Let's start with some standard imports and environment set-up: Let's start with some standard imports and environment set-up:
%% Cell type:code id: tags: %% Cell type:code id:0a8807ba tags:
``` ```
%matplotlib inline %matplotlib inline
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import os import os
import os.path as op import os.path as op
import nibabel as nib import nibabel as nib
import numpy as np import numpy as np
import warnings import warnings
warnings.filterwarnings("ignore") warnings.filterwarnings("ignore")
np.set_printoptions(suppress=True, precision=4) np.set_printoptions(suppress=True, precision=4)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:fb1c18e4 tags:
And a little function that we can use to generate a simple orthographic plot: And a little function that we can use to generate a simple orthographic plot:
%% Cell type:code id: tags: %% Cell type:code id:733fa41c tags:
``` ```
def ortho(data, voxel, fig=None, cursor=False, **kwargs): def ortho(data, voxel, fig=None, cursor=False, **kwargs):
"""Simple orthographic plot of a 3D array using matplotlib. """Simple orthographic plot of a 3D array using matplotlib.
:arg data: 3D numpy array :arg data: 3D numpy array
:arg voxel: XYZ coordinates for each slice :arg voxel: XYZ coordinates for each slice
:arg fig: Existing figure and axes for overlay plotting :arg fig: Existing figure and axes for overlay plotting
:arg cursor: Show a cursor at the `voxel` :arg cursor: Show a cursor at the `voxel`
All other arguments are passed through to the `imshow` function. All other arguments are passed through to the `imshow` function.
:returns: The figure and orthogaxes (which can be passed back in as the :returns: The figure and orthogaxes (which can be passed back in as the
`fig` argument to plot overlays). `fig` argument to plot overlays).
""" """
voxel = [int(round(v)) for v in voxel] voxel = [int(round(v)) for v in voxel]
data = np.asanyarray(data, dtype=np.float) data = np.asanyarray(data, dtype=np.float)
data[data <= 0] = np.nan data[data <= 0] = np.nan
x, y, z = voxel x, y, z = voxel
xslice = np.flipud(data[x, :, :].T) xslice = np.flipud(data[x, :, :].T)
yslice = np.flipud(data[:, y, :].T) yslice = np.flipud(data[:, y, :].T)
zslice = np.flipud(data[:, :, z].T) zslice = np.flipud(data[:, :, z].T)
if fig is None: if fig is None:
fig = plt.figure() fig = plt.figure()
xax = fig.add_subplot(1, 3, 1) xax = fig.add_subplot(1, 3, 1)
yax = fig.add_subplot(1, 3, 2) yax = fig.add_subplot(1, 3, 2)
zax = fig.add_subplot(1, 3, 3) zax = fig.add_subplot(1, 3, 3)
else: else:
fig, xax, yax, zax = fig fig, xax, yax, zax = fig
xax.imshow(xslice, **kwargs) xax.imshow(xslice, **kwargs)
yax.imshow(yslice, **kwargs) yax.imshow(yslice, **kwargs)
zax.imshow(zslice, **kwargs) zax.imshow(zslice, **kwargs)
if cursor: if cursor:
cargs = {'color' : (0, 1, 0), 'linewidth' : 1} cargs = {'color' : (0, 1, 0), 'linewidth' : 1}
xax.axvline( y, **cargs) xax.axvline( y, **cargs)
xax.axhline(data.shape[2] - z, **cargs) xax.axhline(data.shape[2] - z, **cargs)
yax.axvline( x, **cargs) yax.axvline( x, **cargs)
yax.axhline(data.shape[2] - z, **cargs) yax.axhline(data.shape[2] - z, **cargs)
zax.axvline( x, **cargs) zax.axvline( x, **cargs)
zax.axhline(data.shape[1] - y, **cargs) zax.axhline(data.shape[1] - y, **cargs)
for ax in (xax, yax, zax): for ax in (xax, yax, zax):
ax.set_xticks([]) ax.set_xticks([])
ax.set_yticks([]) ax.set_yticks([])
fig.tight_layout(pad=0) fig.tight_layout(pad=0)
return (fig, xax, yax, zax) return (fig, xax, yax, zax)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:a375c62b tags:
And another function which uses FSLeyes for more complex plots: And another function which uses FSLeyes for more complex plots:
%% Cell type:code id: tags: %% Cell type:code id:2fa4e153 tags:
``` ```
def render(cmdline): def render(cmdline):
import shlex
import IPython.display as display import IPython.display as display
prefix = '-of screenshot.png -hl -c 2 ' prefix = '-of screenshot.png -hl -c 2 '
try: from fsl.utils.run import runfsl
from fsleyes.render import main prefix = 'render ' + prefix
main(shlex.split(prefix + cmdline)) runfsl(prefix + cmdline, env={})
except (ImportError, AttributeError):
# 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={})
return display.Image('screenshot.png') return display.Image('screenshot.png')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:3667cc28 tags:
<a class="anchor" id="the-image-class-and-other-data-types"></a> <a class="anchor" id="the-image-class-and-other-data-types"></a>
## The `Image` class, and other data types ## The `Image` class, and other data types
The The
[`fsl.data.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image) [`fsl.data.image`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.image.html#fsl.data.image.Image)
module provides the `Image` class, which sits on top of `nibabel` and contains module provides the `Image` class, which sits on top of `nibabel` and contains
some handy functionality if you need to work with coordinate transformations, some handy functionality if you need to work with coordinate transformations,
or do some FSL-specific processing. The `Image` class provides features such or do some FSL-specific processing. The `Image` class provides features such
as: as:
- Support for NIFTI1, NIFTI2, and ANALYZE image files - Support for NIFTI1, NIFTI2, and ANALYZE image files
- Access to affine transformations between the voxel, FSL and world coordinate - Access to affine transformations between the voxel, FSL and world coordinate
systems systems
- Ability to load metadata from BIDS sidecar files - Ability to load metadata from BIDS sidecar files
> The `Image` class behaves differently to the `nibabel.Nifti1Image`. For > The `Image` class behaves differently to the `nibabel.Nifti1Image`. For
> example, when you create an `Image` object, the default behaviour is to load > 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 image data into memory. This is configurable however; take a look at
> [the > [the
> documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image) > documentation](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.image.html#fsl.data.image.Image)
> to explore all of the options. > to explore all of the options.
Some simple image processing routines are also provided - these are covered Some simple image processing routines are also provided - these are covered
[below](#image-processing). [below](#image-processing).
<a class="anchor" id="creating-images"></a> <a class="anchor" id="creating-images"></a>
### Creating images ### Creating images
It's easy to create an `Image` - you can create one from a file name: It's easy to create an `Image` - you can create one from a file name:
%% Cell type:code id: tags: %% Cell type:code id:649bcad8 tags:
``` ```
from fsl.data.image import Image from fsl.data.image import Image
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
# load a FSL image - the file # load a FSL image - the file
# suffix is optional, just like # suffix is optional, just like
# in real FSL-land! # in real FSL-land!
std1mm = Image(op.join(stddir, 'MNI152_T1_1mm')) std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))
print(std1mm) print(std1mm)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:68003fb0 tags:
You can create an `Image` from an existing `nibabel` image: You can create an `Image` from an existing `nibabel` image:
%% Cell type:code id: tags: %% Cell type:code id:863c9948 tags:
``` ```
# load a nibabel image, and # load a nibabel image, and
# convert it into an FSL image # convert it into an FSL image
nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz')) nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz'))
std1mm = Image(nibimg) std1mm = Image(nibimg)
print(std1mm) print(std1mm)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:086a20bf tags:
Or you can create an `Image` from a `numpy` array: Or you can create an `Image` from a `numpy` array:
%% Cell type:code id: tags: %% Cell type:code id:ba0f297d tags:
``` ```
data = np.zeros((182, 218, 182)) data = np.zeros((182, 218, 182))
img = Image(data, xform=np.eye(4)) img = Image(data, xform=np.eye(4))
print(img) print(img)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:a3e4a949 tags:
If you have generated some data from another `Image` (or from a If you have generated some data from another `Image` (or from a
`nibabel.Nifti1Image`) you can use the `header` option to set `nibabel.Nifti1Image`) you can use the `header` option to set
the header information on the new image: the header information on the new image:
%% Cell type:code id: tags: %% Cell type:code id:5566318e tags:
``` ```
img = Image(data, header=std1mm.header) img = Image(data, header=std1mm.header)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:8f13c01b tags:
You can save an image to file via the `save` method: You can save an image to file via the `save` method:
%% Cell type:code id: tags: %% Cell type:code id:7245b478 tags:
``` ```
img.save('empty') img.save('empty')
!ls !ls
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:3f50bba4 tags:
`Image` objects have all of the attributes you might expect: `Image` objects have all of the attributes you might expect:
%% Cell type:code id: tags: %% Cell type:code id:997ba5ec tags:
``` ```
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
std1mm = Image(op.join(stddir, 'MNI152_T1_1mm')) std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))
print('name: ', std1mm.name) print('name: ', std1mm.name)
print('file: ', std1mm.dataSource) print('file: ', std1mm.dataSource)
print('NIfTI version:', std1mm.niftiVersion) print('NIfTI version:', std1mm.niftiVersion)
print('ndim: ', std1mm.ndim) print('ndim: ', std1mm.ndim)
print('shape: ', std1mm.shape) print('shape: ', std1mm.shape)
print('dtype: ', std1mm.dtype) print('dtype: ', std1mm.dtype)
print('nvals: ', std1mm.nvals) print('nvals: ', std1mm.nvals)
print('pixdim: ', std1mm.pixdim) print('pixdim: ', std1mm.pixdim)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:100f5f17 tags:
and a number of useful methods: and a number of useful methods:
%% Cell type:code id: tags: %% Cell type:code id:bfa9c7cc tags:
``` ```
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm')) std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))
mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask')) mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask'))
print(std1mm.sameSpace(std2mm)) print(std1mm.sameSpace(std2mm))
print(std2mm.sameSpace(mask2mm)) print(std2mm.sameSpace(mask2mm))
print(std2mm.getAffine('voxel', 'world')) print(std2mm.getAffine('voxel', 'world'))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:f26eb209 tags:
An `Image` object is a high-level wrapper around a `nibabel` image object - 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` you can always work directly with the `nibabel` object via the `nibImage`
attribute: attribute:
%% Cell type:code id: tags: %% Cell type:code id:f297fc8a tags:
``` ```
print(std2mm) print(std2mm)
print(std2mm.nibImage) print(std2mm.nibImage)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:b165916c tags:
<a class="anchor" id="working-with-image-data"></a> <a class="anchor" id="working-with-image-data"></a>
### Working with image data ### Working with image data
You can get the image data as a `numpy` array via the `data` attribute: You can get the image data as a `numpy` array via the `data` attribute:
%% Cell type:code id: tags: %% Cell type:code id:be17fb15 tags:
``` ```
data = std2mm.data data = std2mm.data
print(data.min(), data.max()) print(data.min(), data.max())
ortho(data, (45, 54, 45)) ortho(data, (45, 54, 45))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:6bc1e464 tags:
> Note that `Image.data` will give you the data in its underlying type, unlike > 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. > the `nibabel.get_fdata` method, which up-casts image data to floating-point.
You can also read and write data directly via the `Image` object: You can also read and write data directly via the `Image` object:
%% Cell type:code id: tags: %% Cell type:code id:4ece60d9 tags:
``` ```
slc = std2mm[:, :, 45] slc = std2mm[:, :, 45]
std2mm[0:10, :, :] *= 2 std2mm[0:10, :, :] *= 2
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:d4128213 tags:
Doing so has some advantages that may or may not be useful, depending on your Doing so has some advantages that may or may not be useful, depending on your
use-case: use-case:
- The image data will be kept on disk - only the parts that you access will - 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 be loaded into RAM (you will also need to pass`loadData=False` when creating
the `Image` to achieve this). the `Image` to achieve this).
- The `Image` object will keep track of modifications to the data (only whether - The `Image` object will keep track of modifications to the data (only whether
or not the image has been modified) - this can be queried via the `saveState` or not the image has been modified) - this can be queried via the `saveState`
attribute. attribute.
<a class="anchor" id="loading-other-file-types"></a> <a class="anchor" id="loading-other-file-types"></a>
### Loading other file types ### Loading other file types
The The
[`fsl.data`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.html#module-fsl.data) [`fsl.data`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.html#module-fsl.data)
package has a number of other classes for working with different types of FSL 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 and neuroimaging data. Most of these are higher-level wrappers around the
corresponding `nibabel` types: corresponding `nibabel` types:
* The * The
[`fsl.data.bitmap.Bitmap`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.bitmap.html) [`fsl.data.bitmap.Bitmap`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.bitmap.html#fsl.data.bitmap.Bitmap)
class can be used to load a bitmap image (e.g. `jpg`, `png`, etc) and class can be used to load a bitmap image (e.g. `jpg`, `png`, etc) and
convert it to a NIfTI image. convert it to a NIfTI image.
* The * The
[`fsl.data.dicom.DicomImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dicom.html) [`fsl.data.dicom.DicomImage`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.dicom.html#fsl.data.dicom.DicomImage)
class uses `dcm2niix` to load NIfTI images contained within a DICOM class uses `dcm2niix` to load NIfTI images contained within a DICOM
directory<sup>*</sup>. directory<sup>*</sup>.
* The * The
[`fsl.data.mghimage.MGHImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.mghimage.html) [`fsl.data.mghimage.MGHImage`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.mghimage.html#fsl.data.mghimage.MGHImage)
class can be used to load `.mgh`/`.mgz` images (they are converted into class can be used to load `.mgh`/`.mgz` images (they are converted into
NIfTI images). NIfTI images).
* The * The
[`fsl.data.dtifit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dtifit.html) [`fsl.data.dtifit`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.dtifit.html)
module contains functions for loading and working with the output of the module contains functions for loading and working with the output of the
FSL `dtifit` tool. FSL `dtifit` tool.
* The * The
[`fsl.data.featanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featanalysis.html), [`fsl.data.featanalysis`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.featanalysis.html),
[`fsl.data.featimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featimage.html), [`fsl.data.featimage`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.featimage.html),
and and
[`fsl.data.featdesign`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featdesign.html) [`fsl.data.featdesign`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.featdesign.html)
modules contain classes and functions for loading data from FEAT modules contain classes and functions for loading data from FEAT
directories. directories.
* Similarly, the * Similarly, the
[`fsl.data.melodicanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicanalysis.html) [`fsl.data.melodicanalysis`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.melodicanalysis.html)
and and
[`fsl.data.melodicimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicimage.html) [`fsl.data.melodicimage`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.melodicimage.html)
modules contain classes and functions for loading data from MELODIC modules contain classes and functions for loading data from MELODIC
directories. directories.
* The * The
[`fsl.data.gifti`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.gifti.html), [`fsl.data.gifti`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.gifti.html),
[`fsl.data.freesurfer`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.freesurfer.html), [`fsl.data.freesurfer`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.freesurfer.html),
and and
[`fsl.data.vtk`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.vtk.html) [`fsl.data.vtk`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.vtk.html)
modules contain functionality form loading surface data from GIfTI, modules contain functionality form loading surface data from GIfTI,
freesurfer, and ASCII VTK files respectively. freesurfer, and ASCII VTK files respectively.
> <sup>*</sup>You must make sure that > <sup>*</sup>You must make sure that
> [`dcm2niix`](https://github.com/rordenlab/dcm2niix/) is installed on your > [`dcm2niix`](https://github.com/rordenlab/dcm2niix/) is installed on your
> system in order to use this class. > system in order to use this class.
<a class="anchor" id="nifti-coordinate-systems"></a> <a class="anchor" id="nifti-coordinate-systems"></a>
### NIfTI coordinate systems ### NIfTI coordinate systems
The `Image.getAffine` method gives you access to affine transformations which The `Image.getAffine` method gives you access to affine transformations which
can be used to convert coordinates between the different coordinate systems 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 associated with a NIfTI image. Have some MNI coordinates you'd like to convert
to voxels? Easy! to voxels? Easy!
%% Cell type:code id: tags: %% Cell type:code id:988a63e9 tags:
``` ```
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm')) std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))
mnicoords = np.array([[0, 0, 0], mnicoords = np.array([[0, 0, 0],
[0, -18, 18]]) [0, -18, 18]])
world2vox = std2mm.getAffine('world', 'voxel') world2vox = std2mm.getAffine('world', 'voxel')
vox2world = std2mm.getAffine('voxel', 'world') vox2world = std2mm.getAffine('voxel', 'world')
# Apply the world->voxel # Apply the world->voxel
# affine to the coordinates # affine to the coordinates
voxcoords = (np.dot(world2vox[:3, :3], mnicoords.T)).T + world2vox[:3, 3] voxcoords = (np.dot(world2vox[:3, :3], mnicoords.T)).T + world2vox[:3, 3]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:65121fc2 tags:
The code above is a bit fiddly, so instead of figuring it out, you can just The code above is a bit fiddly, so instead of figuring it out, you can just
use the use the
[`affine.transform`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.affine.html#fsl.transform.affine.transform) [`affine.transform`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.affine.html#fsl.transform.affine.transform)
function: function:
%% Cell type:code id: tags: %% Cell type:code id:67da0015 tags:
``` ```
from fsl.transform.affine import transform from fsl.transform.affine import transform
voxcoords = transform(mnicoords, world2vox) voxcoords = transform(mnicoords, world2vox)
# just to double check, let's transform # just to double check, let's transform
# those voxel coordinates back into world # those voxel coordinates back into world
# coordinates # coordinates
backtomni = transform(voxcoords, vox2world) backtomni = transform(voxcoords, vox2world)
for m, v, b in zip(mnicoords, voxcoords, backtomni): for m, v, b in zip(mnicoords, voxcoords, backtomni):
print(m, '->', v, '->', b) print(m, '->', v, '->', b)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:bd76e384 tags:
> The `Image.getAffine` method can give you transformation matrices > The `Image.getAffine` method can give you transformation matrices
> between any of these coordinate systems: > between any of these coordinate systems:
> >
> - `'voxel'`: Image data voxel coordinates > - `'voxel'`: Image data voxel coordinates
> - `'world'`: mm coordinates, defined by the sform/qform of an image > - `'world'`: mm coordinates, defined by the sform/qform of an image
> - `'fsl'`: The FSL coordinate system, used internally by many FSL tools > - `'fsl'`: The FSL coordinate system, used internally by many FSL tools
> (e.g. FLIRT) > (e.g. FLIRT)
Oh, that example was too easy I hear you say? Try this one on for size. Let's 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 say we have run FEAT on some task fMRI data, and want to get the MNI
coordinates of the voxel with peak activation. coordinates of the voxel with peak activation.
> This is what people used to use `Featquery` for, back in the un-enlightened > This is what people used to use `Featquery` for, back in the un-enlightened
> days. > days.
Let's start by identifying the voxel with the biggest t-statistic: Let's start by identifying the voxel with the biggest t-statistic:
%% Cell type:code id: tags: %% Cell type:code id:667ca11f tags:
``` ```
featdir = 'fmri.feat' featdir = 'fmri.feat'
tstat1 = Image(op.join(featdir, 'stats', 'tstat1')).data tstat1 = Image(op.join(featdir, 'stats', 'tstat1')).data
# Recall from the numpy practical that # Recall from the numpy practical that
# argmax gives us a 1D index into a # argmax gives us a 1D index into a
# flattened view of the array. We can # flattened view of the array. We can
# use the unravel_index function to # use the unravel_index function to
# convert it into a 3D index. # convert it into a 3D index.
peakvox = np.abs(tstat1).argmax() peakvox = np.abs(tstat1).argmax()
peakvox = np.unravel_index(peakvox, tstat1.shape) peakvox = np.unravel_index(peakvox, tstat1.shape)
print('Peak voxel coordinates for tstat1:', peakvox, tstat1[peakvox]) print('Peak voxel coordinates for tstat1:', peakvox, tstat1[peakvox])
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:c0fdb45f tags:
Now that we've got the voxel coordinates in functional space, we need to 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 transform them into MNI space. FEAT provides a transformation which goes
directly from functional to standard space, in the `reg` directory: directly from functional to standard space, in the `reg` directory:
%% Cell type:code id: tags: %% Cell type:code id:0c8a57db tags:
``` ```
func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat')) func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:49ee9de3 tags:
But ... wait a minute ... this is a FLIRT matrix! We can't just plug voxel 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 coordinates into a FLIRT matrix and expect to get sensible results, because
FLIRT works in an internal FSL coordinate system, which is not quite 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. `'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 Let's start by loading our functional image, and the MNI152 template (the
source and reference images of our FLIRT matrix): source and reference images of our FLIRT matrix):
%% Cell type:code id: tags: %% Cell type:code id:8acb014f tags:
``` ```
func = Image(op.join(featdir, 'reg', 'example_func')) func = Image(op.join(featdir, 'reg', 'example_func'))
std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm'))) std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:baff5147 tags:
Now we can use them to get affines which convert between all of the different 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, coordinate systems - we're going to combine them into a single uber-affine,
which transforms our functional-space voxels into MNI world coordinates via: which transforms our functional-space voxels into MNI world coordinates via:
1. functional voxels -> FLIRT source space 1. functional voxels -> FLIRT source space
2. FLIRT source space -> FLIRT reference space 2. FLIRT source space -> FLIRT reference space
3. FLIRT referece space -> MNI world coordinates 3. FLIRT referece space -> MNI world coordinates
%% Cell type:code id: tags: %% Cell type:code id:8b693da2 tags:
``` ```
vox2fsl = func.getAffine('voxel', 'fsl') vox2fsl = func.getAffine('voxel', 'fsl')
fsl2mni = std .getAffine('fsl', 'world') fsl2mni = std .getAffine('fsl', 'world')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:86d75acf tags:
Combining two affines into one is just a simple dot-product. There is a 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: `concat()` function which does this for us, for any number of affines:
%% Cell type:code id: tags: %% Cell type:code id:12beef51 tags:
``` ```
from fsl.transform.affine import concat from fsl.transform.affine import concat
# To combine affines together, we # To combine affines together, we
# have to list them in reverse - # have to list them in reverse -
# linear algebra is *weird*. # linear algebra is *weird*.
funcvox2mni = concat(fsl2mni, func2std, vox2fsl) funcvox2mni = concat(fsl2mni, func2std, vox2fsl)
print(funcvox2mni) print(funcvox2mni)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:94b36d03 tags:
> In the next section we will use the > In the next section we will use the
> [`fsl.transform.flirt.fromFlirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html#fsl.transform.flirt.fromFlirt) > [`fsl.transform.flirt.fromFlirt`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.flirt.html#fsl.transform.flirt.fromFlirt)
> function, which does all of the above for us. > function, which does all of the above for us.
So we've now got some voxel coordinates from our functional data, and an 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: affine to transform into MNI world coordinates. The rest is easy:
%% Cell type:code id: tags: %% Cell type:code id:dc193ebb tags:
``` ```
mnicoords = transform(peakvox, funcvox2mni) mnicoords = transform(peakvox, funcvox2mni)
mnivoxels = transform(mnicoords, std.getAffine('world', 'voxel')) mnivoxels = transform(mnicoords, std.getAffine('world', 'voxel'))
mnivoxels = [int(round(v)) for v in mnivoxels] mnivoxels = [int(round(v)) for v in mnivoxels]
print('Peak activation (MNI coordinates):', mnicoords) print('Peak activation (MNI coordinates):', mnicoords)
print('Peak activation (MNI voxels): ', mnivoxels) print('Peak activation (MNI voxels): ', mnivoxels)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:60a3b4b7 tags:
Note that in the above example we are only applying a linear transformation 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 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 structural-to-standard transformation too. This is covered in the next
section. section.
<a class="anchor" id="transformations-and-resampling"></a> <a class="anchor" id="transformations-and-resampling"></a>
### Transformations and resampling ### Transformations and resampling
Now, it's all well and good to look at t-statistic values and voxel 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 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 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 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 overlay it on the MNI template. This can be done using some handy functions
from the from the
[`fsl.transform.flirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html) [`fsl.transform.flirt`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.flirt.html#)
and and
[`fsl.utils.image.resample`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.resample.html) [`fsl.utils.image.resample`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.utils.image.resample.html)
modules. modules.
Let's make sure we've got our source and reference images loaded: Let's make sure we've got our source and reference images loaded:
%% Cell type:code id: tags: %% Cell type:code id:3fc656bc tags:
``` ```
featdir = 'fmri.feat' featdir = 'fmri.feat'
tstat1 = Image(op.join(featdir, 'stats', 'tstat1')) tstat1 = Image(op.join(featdir, 'stats', 'tstat1'))
std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm'))) std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:03919e5c tags:
Now we'll load the `example_func2standard` FLIRT matrix, and adjust it so that Now we'll load the `example_func2standard` FLIRT matrix, and adjust it so that
it transforms from functional *world* coordinates into standard *world* it transforms from functional *world* coordinates into standard *world*
coordinates - this is what is expected by the `resampleToReference` function, coordinates, as this is what is expected by the `resampleToReference`
used below: function, used below. We can use the
[`fromFlirt`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.flirt.html#fsl.transform.flirt.fromFlirt)
function to do this for us:
%% Cell type:code id: tags: %% Cell type:code id:17c25065 tags:
``` ```
from fsl.transform.flirt import fromFlirt from fsl.transform.flirt import fromFlirt
func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat')) func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))
func2std = fromFlirt(func2std, tstat1, std, 'world', 'world') func2std = fromFlirt(func2std, tstat1, std, 'world', 'world')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:ea3917c9 tags:
Now we can use `resampleToReference` to resample our functional data into Now we can use `resampleToReference` to resample our functional data into
MNI152 space. This function returns a `numpy` array containing the resampled MNI152 space. This function returns a `numpy` array containing the resampled
data, and an adjusted voxel-to-world affine transformation. But in this case, 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: we know that the data will be aligned to MNI152, so we can ignore the affine:
%% Cell type:code id: tags: %% Cell type:code id:222a079c tags:
``` ```
from fsl.utils.image.resample import resampleToReference from fsl.utils.image.resample import resampleToReference
std_tstat1 = resampleToReference(tstat1, std, func2std)[0] std_tstat1 = resampleToReference(tstat1, std, func2std)[0]
std_tstat1 = Image(std_tstat1, header=std.header) std_tstat1 = Image(std_tstat1, header=std.header)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:ac2f748d tags:
Now that we have our t-statistic image in MNI152 space, we can plot it in Now that we have our t-statistic image in MNI152 space, we can plot it in
standard space using `matplotlib`: standard space using `matplotlib`:
%% Cell type:code id: tags: %% Cell type:code id:a7fe6c8b tags:
``` ```
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm')) std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))
std_tstat1 = std_tstat1.data std_tstat1 = std_tstat1.data
std_tstat1[std_tstat1 < 3] = 0 std_tstat1[std_tstat1 < 3] = 0
fig = ortho(std2mm.data, mnivoxels, cmap=plt.cm.gray) fig = ortho(std2mm.data, mnivoxels, cmap=plt.cm.gray)
fig = ortho(std_tstat1, mnivoxels, cmap=plt.cm.inferno, fig=fig, cursor=True) fig = ortho(std_tstat1, mnivoxels, cmap=plt.cm.inferno, fig=fig, cursor=True)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:aef19d0e tags:
In the example above, we resampled some data from functional space into 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 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 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. real world is full of lions and tigers and bears and warp fields.
The The
[`fsl.transform.fnirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.fnirt.html#fsl.transform.fnirt.fromFnirt) [`fsl.transform.fnirt`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.fnirt.html)
and and
[`fsl.transform.nonlinear`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.nonlinear.html) [`fsl.transform.nonlinear`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.nonlinear.html)
modules contain classes and functions for working with FNIRT-style warp fields modules contain classes and functions for working with FNIRT-style warp fields
(modules for working with lions, tigers, and bears are still under (modules for working with lions, tigers, and bears are still under
development). development).
Let's imagine that we have defined an ROI in MNI152 space, and we want to 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 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 the nonlinear structural to standard registration produced by FNIRT with the
linear functional to structural registration generated by FLIRT. First of linear functional to structural registration generated by FLIRT. First of
all, we'll load images from each of the functional, structural, and standard all, we'll load images from each of the functional, structural, and standard
spaces: spaces:
%% Cell type:code id: tags: %% Cell type:code id:16c1b772 tags:
``` ```
featdir = 'fmri.feat' featdir = 'fmri.feat'
func = Image(op.join(featdir, 'reg', 'example_func')) func = Image(op.join(featdir, 'reg', 'example_func'))
struc = Image(op.join(featdir, 'reg', 'highres')) struc = Image(op.join(featdir, 'reg', 'highres'))
std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm'))) std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:c5e907ee tags:
Now, let's say we have obtained our seed location in MNI152 coordinates. Let's Now, let's say we have obtained our seed location in MNI152 coordinates. Let's
convert them to MNI152 voxels just to double check: convert them to MNI152 voxels just to double check:
%% Cell type:code id: tags: %% Cell type:code id:8b7aa6be tags:
``` ```
seedmni = [-48, -74, -9] seedmni = [-48, -74, -9]
seedmnivox = transform(seedmni, std.getAffine('world', 'voxel')) seedmnivox = transform(seedmni, std.getAffine('world', 'voxel'))
ortho(std.data, seedmnivox, cursor=True) ortho(std.data, seedmnivox, cursor=True)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:56296715 tags:
Now we'll load the FNIRT warp field, which encodes a nonlinear transformation 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 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 *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*) convert the coefficient field into a *deformation* (a.k.a. *displacement*)
field. This takes a few seconds: field. This takes a few seconds:
%% Cell type:code id: tags: %% Cell type:code id:84a63882 tags:
``` ```
from fsl.transform.fnirt import readFnirt from fsl.transform.fnirt import readFnirt
from fsl.transform.nonlinear import coefficientFieldToDeformationField from fsl.transform.nonlinear import coefficientFieldToDeformationField
struc2std = readFnirt(op.join(featdir, 'reg', 'highres2standard_warp'), struc, std) struc2std = readFnirt(op.join(featdir, 'reg', 'highres2standard_warp'), struc, std)
struc2std = coefficientFieldToDeformationField(struc2std) struc2std = coefficientFieldToDeformationField(struc2std)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:901c7356 tags:
We'll also load our FLIRT functional to structural transformation, adjust it We'll also load our FLIRT functional to structural transformation, adjust it
so that it transforms between voxel coordinate systems instead of the FSL so that it transforms between voxel coordinate systems instead of the FSL
coordinate system, and invert so it can transform from structural voxels to coordinate system, and invert so it can transform from structural voxels to
functional voxels: functional voxels:
%% Cell type:code id: tags: %% Cell type:code id:17b25fa6 tags:
``` ```
from fsl.transform.affine import invert from fsl.transform.affine import invert
func2struc = np.loadtxt(op.join(featdir, 'reg', 'example_func2highres.mat')) func2struc = np.loadtxt(op.join(featdir, 'reg', 'example_func2highres.mat'))
func2struc = fromFlirt(func2struc, func, struc, 'voxel', 'voxel') func2struc = fromFlirt(func2struc, func, struc, 'voxel', 'voxel')
struc2func = invert(func2struc) struc2func = invert(func2struc)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:ce56d4e3 tags:
Now we can transform our seed coordinates from MNI152 space into functional 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 space in two stages. First, we'll use our deformation field to transform from
MNI152 space into structural space: MNI152 space into structural space, then we'll use our inverted FLIRT affine
to transform from structural space into functional space:
%% Cell type:code id: tags: %% Cell type:code id:448033ac tags:
``` ```
seedstruc = struc2std.transform(seedmni, 'world', 'voxel') seedstruc = struc2std.transform(seedmni, 'world', 'voxel')
seedfunc = transform(seedstruc, struc2func) seedfunc = transform(seedstruc, struc2func)
print('Seed location in MNI coordinates: ', seedmni) print('Seed location in MNI coordinates: ', seedmni)
print('Seed location in functional voxels:', seedfunc) print('Seed location in functional voxels:', seedfunc)
ortho(func.data, seedfunc, cursor=True) ortho(func.data, seedfunc, cursor=True)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:c9636bb0 tags:
> FNIRT warp fields kind of work backwards - we can use them to transform > FNIRT warp fields kind of work backwards - we can use them to transform
> reference coordinates into source coordinates, but would need to invert the > reference coordinates into source coordinates, but would need to invert the
> warp field using `invwarp` if we wanted to transform from source coordinates > warp field using `invwarp` if we wanted to transform from source coordinates
> into referemce coordinates. > into reference coordinates.
Of course, we can also use our deformation field to resample an image from Of course, we can also use our deformation field to resample an image from
structural space into MNI152 space. The `applyDeformation` function takes an structural space into MNI152 space. The `applyDeformation` function takes an
`Image` and a `DeformationField`, and returns a `numpy` array containing the `Image` and a `DeformationField`, and returns a `numpy` array containing the
resampled data. resampled data.
%% Cell type:code id: tags: %% Cell type:code id:a38b874a tags:
``` ```
from fsl.transform.nonlinear import applyDeformation from fsl.transform.nonlinear import applyDeformation
strucmni = applyDeformation(struc, struc2std) strucmni = applyDeformation(struc, struc2std)
# remove low-valued voxels, # remove low-valued voxels,
# just for visualisation below # just for visualisation below
strucmni[strucmni < 1] = 0 strucmni[strucmni < 1] = 0
fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray) fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray)
fig = ortho(strucmni, [45, 54, 45], fig=fig) fig = ortho(strucmni, [45, 54, 45], fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:f27e844c tags:
The `premat` option to `applyDeformation` can be used to specify our linear The `premat` option to `applyDeformation` can be used to specify our linear
functional to structural transformation, and hence resample a functional image functional to structural transformation, and hence resample a functional image
into MNI152 space: into MNI152 space:
%% Cell type:code id: tags: %% Cell type:code id:81b3d22b tags:
``` ```
tstatmni = applyDeformation(tstat1, struc2std, premat=func2struc) tstatmni = applyDeformation(tstat1, struc2std, premat=func2struc)
tstatmni[tstatmni < 3] = 0 tstatmni[tstatmni < 3] = 0
fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray) fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray)
fig = ortho(tstatmni, [45, 54, 45], fig=fig) fig = ortho(tstatmni, [45, 54, 45], fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:6da604af tags:
There are a few other useful functions tucked away in the There are a few other useful functions tucked away in the
[`fsl.utils.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.html) [`fsl.utils.image`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.utils.image.html)
and and
[`fsl.transform`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.html) [`fsl.transform`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.transform.html)
packages, with more to be added in the future. packages, with more to be added in the future.
<a class="anchor" id="fsl-wrapper-functions"></a> <a class="anchor" id="fsl-wrapper-functions"></a>
## FSL wrapper functions ## FSL wrapper functions
The The
[fsl.wrappers](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.wrappers.html) [`fsl.wrappers`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.wrappers.html)
package is the home of "wrapper" functions for a range of FSL tools. You can 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 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. constructing a command-line, or saving/loading input/output images.
> The `fsl.wrappers` functions also allow you to submit jobs to be run on the > The `fsl.wrappers` functions also allow you to submit jobs to be run on the
> cluster - this is described [below](#submitting-to-the-cluster). > cluster - this is described [below](#submitting-to-the-cluster).
You can use the FSL wrapper functions with file names, similar to calling the You can use the FSL wrapper functions with file names, similar to calling the
corresponding tool via the command-line: corresponding tool via the command-line:
%% Cell type:code id: tags: %% Cell type:code id:08d8e2a2 tags:
``` ```
from fsl.wrappers import robustfov from fsl.wrappers import robustfov
robustfov('bighead', 'bighead_cropped') robustfov('bighead', 'bighead_cropped')
render('bighead bighead_cropped -cm blue') render('bighead bighead_cropped -cm blue')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:00eb0f6c tags:
The `fsl.wrappers` functions strive to provide an interface which is as close The `fsl.wrappers` functions strive to provide an interface which is as close
as possible to the command-line tool - most functions use positional arguments as possible to the command-line tool - most functions use positional arguments
for required options, and keyword arguments for all other options, with for required options, and keyword arguments for all other options, with
argument names equivalent to command line option names. For example, the usage argument names equivalent to command line option names. For example, the usage
for the command-line `bet` tool is as follows: for the command-line `bet` tool is as follows:
> ``` > ```
> Usage: bet <input> <output> [options] > Usage: bet <input> <output> [options]
> >
> Main bet2 options: > Main bet2 options:
> -o generate brain surface outline overlaid onto original image > -o generate brain surface outline overlaid onto original image
> -m generate binary brain mask > -m generate binary brain mask
> -s generate approximate skull image > -s generate approximate skull image
> -n don't generate segmented brain image output > -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 > -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 > -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 > -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. > -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 So to use the `bet()` wrapper function, pass `<input>` and `<output>` as
positional arguments, and pass the additional options as keyword arguments: positional arguments, and pass the additional options as keyword arguments:
%% Cell type:code id: tags: %% Cell type:code id:383795d5 tags:
``` ```
from fsl.wrappers import bet from fsl.wrappers import bet
bet('bighead_cropped', 'bighead_cropped_brain', f=0.3, m=True, s=True) bet('bighead_cropped', 'bighead_cropped_brain', f=0.3, m=True, s=True)
render('bighead_cropped -b 40 ' render('bighead_cropped -b 40 '
'bighead_cropped_brain -cm hot ' 'bighead_cropped_brain -cm hot '
'bighead_cropped_brain_skull -ot mask -mc 0.4 0.4 1 ' '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') 'bighead_cropped_brain_mask -ot mask -mc 0 1 0 -o -w 5')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:e03ababe tags:
> Some FSL commands accept arguments which cannot be used as Python > Some FSL commands accept arguments which cannot be used as Python
> identifiers - for example, the `-2D` option to `flirt` cannot be used as an > 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 > 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: > this, an alias is used. So to set the `-2D` option to `flirt`, you can do this:
> >
> ``` > ```
> # "twod" applies the -2D flag > # "twod" applies the -2D flag
> flirt('source.nii.gz', 'ref.nii.gz', omat='src2ref.mat', twod=True) > flirt('source.nii.gz', 'ref.nii.gz', omat='src2ref.mat', twod=True)
> ``` > ```
> >
> Some of the `fsl.wrappers` functions also support aliases which may make > 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 > 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. > `m=True` or `mask=True` to apply the `-m` command line flag.
<a class="anchor" id="in-memory-images"></a> <a class="anchor" id="in-memory-images"></a>
### In-memory images ### In-memory images
It can be quite awkward to combine image processing with FSL tools and image It can be quite awkward to combine image processing with FSL tools and image
processing in Python. The `fsl.wrappers` package tries to make this a little processing in Python. The `fsl.wrappers` package tries to make this a little
easier for you - if you are working with image data in Python, you can pass easier for you - if you are working with image data in Python, you can pass
`Image` or `nibabel` objects directly into `fsl.wrappers` functions - they will `Image` or `nibabel` objects directly into `fsl.wrappers` functions - they will
be automatically saved to temporary files and passed to the underlying FSL be automatically saved to temporary files and passed to the underlying FSL
command: command:
%% Cell type:code id: tags: %% Cell type:code id:af58a85d tags:
``` ```
cropped = Image('bighead_cropped') cropped = Image('bighead_cropped')
bet(cropped, 'bighead_cropped_brain') bet(cropped, 'bighead_cropped_brain')
betted = Image('bighead_cropped_brain') betted = Image('bighead_cropped_brain')
fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray) fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)
fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig) fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:ea0678c8 tags:
<a class="anchor" id="loading-outputs-into-python"></a> <a class="anchor" id="loading-outputs-into-python"></a>
### Loading outputs into Python ### Loading outputs into Python
By using the special `fsl.wrappers.LOAD` symbol, you can also have any output By using the special `fsl.wrappers.LOAD` symbol, you can also have any output
files produced by the tool automatically loaded into memory for you: files produced by the tool automatically loaded into memory for you:
%% Cell type:code id: tags: %% Cell type:code id:6cf63c78 tags:
``` ```
from fsl.wrappers import LOAD from fsl.wrappers import LOAD
cropped = Image('bighead_cropped') cropped = Image('bighead_cropped')
# The loaded result is called "output", # The loaded result is called "output",
# because that is the name of the # because that is the name of the
# argument in the bet wrapper function. # argument in the bet wrapper function.
betted = bet(cropped, LOAD).output betted = bet(cropped, LOAD).output
fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray) fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)
fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig) fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:48111f56 tags:
You can use the `LOAD` symbol for any output argument - any output files which You can use the `LOAD` symbol for any output argument - any output files which
are loaded will be available through the return value of the wrapper function: are loaded will be available through the return value of the wrapper function:
%% Cell type:code id: tags: %% Cell type:code id:ca37247b tags:
``` ```
from fsl.wrappers import flirt from fsl.wrappers import flirt
std2mm = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm'))) std2mm = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))
tstat1 = Image(op.join('fmri.feat', 'stats', 'tstat1')) tstat1 = Image(op.join('fmri.feat', 'stats', 'tstat1'))
func2std = np.loadtxt(op.join('fmri.feat', 'reg', 'example_func2standard.mat')) func2std = np.loadtxt(op.join('fmri.feat', 'reg', 'example_func2standard.mat'))
aligned = flirt(tstat1, std2mm, applyxfm=True, init=func2std, out=LOAD) aligned = flirt(tstat1, std2mm, applyxfm=True, init=func2std, out=LOAD)
# Here the resampled tstat image # Here the resampled tstat image
# is called "out", because that # is called "out", because that
# is the name of the flirt argument. # is the name of the flirt argument.
aligned = aligned.out.data aligned = aligned.out.data
aligned[aligned < 1] = 0 aligned[aligned < 1] = 0
peakvox = np.abs(aligned).argmax() peakvox = np.abs(aligned).argmax()
peakvox = np.unravel_index(peakvox, aligned.shape) peakvox = np.unravel_index(peakvox, aligned.shape)
fig = ortho(std2mm .data, peakvox, cmap=plt.cm.gray) fig = ortho(std2mm .data, peakvox, cmap=plt.cm.gray)
fig = ortho(aligned.data, peakvox, cmap=plt.cm.inferno, fig=fig, cursor=True) fig = ortho(aligned.data, peakvox, cmap=plt.cm.inferno, fig=fig, cursor=True)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:a3534694 tags:
For tools like `bet` and `fast`, which expect an output *prefix* or 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 *basename*, you can just set the prefix to `LOAD` - all output files with that
prefix will be available in the object that is returned: prefix will be available in the object that is returned:
%% Cell type:code id: tags: %% Cell type:code id:d07d92d6 tags:
``` ```
img = Image('bighead_cropped') img = Image('bighead_cropped')
betted = bet(img, LOAD, f=0.3, mask=True) betted = bet(img, LOAD, f=0.3, mask=True)
fig = ortho(img .data, (80, 112, 85), cmap=plt.cm.gray) 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 .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) fig = ortho(betted.output_mask.data, (80, 112, 85), cmap=plt.cm.summer, fig=fig, alpha=0.5)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:f68f04fc tags:
<a class="anchor" id="the-fslmaths-wrapper"></a> <a class="anchor" id="the-fslmaths-wrapper"></a>
### The `fslmaths` wrapper ### The `fslmaths` wrapper
*Most* of the `fsl.wrappers` functions aim to provide an interface which is as *Most* of the `fsl.wrappers` functions aim to provide an interface which is as
close as possible to the underlying FSL tool. Ideally, if you read the 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 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 corresponding wrapper function. The wrapper for the `fslmaths` command is a
little different, however. It provides more of an object-oriented interface, little different, however. It provides more of an object-oriented interface,
which is hopefully a little easier to use from within Python. which is hopefully a little easier to use from within Python.
You can apply an `fslmaths` operation by specifying the input image, You can apply an `fslmaths` operation by specifying the input image,
*chaining* method calls together, and finally calling the `run()` method. For *chaining* method calls together, and finally calling the `run()` method. For
example: example:
%% Cell type:code id: tags: %% Cell type:code id:958a31a2 tags:
``` ```
from fsl.wrappers import fslmaths from fsl.wrappers import fslmaths
fslmaths('bighead_cropped') \ fslmaths('bighead_cropped') \
.mas( 'bighead_cropped_brain_mask') \ .mas( 'bighead_cropped_brain_mask') \
.run( 'bighead_cropped_brain') .run( 'bighead_cropped_brain')
render('bighead_cropped bighead_cropped_brain -cm hot') render('bighead_cropped bighead_cropped_brain -cm hot')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:2f6f5e4a tags:
Of course, you can also use the `fslmaths` wrapper with in-memory images: Of course, you can also use the `fslmaths` wrapper with in-memory images:
%% Cell type:code id: tags: %% Cell type:code id:75ada533 tags:
``` ```
wholehead = Image('bighead_cropped') wholehead = Image('bighead_cropped')
brainmask = Image('bighead_cropped_brain_mask') brainmask = Image('bighead_cropped_brain_mask')
eroded = fslmaths(brainmask).ero().ero().run() eroded = fslmaths(brainmask).ero().ero().run()
erodedbrain = fslmaths(wholehead).mas(eroded).run() erodedbrain = fslmaths(wholehead).mas(eroded).run()
fig = ortho(wholehead .data, (80, 112, 85), cmap=plt.cm.gray) 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(brainmask .data, (80, 112, 85), cmap=plt.cm.summer, fig=fig)
fig = ortho(erodedbrain.data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig) fig = ortho(erodedbrain.data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:9de21eab tags:
<a class="anchor" id="the-filetree"></a> <a class="anchor" id="the-filetree"></a>
## The `FileTree` ## The `FileTree`
The The
[`fsl.utils.filetree`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html) [`file_tree`](https://git.fmrib.ox.ac.uk/ndcn0236/file-tree)
library provides functionality which allows you to work with *structured data library provides functionality which allows you to work with *structured data
directories*, such as HCP or BIDS datasets. You can use `filetree` for both directories*, such as HCP or BIDS datasets. You can use `file_tree` for both
reading and for creating datasets. reading and for creating datasets.
This practical gives a very brief introduction to the `filetree` library - This practical gives a very brief introduction to the `file_tree` library -
refer to the [full refer to the [full
documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html) documentation](https://open.win.ox.ac.uk/pages/ndcn0236/file-tree/)
to get a feel for how powerful it can be. to get a feel for how powerful it can be.
<a class="anchor" id="describing-your-data"></a> <a class="anchor" id="describing-your-data"></a>
### Describing your data ### Describing your data
To introduce `filetree`, we'll begin with a small example. Imagine that we To introduce `file_tree`, we'll begin with a small example. Imagine that we
have a dataset which looks like this: have a dataset which looks like this:
> ``` > ```
> mydata > mydata
> ├── sub_A > ├── sub_A
> │ ├── ses_1 > │ ├── ses_1
> │ │ └── T1w.nii.gz > │ │ └── T1w.nii.gz
> │ ├── ses_2 > │ ├── ses_2
> │ │ └── T1w.nii.gz > │ │ └── T1w.nii.gz
> │ └── T2w.nii.gz > │ └── T2w.nii.gz
> ├── sub_B > ├── sub_B
> │ ├── ses_1 > │ ├── ses_1
> │ │ └── T1w.nii.gz > │ │ └── T1w.nii.gz
> │ ├── ses_2 > │ ├── ses_2
> │ │ └── T1w.nii.gz > │ │ └── T1w.nii.gz
> │ └── T2w.nii.gz > │ └── T2w.nii.gz
> └── sub_C > └── sub_C
> ├── ses_1 > ├── ses_1
> │ └── T1w.nii.gz > │ └── T1w.nii.gz
> ├── ses_2 > ├── ses_2
> │ └── T1w.nii.gz > │ └── T1w.nii.gz
> └── T2w.nii.gz > └── T2w.nii.gz
> ``` > ```
(Run the code cell below to create a dummy data set with the above structure): (Run the code cell below to create a dummy data set with the above structure):
%% Cell type:code id: tags: %% Cell type:code id:5381d777 tags:
``` ```
%%bash %%bash
for sub in A B C; do for sub in A B C; do
subdir=mydata/sub_$sub/ subdir=mydata/sub_$sub/
mkdir -p $subdir mkdir -p $subdir
cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $subdir/T2w.nii.gz cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $subdir/T2w.nii.gz
for ses in 1 2; do for ses in 1 2; do
sesdir=$subdir/ses_$ses/ sesdir=$subdir/ses_$ses/
mkdir $sesdir mkdir $sesdir
cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $sesdir/T1w.nii.gz cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $sesdir/T1w.nii.gz
done done
done done
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:8c317dfc tags:
To use `filetree` with this dataset, we must first describe its structure - we To use `file_tree` with this dataset, we must first describe its structure -
do this by creating a `.tree` file: we do this by creating a `.tree` file:
%% Cell type:code id: tags: %% Cell type:code id:da3970ca tags:
``` ```
%%writefile mydata.tree %%writefile mydata.tree
sub_{subject} sub_{subject}
T2w.nii.gz T2w.nii.gz
ses_{session} ses_{session}
T1w.nii.gz T1w.nii.gz
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:9018dc9e tags:
A `.tree` file is simply a description of the structure of your data A `.tree` file is simply a description of the structure of your data
directory - it describes the *file types* (also known as *templates*) which directory - it describes the *file types* (also known as *templates*) which
are present in the dataset (`T1w` and `T2w`), and the *variables* which are are present in the dataset (`T1w` and `T2w`), and the *variables* which are
implicitly present in the structure of the dataset (`subject` and `session`). implicitly present in the structure of the dataset (`subject` and `session`).
<a class="anchor" id="using-the-filetree"></a> <a class="anchor" id="using-the-filetree"></a>
### Using the `FileTree` ### Using the `FileTree`
Now that we have a `.tree` file which describe our data, we can create a Now that we have a `.tree` file which describe our data, we can create a
`FileTree` to work with it: `FileTree` to work with it:
%% Cell type:code id: tags: %% Cell type:code id:53118eba tags:
``` ```
from fsl.utils.filetree import FileTree from file_tree import FileTree
# Create a FileTree, giving # Create a FileTree, giving
# it our tree specification, # it our tree specification,
# and the path to our data. # and the path to our data.
tree = FileTree.read('mydata.tree', 'mydata') tree = FileTree.read('mydata.tree', 'mydata')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:96cc4535 tags:
We can list all of the T1 images via the `FileTree.get_all` method. The We can list all of the T1 images via the `FileTree.get_mult_glob` method. This
`glob_vars='all'` option tells the `FileTree` to fill in the `T1w` template method returns a [multi-dimensional
with all possible combinations of variables. The `FileTree.extract_variables` array](https://xarray.pydata.org/en/stable/index.html) of file names, where
method accepts a file path, and gives you back the variable values contained each dimension corresponds to one of the variables in your `.tree` file
within: (`subject` and `session` in this example):
%% Cell type:code id: tags: %% Cell type:code id:89325712 tags:
``` ```
for t1file in tree.get_all('T1w', glob_vars='all'): import itertools as it
fvars = tree.extract_variables('T1w', t1file)
print(t1file, fvars) t1files = tree.get_mult_glob('T1w')
subjects = t1files.coords['subject'].data
sessions = t1files.coords['session'].data
print('Subjects:', subjects)
print('Sessions:', sessions)
for subject, session in it.product(subjects, sessions):
t1file = t1files.loc[subject, session].item()
print(subject, session, t1file)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:b3080ecd tags:
The `FileTree.update` method allows you to "fill in" variable values; it 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 returns a new `FileTree` object which can be used on a selection of the
data set: data set:
%% Cell type:code id: tags: %% Cell type:code id:a45ea015 tags:
``` ```
treeA = tree.update(subject='A') treeA = tree.update(subject='A')
for t1file in treeA.get_all('T1w', glob_vars='all'): t1files = treeA.get_mult_glob('T1w')
fvars = treeA.extract_variables('T1w', t1file) for t1file in t1files:
print(t1file, fvars) print(t1file.session.item(), t1file.item())
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:44ca52c4 tags:
<a class="anchor" id="building-a-processing-pipeline-with-filetree"></a> <a class="anchor" id="building-a-processing-pipeline-with-filetree"></a>
### Building a processing pipeline with `FileTree` ### 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 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: our `.tree` definition to include the BET outputs:
%% Cell type:code id: tags: %% Cell type:code id:a33ed1ed tags:
``` ```
%%writefile mydata.tree %%writefile mydata.tree
sub_{subject} sub_{subject}
T2w.nii.gz T2w.nii.gz
ses_{session} ses_{session}
T1w.nii.gz T1w.nii.gz
T1w_brain.nii.gz T1w_brain.nii.gz
T1w_brain_mask.nii.gz T1w_brain_mask.nii.gz
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:fff7b7cc tags:
Now we can use the `FileTree` to generate the relevant file names for us, 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` which we can then pass on to BET. Here we'll use the `FileTree.update_glob`
method to create a sub-tree for each subject and each session: method, which tells the `FileTree` to scan the directory to identify all
`T1w` images. Then the `FileTree.iter` method allows us to create a sub-tree
for all combinations of `subject` and `session`:
%% Cell type:code id: tags: %% Cell type:code id:79767584 tags:
``` ```
from fsl.wrappers import bet from fsl.wrappers import bet
tree = FileTree.read('mydata.tree', 'mydata') tree = FileTree.read('mydata.tree', 'mydata')
for subtree in tree.get_all_trees('T1w', glob_vars='all'):
tree.update_glob("T1w", inplace=True)
for subtree in tree.iter('T1w'):
t1file = subtree.get('T1w') t1file = subtree.get('T1w')
t1brain = subtree.get('T1w_brain') t1brain = subtree.get('T1w_brain')
print('Running BET: {} -> {} ...'.format(t1file, t1brain)) print(f'Running BET: {t1file} -> {t1brain} ...')
bet(t1file, t1brain, mask=True) bet(t1file, t1brain, mask=True)
print('Done!') print('Done!')
example = tree.update(subject='A', session='1') example = tree.update(subject='A', session='1')
render('{} {} -ot mask -o -w 2 -mc 0 1 0'.format( render('{} {} -ot mask -o -w 2 -mc 0 1 0'.format(
example.get('T1w'), example.get('T1w'),
example.get('T1w_brain_mask'))) example.get('T1w_brain_mask')))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:6bb919b6 tags:
<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:
%% Cell type:code id: tags:
```
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'))
```
%% Cell type:markdown id: tags:
The `FileTreeQuery.query` method will return the paths to all existing files
which match a set of variable values:
%% Cell type:code id: tags:
```
print('All files for subject A')
for template in query.templates:
print(' {} files:'.format(template))
for match in query.query(template, subject='A'):
print(' ', match.filename)
```
%% Cell type:markdown id: tags:
<a class="anchor" id="calling-shell-commands"></a> <a class="anchor" id="calling-shell-commands"></a>
## Calling shell commands ## Calling shell commands
The The
[`fsl.utils.run`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.run.html) [`fsl.utils.run`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.utils.run.html)
module provides the `run` and `runfsl` functions, which are wrappers around module provides the `run` and `runfsl` functions, which are wrappers around
the built-in [`subprocess` the built-in [`subprocess`
library](https://docs.python.org/3/library/subprocess.html). library](https://docs.python.org/3/library/subprocess.html).
The default behaviour of `run` is to return the standard output of the The default behaviour of `run` is to return the standard output of the
command: command as a string, while also printing it normally:
%% Cell type:code id: tags: %% Cell type:code id:4acfb19a tags:
``` ```
from fsl.utils.run import run from fsl.utils.run import run
# You can pass the command # You can pass the command
# and its arguments as a single # and its arguments as a single
# string, or as a sequence # string, or as a sequence
print('Lines in this notebook:', run('wc -l fslpy.md').strip()) print('Lines in this notebook:', run('wc -l fslpy.md').strip())
print('Words in this notebook:', run(['wc', '-w', 'fslpy.md']).strip()) print('Words in this notebook:', run(['wc', '-w', 'fslpy.md']).strip())
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:01f20517 tags:
But you can control what `run` returns, depending on your needs. Let's create But you can control what `run` returns, depending on your needs. Let's create
a little script to demonstrate the options: a little script to demonstrate the options:
%% Cell type:code id: tags: %% Cell type:code id:5abe68ea tags:
``` ```
%%writefile mycmd %%writefile mycmd
#!/usr/bin/env bash #!/usr/bin/env bash
exitcode=$1 exitcode=$1
echo "Standard output!" echo "Standard output!"
echo "Standard error :(" >&2 echo "Standard error :(" >&2
exit $exitcode exit $exitcode
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:7bac50e6 tags:
And let's not forget to make it executable: And let's not forget to make it executable:
%% Cell type:code id: tags: %% Cell type:code id:68c2870c tags:
``` ```
!chmod a+x mycmd !chmod a+x mycmd
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:ac9875e2 tags:
You can use the `stdout`, `stderr` and `exitcode` arguments to control the You can use the `stdout`, `stderr` and `exitcode` arguments to control the
return value: return value:
%% Cell type:code id: tags: %% Cell type:code id:3f9f6b9b tags:
``` ```
print('run("./mycmd 0"): ', print('run("./mycmd 0"): ',
run("./mycmd 0").strip()) run("./mycmd 0").strip())
print('run("./mycmd 0", stdout=False): ', print('run("./mycmd 0", stdout=False): ',
run("./mycmd 0", stdout=False)) run("./mycmd 0", stdout=False))
print('run("./mycmd 0", exitcode=True):', print('run("./mycmd 0", exitcode=True):',
run("./mycmd 0", exitcode=True)) run("./mycmd 0", exitcode=True))
print('run("./mycmd 0", stdout=False, exitcode=True):', print('run("./mycmd 0", stdout=False, exitcode=True):',
run("./mycmd 0", stdout=False, exitcode=True)) run("./mycmd 0", stdout=False, exitcode=True))
print('run("./mycmd 0", stderr=True): ', print('run("./mycmd 0", stderr=True): ',
run("./mycmd 0", stderr=True)) run("./mycmd 0", stderr=True))
print('run("./mycmd 0", stdout=False, stderr=True): ', print('run("./mycmd 0", stdout=False, stderr=True): ',
run("./mycmd 0", stdout=False, stderr=True).strip()) run("./mycmd 0", stdout=False, stderr=True).strip())
print('run("./mycmd 0", stderr=True, exitcode=True):', print('run("./mycmd 0", stderr=True, exitcode=True):',
run("./mycmd 0", stderr=True, exitcode=True)) run("./mycmd 0", stderr=True, exitcode=True))
print('run("./mycmd 1", exitcode=True):', print('run("./mycmd 1", exitcode=True):',
run("./mycmd 1", exitcode=True)) run("./mycmd 1", exitcode=True))
print('run("./mycmd 1", stdout=False, exitcode=True):', print('run("./mycmd 1", stdout=False, exitcode=True):',
run("./mycmd 1", stdout=False, exitcode=True)) run("./mycmd 1", stdout=False, exitcode=True))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:57728f5a tags:
So if only one of `stdout`, `stderr`, or `exitcode` is `True`, `run` will only 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 return the corresponding value. Otherwise `run` will return a tuple which
contains the requested outputs. contains the requested outputs.
If you run a command which returns a non-0 exit code, the default behaviour 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: (if you don't set `exitcode=True`) is for a `RuntimeError` to be raised:
%% Cell type:code id: tags: %% Cell type:code id:e8e0fcd9 tags:
``` ```
run("./mycmd 99") run("./mycmd 99")
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:44a3a3cd tags:
<a class="anchor" id="the-runfsl-function"></a> <a class="anchor" id="the-runfsl-function"></a>
### The `runfsl` function ### The `runfsl` function
The `runfsl` function is a wrapper around `run` which simply makes sure that 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 the command you are calling is inside the `$FSLDIR/bin/` directory. It has the
same usage as the `run` function: same usage as the `run` function:
%% Cell type:code id: tags: %% Cell type:code id:48c662a4 tags:
``` ```
from fsl.utils.run import runfsl from fsl.utils.run import runfsl
runfsl('bet bighead_cropped bighead_cropped_brain') runfsl('bet bighead_cropped bighead_cropped_brain')
runfsl('fslroi bighead_cropped_brain bighead_slices 0 -1 0 -1 90 3') runfsl('fslroi bighead_cropped_brain bighead_slices 0 -1 0 -1 90 3')
runfsl('fast -o bighead_fast bighead_slices') runfsl('fast -o bighead_fast bighead_slices')
render('-vl 80 112 91 -xh -yh ' render('-vl 80 112 91 -xh -yh '
'bighead_cropped ' 'bighead_cropped '
'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 ' 'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '
'bighead_fast_seg.nii.gz -ot label -o') 'bighead_fast_seg.nii.gz -ot label -o')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:69321596 tags:
<a class="anchor" id="submitting-to-the-cluster"></a> <a class="anchor" id="submitting-to-the-cluster"></a>
### Submitting to the cluster ### Submitting to the cluster
Both the `run` and `runfsl` accept an argument called `submit`, which allows 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` you to submit jobs to be executed on the cluster via the FSL `fsl_sub`
command. command.
> Cluster submission is handled by the > Cluster submission is handled by
> [`fsl.utils.fslsub`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html) > [`fsl_sub`](https://git.fmrib.ox.ac.uk/fsl/fsl_sub) - in addition to
> module - it contains lower level functions for managing and querying jobs > providing the `fsl_sub` command, it contains Python functions for managing
> that have been submitted to the cluster. The functions defined in this > and querying jobs that have been submitted to the cluster. The functions
> module can be used directly if you have more complicated requirements. > defined in the `fsl_sub` library can be used directly if you have more
> complicated requirements.
The semantics of the `run` and `runfsl` functions are slightly different when The semantics of the `run` and `runfsl` functions are slightly different when
you use the `submit` option - when you submit a job, the `run`/`runfsl` 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 functions will return immediately, and will return a string containing the job
ID: ID:
%% Cell type:code id: tags: %% Cell type:code id:f8ce946d tags:
``` ```
jobid = run('ls', submit=True) jobid = run('ls', submit=True)
print('Job ID:', jobid) print('Job ID:', jobid)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:3838f821 tags:
Once the job finishes, we should be able to read the usual `.o` and `.e` Once the job finishes, we should be able to read the usual `.o` and `.e`
files: files:
%% Cell type:code id: tags: %% Cell type:code id:0c1b4c6f tags:
``` ```
stdout = f'ls.o{jobid}' stdout = f'ls.o{jobid}'
print('Job output') print('Job output')
print(open(stdout).read()) print(open(stdout).read())
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:626dff1a tags:
All of the `fsl.wrappers` functions also accept the `submit` argument: All of the `fsl.wrappers` functions also accept the `submit` argument:
%% Cell type:code id: tags: %% Cell type:code id:2ae56b20 tags:
``` ```
jobid = bet('bighead', 'bighead_brain', submit=True) jobid = bet('bighead', 'bighead_brain', submit=True)
print('Job ID:', jobid) print('Job ID:', jobid)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:a2af7f93 tags:
> But an error will occur if you try to pass in-memory images, or `LOAD` any > 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`. > outputs when you call a wrapper function with `submit=True`.
After submitting a job, you can use the `hold` function to wait until a job After submitting a job, you can use the `hold` function to wait until a job
has completed: has completed:
%% Cell type:code id: tags: %% Cell type:code id:4e4f16dc tags:
``` ```
from fsl.utils.run import hold from fsl.utils.run import hold
jobid = bet('bighead', 'bighead_brain', submit=True) jobid = bet('bighead', 'bighead_brain', submit=True)
print('Job ID:', jobid) print('Job ID:', jobid)
hold(jobid) hold(jobid)
print('Done!') print('Done!')
render('bighead bighead_brain -cm hot') render('bighead bighead_brain -cm hot')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:d583e7a6 tags:
When you use `submit=True`, you can also specify cluster submission options - When you use `submit=True`, you can also specify cluster submission options -
you can include any arguments that are accepted by the you can include any arguments that are accepted by the
[`fslsub.submit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html#fsl.utils.fslsub.submit) [`fsl_sub`](https://git.fmrib.ox.ac.uk/fsl/fsl_sub) command - for example, if
function you call:
%% Cell type:code id: tags: > `runfsl('command', submit=True, queue='short.q', jobhold=<some-job-id>)`
this will be translated into a command-line call:
> `fsl_sub command --queue=short.q --jobhold=<some-job-id>`
%% Cell type:code id:5b8cfcb4 tags:
``` ```
jobs = [] jobs = []
jobs.append(runfsl('robustfov -i bighead -r bighead_cropped', submit=True, queue='short.q')) jobs.append(runfsl('robustfov -i 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('bet bighead_cropped bighead_brain', submit=True, queue='short.q', jobhold=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('fslroi bighead_brain bighead_slices 0 -1 111 3 0 -1', submit=True, queue='short.q', jobhold=jobs[-1]))
jobs.append(runfsl('fast -o bighead_fast bighead_slices', submit=True, queue='short.q', wait_for=jobs[-1])) jobs.append(runfsl('fast -o bighead_fast bighead_slices', submit=True, queue='short.q', jobhold=jobs[-1]))
print('Waiting for', jobs, '...') print('Waiting for', jobs, '...')
hold(jobs) hold(jobs)
render('-vl 80 112 91 -xh -zh -hc ' render('-vl 80 112 91 -xh -zh -hc '
'bighead_brain ' 'bighead_brain '
'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 ' 'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '
'bighead_fast_seg.nii.gz -ot label -o') 'bighead_fast_seg.nii.gz -ot label -o')
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:02ef68d6 tags:
> *Note:* If you are using a version of FSL older than 6.0.5.1, you may need
> to change `jobhold` to `wait_for` in the code block above.
<a class="anchor" id="redirecting-output"></a> <a class="anchor" id="redirecting-output"></a>
### Redirecting output ### Redirecting output
The `log` option, accepted by both `run` and `fslrun`, allows for more The `log` option, accepted by both `run` and `runfsl`, allows for more
fine-grained control over what is done with the standard output and error fine-grained control over what is done with the standard output and error
streams. streams.
You can use `'tee'` to redirect the standard output and error streams of the The default behaviour of `run`/`runfsl` is to redirect the standard output and
command to the standard output and error streams of the calling command (your error streams of the command to the standard output and error streams of the
python script): calling command (your python script). However you can disable this via the
`tee` option:
%% Cell type:code id: tags: %% Cell type:code id:d2626c3a tags:
``` ```
print('Teeing:') _ = run('./mycmd 0', log={'tee' : False})
_ = run('./mycmd 0', log={'tee' : True})
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:08b26a21 tags:
Or you can use `'stdout'` and `'stderr'` to redirect the standard output and You can also use `'stdout'` and `'stderr'` to redirect the standard output and
error streams of the command to files: error streams of the command to separate files:
%% Cell type:code id: tags: %% Cell type:code id:97e3464c tags:
``` ```
with open('stdout.log', 'wt') as o, \ with open('stdout.log', 'wt') as o, \
open('stderr.log', 'wt') as e: open('stderr.log', 'wt') as e:
run('./mycmd 0', log={'stdout' : o, 'stderr' : e}) run('./mycmd 0', log={'tee' : False, 'stdout' : o, 'stderr' : e})
print('\nRedirected stdout:') print('\nRedirected stdout:')
!cat stdout.log !cat stdout.log
print('\nRedirected stderr:') print('\nRedirected stderr:')
!cat stderr.log !cat stderr.log
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:059b146a tags:
Finally, you can use `'cmd'` to log the command itself to a file (useful for Finally, you can use `'cmd'` to log the command itself to a file (useful for
pipeline logging): pipeline logging):
%% Cell type:code id: tags: %% Cell type:code id:d4b264af tags:
``` ```
with open('commands.log', 'wt') as cmdlog: with open('commands.log', 'wt') as cmdlog:
run('./mycmd 0', log={'cmd' : cmdlog}) run('./mycmd 0', log={'tee' : False, 'cmd' : cmdlog})
run('wc -l fslpy.md', log={'cmd' : cmdlog}) run('wc -l fslpy.md', log={'tee' : False, 'cmd' : cmdlog})
print('\nCommand log:') print('\nCommand log:')
!cat commands.log !cat commands.log
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:128cbef5 tags:
<a class="anchor" id="fsl-atlases"></a> <a class="anchor" id="fsl-atlases"></a>
## FSL atlases ## FSL atlases
The The
[`fsl.data.atlases`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.atlases.html) [`fsl.data.atlases`](https://open.win.ox.ac.uk/pages/fsl/fslpy/fsl.data.atlases.html)
module provides access to all of the atlas images that are stored in the 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 `$FSLDIR/data/atlases/` directory of a standard FSL installation. It can be
used to load and query probabilistic and label-based atlases. used to load and query probabilistic and label-based atlases.
The `atlases` module needs to be initialised using the `rescanAtlases` function: The `atlases` module needs to be initialised using the `rescanAtlases` function:
%% Cell type:code id: tags: %% Cell type:code id:b97c19c5 tags:
``` ```
import fsl.data.atlases as atlases import fsl.data.atlases as atlases
atlases.rescanAtlases() atlases.rescanAtlases()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:1bfdf4a4 tags:
<a class="anchor" id="querying-atlases"></a> <a class="anchor" id="querying-atlases"></a>
### Querying atlases ### Querying atlases
You can list all of the available atlases using `listAtlases`: You can list all of the available atlases using `listAtlases`:
%% Cell type:code id: tags: %% Cell type:code id:193049ea tags:
``` ```
for desc in atlases.listAtlases(): for desc in atlases.listAtlases():
print(desc) print(desc)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:4163e9c1 tags:
`listAtlases` returns a list of `AtlasDescription` objects, each of which `listAtlases` returns a list of `AtlasDescription` objects, each of which
contains descriptive information about one atlas. You can retrieve the contains descriptive information about one atlas. You can retrieve the
`AtlasDescription` for a specific atlas via the `getAtlasDescription` `AtlasDescription` for a specific atlas via the `getAtlasDescription`
function: function:
%% Cell type:code id: tags: %% Cell type:code id:83d75569 tags:
``` ```
desc = atlases.getAtlasDescription('harvardoxford-cortical') desc = atlases.getAtlasDescription('harvardoxford-cortical')
print(desc.name) print(desc.name)
print(desc.atlasID) print(desc.atlasID)
print(desc.specPath) print(desc.specPath)
print(desc.atlasType) print(desc.atlasType)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:01311333 tags:
Each `AtlasDescription` maintains a list of `AtlasLabel` objects, each of Each `AtlasDescription` maintains a list of `AtlasLabel` objects, each of
which represents one region that is defined in the atlas. You can access all which represents one region that is defined in the atlas. You can access all
of the `AtlasLabel` objects via the `labels` attribute: of the `AtlasLabel` objects via the `labels` attribute:
%% Cell type:code id: tags: %% Cell type:code id:6914ad40 tags:
``` ```
for lbl in desc.labels[:5]: for lbl in desc.labels[:5]:
print(lbl) print(lbl)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:0630b809 tags:
Or you can retrieve a specific label using the `find` method: Or you can retrieve a specific label using the `find` method:
%% Cell type:code id: tags: %% Cell type:code id:afb6cd3f tags:
``` ```
# search by region name # search by region name
print(desc.find(name='Occipital Pole')) print(desc.find(name='Occipital Pole'))
# or by label value # or by label value
print(desc.find(value=48)) print(desc.find(value=48))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:4778d6e0 tags:
<a class="anchor" id="loading-atlas-images"></a> <a class="anchor" id="loading-atlas-images"></a>
### Loading atlas images ### Loading atlas images
The `loadAtlas` function can be used to load the atlas image: The `loadAtlas` function can be used to load the atlas image:
%% Cell type:code id: tags: %% Cell type:code id:65e7bb65 tags:
``` ```
# For probabilistic atlases, you # For probabilistic atlases, you
# can ask for the 3D ROI image # can ask for the 3D ROI image
# by setting loadSummary=True. # by setting loadSummary=True.
# You can also request a # You can also request a
# resolution - by default the # resolution - by default the
# highest resolution version # highest resolution version
# will be loaded. # will be loaded.
lblatlas = atlases.loadAtlas('harvardoxford-cortical', lblatlas = atlases.loadAtlas('harvardoxford-cortical',
loadSummary=True, loadSummary=True,
resolution=2) resolution=2)
# By default you will get the 4D # By default you will get the 4D
# probabilistic atlas image (for # probabilistic atlas image (for
# atlases for which this is # atlases for which this is
# available). # available).
probatlas = atlases.loadAtlas('harvardoxford-cortical', probatlas = atlases.loadAtlas('harvardoxford-cortical',
resolution=2) resolution=2)
print(lblatlas) print(lblatlas)
print(probatlas) print(probatlas)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:548fdc41 tags:
<a class="anchor" id="working-with-atlases"></a> <a class="anchor" id="working-with-atlases"></a>
### Working with atlases ### Working with atlases
Both `LabelAtlas` and `ProbabilisticAtlas` objects have a method called `get`, Both `LabelAtlas` and `ProbabilisticAtlas` objects have a method called `get`,
which can be used to extract ROI images for a specific region: which can be used to extract ROI images for a specific region:
%% Cell type:code id: tags: %% Cell type:code id:5e6104d3 tags:
``` ```
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm')) std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))
frontal = lblatlas.get(name='Frontal Pole').data frontal = lblatlas.get(name='Frontal Pole').data
frontal = np.ma.masked_where(frontal < 1, frontal) frontal = np.ma.masked_where(frontal < 1, frontal)
fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray) fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)
fig = ortho(frontal, (45, 54, 45), cmap=plt.cm.winter, fig=fig) fig = ortho(frontal, (45, 54, 45), cmap=plt.cm.winter, fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:ff93344d tags:
Calling `get` on a `ProbabilisticAtlas` will return a probability image: Calling `get` on a `ProbabilisticAtlas` will return a probability image:
%% Cell type:code id: tags: %% Cell type:code id:46250e83 tags:
``` ```
stddir = op.expandvars('${FSLDIR}/data/standard/') stddir = op.expandvars('${FSLDIR}/data/standard/')
std2mm = Image(op.join(stddir, 'MNI152_T1_2mm')) std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))
frontal = probatlas.get(name='Frontal Pole').data frontal = probatlas.get(name='Frontal Pole').data
frontal = np.ma.masked_where(frontal < 1, frontal) frontal = np.ma.masked_where(frontal < 1, frontal)
fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray) fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)
fig = ortho(frontal, (45, 54, 45), cmap=plt.cm.inferno, fig=fig) fig = ortho(frontal, (45, 54, 45), cmap=plt.cm.inferno, fig=fig)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:befac68b tags:
The `get` method can be used to retrieve an image for a region by: The `get` method can be used to retrieve an image for a region by:
- an `AtlasLabel` object - an `AtlasLabel` object
- The region index - The region index
- The region value - The region value
- The region name - The region name
`LabelAtlas` objects have a method called `label`, which can be used to `LabelAtlas` objects have a method called `label`, which can be used to
interrogate the atlas at specific locations: interrogate the atlas at specific locations:
%% Cell type:code id: tags: %% Cell type:code id:2e86834e tags:
``` ```
# The label method accepts 3D # The label method accepts 3D
# voxel or world coordinates # voxel or world coordinates
val = lblatlas.label((25, 52, 43), voxel=True) val = lblatlas.label((25, 52, 43), voxel=True)
lbl = lblatlas.find(value=val) lbl = lblatlas.find(value=val)
print('Region at voxel [25, 52, 43]: {} [{}]'.format(val, lbl.name)) print(f'Region at voxel [25, 52, 43]: {val} [{lbl.name}]')
# or a 3D weighted or binary mask # or a 3D weighted or binary mask
mask = np.zeros(lblatlas.shape) mask = np.zeros(lblatlas.shape)
mask[30:60, 30:60, 30:60] = 1 mask[30:60, 30:60, 30:60] = 1
mask = Image(mask, header=lblatlas.header) mask = Image(mask, header=lblatlas.header)
lbls, props = lblatlas.label(mask) lbls, props = lblatlas.label(mask)
print('Labels in mask:') print('Labels in mask:')
for lbl, prop in zip(lbls, props): for lbl, prop in zip(lbls, props):
lblname = lblatlas.find(value=lbl).name lblname = lblatlas.find(value=lbl).name
print(' {} [{}]: {:0.2f}%'.format(lbl, lblname, prop)) print(f' {lbl} [{lblname}]: {prop:0.2f}%')
fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)
fig = ortho(mask.data, (45, 54, 45), cmap=plt.cm.winter, fig=fig, alpha=0.5)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id:523d6346 tags:
`ProbabilisticAtlas` objects have an analogous method called `values`: `ProbabilisticAtlas` objects have an analogous method called `values`:
%% Cell type:code id: tags: %% Cell type:code id:daf900b4 tags:
``` ```
vals = probatlas.values((25, 52, 43), voxel=True) vals = probatlas.values((25, 52, 43), voxel=True)
print('Regions at voxel [25, 52, 43]:') print('Regions at voxel [25, 52, 43]:')
for idx, val in enumerate(vals): for idx, val in enumerate(vals):
if val > 0: if val > 0:
lbl = probatlas.find(index=idx) lbl = probatlas.find(index=idx)
print(' {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val)) print(f' {lbl.value} [{lbl.name}]: {val:0.2f}%')
print('Average proportions of regions within mask:') print('Average proportions of regions within mask:')
vals = probatlas.values(mask) vals = probatlas.values(mask)
for idx, val in enumerate(vals): for idx, val in enumerate(vals):
if val > 0: if val > 0:
lbl = probatlas.find(index=idx) lbl = probatlas.find(index=idx)
print(' {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val)) print(f' {lbl.value} [{lbl.name}]: {val:0.2f}%')
``` ```
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment