{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# `fslpy`\n", "\n", "\n", "**Important:** Portions of this practical require `fslpy` 2.9.0, due to be\n", "released with FSL 6.0.4, in Spring 2020.\n", "\n", "\n", "[`fslpy`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/) is a\n", "Python library which is built into FSL, and contains a range of functionality\n", "for working with FSL and with neuroimaging data from Python.\n", "\n", "\n", "This practical highlights some of the most useful features provided by\n", "`fslpy`. You may find `fslpy` useful if you are writing Python code to\n", "perform analyses and image processing in conjunction with FSL.\n", "\n", "\n", "* [The `Image` class, and other data types](#the-image-class-and-other-data-types)\n", " * [Creating images](#creating-images)\n", " * [Working with image data](#working-with-image-data)\n", " * [Loading other file types](#loading-other-file-types)\n", " * [NIfTI coordinate systems](#nifti-coordinate-systems)\n", " * [Transformations and resampling](#transformations-and-resampling)\n", "* [FSL wrapper functions](#fsl-wrapper-functions)\n", " * [In-memory images](#in-memory-images)\n", " * [Loading outputs into Python](#loading-outputs-into-python)\n", " * [The `fslmaths` wrapper](#the-fslmaths-wrapper)\n", "* [The `FileTree`](#the-filetree)\n", " * [Describing your data](#describing-your-data)\n", " * [Using the `FileTree`](#using-the-filetree)\n", " * [Building a processing pipeline with `FileTree`](#building-a-processing-pipeline-with-filetree)\n", " * [The `FileTreeQuery`](#the-filetreequery)\n", "* [Calling shell commands](#calling-shell-commands)\n", " * [The `runfsl` function](#the-runfsl-function)\n", " * [Submitting to the cluster](#submitting-to-the-cluster)\n", " * [Redirecting output](#redirecting-output)\n", "* [FSL atlases](#fsl-atlases)\n", " * [Querying atlases](#querying-atlases)\n", " * [Loading atlas images](#loading-atlas-images)\n", " * [Working with atlases](#working-with-atlases)\n", "\n", "\n", "> **Note**: `fslpy` is distinct from `fslpython` - `fslpython` is the Python\n", "> environment that is baked into FSL. `fslpy` is a Python library which is\n", "> installed into the `fslpython` environment.\n", "\n", "\n", "Let's start with some standard imports and environment set-up:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt\n", "import os\n", "import os.path as op\n", "import nibabel as nib\n", "import numpy as np\n", "import warnings\n", "warnings.filterwarnings(\"ignore\")\n", "np.set_printoptions(suppress=True, precision=4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And a little function that we can use to generate a simple orthographic plot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def ortho(data, voxel, fig=None, cursor=False, **kwargs):\n", " \"\"\"Simple orthographic plot of a 3D array using matplotlib.\n", "\n", " :arg data: 3D numpy array\n", " :arg voxel: XYZ coordinates for each slice\n", " :arg fig: Existing figure and axes for overlay plotting\n", " :arg cursor: Show a cursor at the `voxel`\n", "\n", " All other arguments are passed through to the `imshow` function.\n", "\n", " :returns: The figure and orthogaxes (which can be passed back in as the\n", " `fig` argument to plot overlays).\n", " \"\"\"\n", "\n", " voxel = [int(round(v)) for v in voxel]\n", "\n", " data = np.asanyarray(data, dtype=np.float)\n", " data[data <= 0] = np.nan\n", "\n", " x, y, z = voxel\n", " xslice = np.flipud(data[x, :, :].T)\n", " yslice = np.flipud(data[:, y, :].T)\n", " zslice = np.flipud(data[:, :, z].T)\n", "\n", " if fig is None:\n", " fig = plt.figure()\n", " xax = fig.add_subplot(1, 3, 1)\n", " yax = fig.add_subplot(1, 3, 2)\n", " zax = fig.add_subplot(1, 3, 3)\n", " else:\n", " fig, xax, yax, zax = fig\n", "\n", " xax.imshow(xslice, **kwargs)\n", " yax.imshow(yslice, **kwargs)\n", " zax.imshow(zslice, **kwargs)\n", "\n", " if cursor:\n", " cargs = {'color' : (0, 1, 0), 'linewidth' : 1}\n", " xax.axvline( y, **cargs)\n", " xax.axhline(data.shape[2] - z, **cargs)\n", " yax.axvline( x, **cargs)\n", " yax.axhline(data.shape[2] - z, **cargs)\n", " zax.axvline( x, **cargs)\n", " zax.axhline(data.shape[1] - y, **cargs)\n", "\n", " for ax in (xax, yax, zax):\n", " ax.set_xticks([])\n", " ax.set_yticks([])\n", " fig.tight_layout(pad=0)\n", "\n", " return (fig, xax, yax, zax)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And another function which uses FSLeyes for more complex plots:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def render(cmdline):\n", "\n", " import shlex\n", " import IPython.display as display\n", "\n", " prefix = '-of screenshot.png -hl -c 2 '\n", "\n", " try:\n", " from fsleyes.render import main\n", " main(shlex.split(prefix + cmdline))\n", "\n", " except ImportError:\n", " # fall-back for macOS - we have to run\n", " # FSLeyes render in a separate process\n", " from fsl.utils.run import runfsl\n", " prefix = 'render ' + prefix\n", " runfsl(prefix + cmdline, env={})\n", "\n", " return display.Image('screenshot.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## The `Image` class, and other data types\n", "\n", "\n", "The\n", "[`fsl.data.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)\n", "module provides the `Image` class, which sits on top of `nibabel` and contains\n", "some handy functionality if you need to work with coordinate transformations,\n", "or do some FSL-specific processing. The `Image` class provides features such\n", "as:\n", "\n", "- Support for NIFTI1, NIFTI2, and ANALYZE image files\n", "- Access to affine transformations between the voxel, FSL and world coordinate\n", " systems\n", "- Ability to load metadata from BIDS sidecar files\n", "\n", "\n", "> The `Image` class behaves differently to the `nibabel.Nifti1Image`. For\n", "> example, when you create an `Image` object, the default behaviour is to load\n", "> the image data into memory. This is configurable however; take a look at\n", "> [the\n", "> documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.image.html#fsl.data.image.Image)\n", "> to explore all of the options.\n", "\n", "\n", "Some simple image processing routines are also provided - these are covered\n", "[below](#image-processing).\n", "\n", "\n", "\n", "### Creating images\n", "\n", "\n", "It's easy to create an `Image` - you can create one from a file name:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.data.image import Image\n", "\n", "stddir = op.expandvars('${FSLDIR}/data/standard/')\n", "\n", "# load a FSL image - the file\n", "# suffix is optional, just like\n", "# in real FSL-land!\n", "std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))\n", "print(std1mm)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can create an `Image` from an existing `nibabel` image:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# load a nibabel image, and\n", "# convert it into an FSL image\n", "nibimg = nib.load(op.join(stddir, 'MNI152_T1_1mm.nii.gz'))\n", "std1mm = Image(nibimg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or you can create an `Image` from a `numpy` array:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = np.zeros((182, 218, 182))\n", "img = Image(data, xform=np.eye(4))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you have generated some data from another `Image` (or from a\n", "`nibabel.Nifti1Image`) you can use the `header` option to set\n", "the header information on the new image:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img = Image(data, header=std1mm.header)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can save an image to file via the `save` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img.save('empty')\n", "!ls" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`Image` objects have all of the attributes you might expect:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stddir = op.expandvars('${FSLDIR}/data/standard/')\n", "std1mm = Image(op.join(stddir, 'MNI152_T1_1mm'))\n", "\n", "print('name: ', std1mm.name)\n", "print('file: ', std1mm.dataSource)\n", "print('NIfTI version:', std1mm.niftiVersion)\n", "print('ndim: ', std1mm.ndim)\n", "print('shape: ', std1mm.shape)\n", "print('dtype: ', std1mm.dtype)\n", "print('nvals: ', std1mm.nvals)\n", "print('pixdim: ', std1mm.pixdim)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "and a number of useful methods:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n", "mask2mm = Image(op.join(stddir, 'MNI152_T1_2mm_brain_mask'))\n", "\n", "print(std1mm.sameSpace(std2mm))\n", "print(std2mm.sameSpace(mask2mm))\n", "print(std2mm.getAffine('voxel', 'world'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An `Image` object is a high-level wrapper around a `nibabel` image object -\n", "you can always work directly with the `nibabel` object via the `nibImage`\n", "attribute:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(std2mm)\n", "print(std2mm.nibImage)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Working with image data\n", "\n", "\n", "You can get the image data as a `numpy` array via the `data` attribute:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "data = std2mm.data\n", "print(data.min(), data.max())\n", "ortho(data, (45, 54, 45))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> Note that `Image.data` will give you the data in its underlying type, unlike\n", "> the `nibabel.get_fdata` method, which up-casts image data to floating-point.\n", "\n", "\n", "You can also read and write data directly via the `Image` object:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "slc = std2mm[:, :, 45]\n", "std2mm[0:10, :, :] *= 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Doing so has some advantages that may or may not be useful, depending on your\n", "use-case:\n", " - The image data will be kept on disk - only the parts that you access will\n", " be loaded into RAM (you will also need to pass`loadData=False` when creating\n", " the `Image` to achieve this).\n", " - The `Image` object will keep track of modifications to the data - this can\n", " be queried via the `saveState` attribute.\n", "\n", "\n", "\n", "### Loading other file types\n", "\n", "\n", "The\n", "[`fsl.data`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.html#module-fsl.data)\n", "package has a number of other classes for working with different types of FSL\n", "and neuroimaging data. Most of these are higher-level wrappers around the\n", "corresponding `nibabel` types:\n", "\n", "* The\n", " [`fsl.data.bitmap.Bitmap`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.bitmap.html)\n", " class can be used to load a bitmap image (e.g. `jpg`, `png`, etc) and\n", " convert it to a NIfTI image.\n", "* The\n", " [`fsl.data.dicom.DicomImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dicom.html)\n", " class uses `dcm2niix` to load NIfTI images contained within a DICOM\n", " directory*.\n", "* The\n", " [`fsl.data.mghimage.MGHImage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.mghimage.html)\n", " class can be used too load `.mgh`/`.mgz` images (they are converted into\n", " NIfTI images).\n", "* The\n", " [`fsl.data.dtifit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.dtifit.html)\n", " module contains functions for loading and working with the output of the\n", " FSL `dtifit` tool.\n", "* The\n", " [`fsl.data.featanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featanalysis.html),\n", " [`fsl.data.featimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featimage.html),\n", " and\n", " [`fsl.data.featdesign`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.featdesign.html)\n", " modules contain classes and functions for loading data from FEAT\n", " directories.\n", "* Similarly, the\n", " [`fsl.data.melodicanalysis`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicanalysis.html)\n", " and\n", " [`fsl.data.melodicimage`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.melodicimage.html)\n", " modules contain classes and functions for loading data from MELODIC\n", " directories.\n", "* The\n", " [`fsl.data.gifti`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.gifti.html),\n", " [`fsl.data.freesurfer`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.freesurfer.html),\n", " and\n", " [`fsl.data.vtk`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.vtk.html)\n", " modules contain functionality form loading surface data from GIfTI,\n", " freesurfer, and ASCII VTK files respectively.\n", "\n", "\n", "> *You must make sure that\n", "> [`dcm2niix`](https://github.com/rordenlab/dcm2niix/) is installed on your\n", "> system in order to use this class.\n", "\n", "\n", "\n", "### NIfTI coordinate systems\n", "\n", "\n", "The `Image.getAffine` method gives you access to affine transformations which\n", "can be used to convert coordinates between the different coordinate systems\n", "associated with a NIfTI image. Have some MNI coordinates you'd like to convert\n", "to voxels? Easy!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stddir = op.expandvars('${FSLDIR}/data/standard/')\n", "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n", "\n", "mnicoords = np.array([[0, 0, 0],\n", " [0, -18, 18]])\n", "\n", "world2vox = std2mm.getAffine('world', 'voxel')\n", "vox2world = std2mm.getAffine('voxel', 'world')\n", "\n", "# Apply the world->voxel\n", "# affine to the coordinates\n", "voxcoords = (np.dot(world2vox[:3, :3], mnicoords.T)).T + world2vox[:3, 3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code above is a bit fiddly, so instead of figuring it out, you can just\n", "use the\n", "[`affine.transform`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.affine.html#fsl.transform.affine.transform)\n", "function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.transform.affine import transform\n", "\n", "voxcoords = transform(mnicoords, world2vox)\n", "\n", "# just to double check, let's transform\n", "# those voxel coordinates back into world\n", "# coordinates\n", "backtomni = transform(voxcoords, vox2world)\n", "\n", "for m, v, b in zip(mnicoords, voxcoords, backtomni):\n", " print(m, '->', v, '->', b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> The `Image.getAffine` method can give you transformation matrices\n", "> between any of these coordinate systems:\n", ">\n", "> - `'voxel'`: Image data voxel coordinates\n", "> - `'world'`: mm coordinates, defined by the sform/qform of an image\n", "> - `'fsl'`: The FSL coordinate system, used internally by many FSL tools\n", "> (e.g. FLIRT)\n", "\n", "\n", "Oh, that example was too easy I hear you say? Try this one on for size. Let's\n", "say we have run FEAT on some task fMRI data, and want to get the MNI\n", "coordinates of the voxel with peak activation.\n", "\n", "\n", "> This is what people used to use `Featquery` for, back in the un-enlightened\n", "> days.\n", "\n", "\n", "Let's start by identifying the voxel with the biggest t-statistic:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "featdir = op.join('08_fslpy', 'fmri.feat')\n", "\n", "tstat1 = Image(op.join(featdir, 'stats', 'tstat1')).data\n", "\n", "# Recall from the numpy practical that\n", "# argmax gives us a 1D index into a\n", "# flattened view of the array. We can\n", "# use the unravel_index function to\n", "# convert it into a 3D index.\n", "peakvox = np.abs(tstat1).argmax()\n", "peakvox = np.unravel_index(peakvox, tstat1.shape)\n", "print('Peak voxel coordinates for tstat1:', peakvox, tstat1[peakvox])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we've got the voxel coordinates in functional space, we need to\n", "transform them into MNI space. FEAT provides a transformation which goes\n", "directly from functional to standard space, in the `reg` directory:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But ... wait a minute ... this is a FLIRT matrix! We can't just plug voxel\n", "coordinates into a FLIRT matrix and expect to get sensible results, because\n", "FLIRT works in an internal FSL coordinate system, which is not quite\n", "`'voxel'`, and not quite `'world'`. So we need to do a little more work.\n", "Let's start by loading our functional image, and the MNI152 template (the\n", "source and reference images of our FLIRT matrix):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "func = Image(op.join(featdir, 'reg', 'example_func'))\n", "std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can use them to get affines which convert between all of the different\n", "coordinate systems - we're going to combine them into a single uber-affine,\n", "which transforms our functional-space voxels into MNI world coordinates via:\n", "\n", " 1. functional voxels -> FLIRT source space\n", " 2. FLIRT source space -> FLIRT reference space\n", " 3. FLIRT referece space -> MNI world coordinates" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vox2fsl = func.getAffine('voxel', 'fsl')\n", "fsl2mni = std .getAffine('fsl', 'world')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Combining two affines into one is just a simple dot-product. There is a\n", "`concat()` function which does this for us, for any number of affines:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.transform.affine import concat\n", "\n", "# To combine affines together, we\n", "# have to list them in reverse -\n", "# linear algebra is *weird*.\n", "funcvox2mni = concat(fsl2mni, func2std, vox2fsl)\n", "print(funcvox2mni)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> In the next section we will use the\n", "> [`fsl.transform.flirt.fromFlirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html#fsl.transform.flirt.fromFlirt)\n", "> function, which does all of the above for us.\n", "\n", "\n", "So we've now got some voxel coordinates from our functional data, and an\n", "affine to transform into MNI world coordinates. The rest is easy:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mnicoords = transform(peakvox, funcvox2mni)\n", "mnivoxels = transform(mnicoords, std.getAffine('world', 'voxel'))\n", "mnivoxels = [int(round(v)) for v in mnivoxels]\n", "print('Peak activation (MNI coordinates):', mnicoords)\n", "print('Peak activation (MNI voxels): ', mnivoxels)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that in the above example we are only applying a linear transformation\n", "into MNI space - in reality you would also want to apply your non-linear\n", "structural-to-standard transformation too. This is covered in the next\n", "section.\n", "\n", "\n", "\n", "### Transformations and resampling\n", "\n", "\n", "Now, it's all well and good to look at t-statistic values and voxel\n", "coordinates and so on and so forth, but let's spice things up a bit and look\n", "at some images. Let's display our peak activation location in MNI space. To do\n", "this, we're going to resample our functional image into MNI space, so we can\n", "overlay it on the MNI template. This can be done using some handy functions\n", "from the\n", "[`fsl.transform.flirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.flirt.html)\n", "and\n", "[`fsl.utils.image.resample`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.resample.html)\n", "modules.\n", "\n", "\n", "Let's make sure we've got our source and reference images loaded:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "featdir = op.join(op.join('08_fslpy', 'fmri.feat'))\n", "tstat1 = Image(op.join(featdir, 'stats', 'tstat1'))\n", "std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we'll load the `example_func2standard` FLIRT matrix, and adjust it so that\n", "it transforms from functional *world* coordinates into standard *world*\n", "coordinates - this is what is expected by the `resampleToReference` function,\n", "used below:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.transform.flirt import fromFlirt\n", "\n", "func2std = np.loadtxt(op.join(featdir, 'reg', 'example_func2standard.mat'))\n", "func2std = fromFlirt(func2std, tstat1, std, 'world', 'world')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can use `resampleToReference` to resample our functional data into\n", "MNI152 space. This function returns a `numpy` array containing the resampled\n", "data, and an adjusted voxel-to-world affine transformation. But in this case,\n", "we know that the data will be aligned to MNI152, so we can ignore the affine:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.utils.image.resample import resampleToReference\n", "\n", "std_tstat1 = resampleToReference(tstat1, std, func2std)[0]\n", "std_tstat1 = Image(std_tstat1, header=std.header)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have our t-statistic image in MNI152 space, we can plot it in\n", "standard space using `matplotlib`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stddir = op.expandvars('${FSLDIR}/data/standard/')\n", "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n", "\n", "std_tstat1 = std_tstat1.data\n", "std_tstat1[std_tstat1 < 3] = 0\n", "\n", "fig = ortho(std2mm.data, mnivoxels, cmap=plt.cm.gray)\n", "fig = ortho(std_tstat1, mnivoxels, cmap=plt.cm.inferno, fig=fig, cursor=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the example above, we resampled some data from functional space into\n", "standard space using a linear transformation. But we all know that this is not\n", "how things work in the real world - linear transformations are for kids. The\n", "real world is full of lions and tigers and bears and warp fields.\n", "\n", "\n", "The\n", "[`fsl.transform.fnirt`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.fnirt.html#fsl.transform.fnirt.fromFnirt)\n", "and\n", "[`fsl.transform.nonlinear`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.nonlinear.html)\n", "modules contain classes and functions for working with FNIRT-style warp fields\n", "(modules for working with lions, tigers, and bears are still under\n", "development).\n", "\n", "\n", "Let's imagine that we have defined an ROI in MNI152 space, and we want to\n", "project it into the space of our functional data. We can do this by combining\n", "the nonlinear structural to standard registration produced by FNIRT with the\n", "linear functional to structural registration generated by FLIRT. First of\n", "all, we'll load images from each of the functional, structural, and standard\n", "spaces:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "featdir = op.join('08_fslpy', 'fmri.feat')\n", "func = Image(op.join(featdir, 'reg', 'example_func'))\n", "struc = Image(op.join(featdir, 'reg', 'highres'))\n", "std = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's say we have obtained our seed location in MNI152 coordinates. Let's\n", "convert them to MNI152 voxels just to double check:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "seedmni = [-48, -74, -9]\n", "seedmnivox = transform(seedmni, std.getAffine('world', 'voxel'))\n", "ortho(std.data, seedmnivox, cursor=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we'll load the FNIRT warp field, which encodes a nonlinear transformation\n", "from structural space to standard space. FNIRT warp fields are often stored as\n", "*coefficient* fields to reduce the file size, but in order to use it, we must\n", "convert the coefficient field into a *deformation* (a.k.a. *displacement*)\n", "field. This takes a few seconds:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.transform.fnirt import readFnirt\n", "from fsl.transform.nonlinear import coefficientFieldToDeformationField\n", "\n", "struc2std = readFnirt(op.join(featdir, 'reg', 'highres2standard_warp'), struc, std)\n", "struc2std = coefficientFieldToDeformationField(struc2std)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll also load our FLIRT functional to structural transformation, adjust it\n", "so that it transforms between voxel coordinate systems instead of the FSL\n", "coordinate system, and invert so it can transform from structural voxels to\n", "functional voxels:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.transform.affine import invert\n", "func2struc = np.loadtxt(op.join(featdir, 'reg', 'example_func2highres.mat'))\n", "func2struc = fromFlirt(func2struc, func, struc, 'voxel', 'voxel')\n", "struc2func = invert(func2struc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can transform our seed coordinates from MNI152 space into functional\n", "space in two stages. First, we'll use our deformation field to transform from\n", "MNI152 space into structural space:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "seedstruc = struc2std.transform(seedmni, 'world', 'voxel')\n", "seedfunc = transform(seedstruc, struc2func)\n", "\n", "print('Seed location in MNI coordinates: ', seedmni)\n", "print('Seed location in functional voxels:', seedfunc)\n", "ortho(func.data, seedfunc, cursor=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> FNIRT warp fields kind of work backwards - we can use them to transform\n", "> reference coordinates into source coordinates, but would need to invert the\n", "> warp field using `invwarp` if we wanted to transform from source coordinates\n", "> into referemce coordinates.\n", "\n", "\n", "Of course, we can also use our deformation field to resample an image from\n", "structural space into MNI152 space. The `applyDeformation` function takes an\n", "`Image` and a `DeformationField`, and returns a `numpy` array containing the\n", "resampled data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.transform.nonlinear import applyDeformation\n", "\n", "strucmni = applyDeformation(struc, struc2std)\n", "\n", "# remove low-valued voxels,\n", "# just for visualisation below\n", "strucmni[strucmni < 1] = 0\n", "\n", "fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray)\n", "fig = ortho(strucmni, [45, 54, 45], fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `premat` option to `applyDeformation` can be used to specify our linear\n", "functional to structural transformation, and hence resample a functional image\n", "into MNI152 space:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tstatmni = applyDeformation(tstat1, struc2std, premat=func2struc)\n", "tstatmni[tstatmni < 3] = 0\n", "\n", "fig = ortho(std.data, [45, 54, 45], cmap=plt.cm.gray)\n", "fig = ortho(tstatmni, [45, 54, 45], fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are a few other useful functions tucked away in the\n", "[`fsl.utils.image`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.image.html)\n", "and\n", "[`fsl.transform`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.transform.html)\n", "packages, with more to be added in the future.\n", "\n", "\n", "\n", "## FSL wrapper functions\n", "\n", "\n", "The\n", "[fsl.wrappers](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.wrappers.html)\n", "package is the home of \"wrapper\" functions for a range of FSL tools. You can\n", "use them to call an FSL tool from Python code, without having to worry about\n", "constructing a command-line, or saving/loading input/output images.\n", "\n", "\n", "> The `fsl.wrappers` functions also allow you to submit jobs to be run on the\n", "> cluster - this is described [below](#submitting-to-the-cluster).\n", "\n", "\n", "You can use the FSL wrapper functions with file names, similar to calling the\n", "corresponding tool via the command-line:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.wrappers import robustfov\n", "\n", "robustfov('08_fslpy/bighead', 'bighead_cropped')\n", "\n", "render('08_fslpy/bighead bighead_cropped -cm blue')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `fsl.wrappers` functions strive to provide an interface which is as close\n", "as possible to the command-line tool - most functions use positional arguments\n", "for required options, and keyword arguments for all other options, with\n", "argument names equivalent to command line option names. For example, the usage\n", "for the command-line `bet` tool is as follows:\n", "\n", "\n", "> ```\n", "> Usage: bet [options]\n", ">\n", "> Main bet2 options:\n", "> -o generate brain surface outline overlaid onto original image\n", "> -m generate binary brain mask\n", "> -s generate approximate skull image\n", "> -n don't generate segmented brain image output\n", "> -f fractional intensity threshold (0->1); default=0.5; smaller values give larger brain outline estimates\n", "> -g vertical gradient in fractional intensity threshold (-1->1); default=0; positive values give larger brain outline at bottom, smaller at top\n", "> -r head radius (mm not voxels); initial surface sphere is set to half of this\n", "> -c centre-of-gravity (voxels not mm) of initial mesh surface.\n", "> ...\n", "> ```\n", "\n", "\n", "So to use the `bet()` wrapper function, pass `` and `` as\n", "positional arguments, and pass the additional options as keyword arguments:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.wrappers import bet\n", "\n", "bet('bighead_cropped', 'bighead_cropped_brain', f=0.3, m=True, s=True)\n", "\n", "render('bighead_cropped -b 40 '\n", " 'bighead_cropped_brain -cm hot '\n", " 'bighead_cropped_brain_skull -ot mask -mc 0.4 0.4 1 '\n", " 'bighead_cropped_brain_mask -ot mask -mc 0 1 0 -o -w 5')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> Some FSL commands accept arguments which cannot be used as Python\n", "> identifiers - for example, the `-2D` option to `flirt` cannot be used as an\n", "> identifier in Python, because it begins with a number. In situations like\n", "> this, an alias is used. So to set the `-2D` option to `flirt`, you can do this:\n", ">\n", "> ```\n", "> # \"twod\" applies the -2D flag\n", "> flirt('source.nii.gz', 'ref.nii.gz', omat='src2ref.mat', twod=True)\n", "> ```\n", ">\n", "> Some of the `fsl.wrappers` functions also support aliases which may make\n", "> your code more readable. For example, when calling `bet`, you can use either\n", "> `m=True` or `mask=True` to apply the `-m` command line flag.\n", "\n", "\n", "\n", "### In-memory images\n", "\n", "\n", "It can be quite awkward to combine image processing with FSL tools and image\n", "processing in Python. The `fsl.wrappers` package tries to make this a little\n", "easier for you - if you are working with image data in Python, you can pass\n", "`Image` or `nibabel` objects directly into `fsl.wrappers` functions - they will\n", "be automatically saved to temporary files and passed to the underlying FSL\n", "command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cropped = Image('bighead_cropped')\n", "\n", "bet(cropped, 'bighead_cropped_brain')\n", "\n", "betted = Image('bighead_cropped_brain')\n", "\n", "fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)\n", "fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Loading outputs into Python\n", "\n", "\n", "By using the special `fsl.wrappers.LOAD` symbol, you can also have any output\n", "files produced by the tool automatically loaded into memory for you:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.wrappers import LOAD\n", "\n", "cropped = Image('bighead_cropped')\n", "\n", "# The loaded result is called \"output\",\n", "# because that is the name of the\n", "# argument in the bet wrapper function.\n", "betted = bet(cropped, LOAD).output\n", "\n", "fig = ortho(cropped.data, (80, 112, 85), cmap=plt.cm.gray)\n", "fig = ortho(betted .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use the `LOAD` symbol for any output argument - any output files which\n", "are loaded will be available through the return value of the wrapper function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.wrappers import flirt\n", "\n", "std2mm = Image(op.expandvars(op.join('$FSLDIR', 'data', 'standard', 'MNI152_T1_2mm')))\n", "tstat1 = Image(op.join('08_fslpy', 'fmri.feat', 'stats', 'tstat1'))\n", "func2std = np.loadtxt(op.join('08_fslpy', 'fmri.feat', 'reg', 'example_func2standard.mat'))\n", "\n", "aligned = flirt(tstat1, std2mm, applyxfm=True, init=func2std, out=LOAD)\n", "\n", "# Here the resampled tstat image\n", "# is called \"out\", because that\n", "# is the name of the flirt argument.\n", "aligned = aligned.out.data\n", "aligned[aligned < 1] = 0\n", "\n", "peakvox = np.abs(aligned).argmax()\n", "peakvox = np.unravel_index(peakvox, aligned.shape)\n", "\n", "fig = ortho(std2mm .data, peakvox, cmap=plt.cm.gray)\n", "fig = ortho(aligned.data, peakvox, cmap=plt.cm.inferno, fig=fig, cursor=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For tools like `bet` and `fast`, which expect an output *prefix* or\n", "*basename*, you can just set the prefix to `LOAD` - all output files with that\n", "prefix will be available in the object that is returned:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "img = Image('bighead_cropped')\n", "betted = bet(img, LOAD, f=0.3, mask=True)\n", "\n", "fig = ortho(img .data, (80, 112, 85), cmap=plt.cm.gray)\n", "fig = ortho(betted.output .data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)\n", "fig = ortho(betted.output_mask.data, (80, 112, 85), cmap=plt.cm.summer, fig=fig, alpha=0.5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### The `fslmaths` wrapper\n", "\n", "\n", "*Most* of the `fsl.wrappers` functions aim to provide an interface which is as\n", "close as possible to the underlying FSL tool. Ideally, if you read the\n", "command-line help for a tool, you should be able to figure out how to use the\n", "corresponding wrapper function. The wrapper for the `fslmaths` command is a\n", "little different, however. It provides more of an object-oriented interface,\n", "which is hopefully a little easier to use from within Python.\n", "\n", "\n", "You can apply an `fslmaths` operation by specifying the input image,\n", "*chaining* method calls together, and finally calling the `run()` method. For\n", "example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.wrappers import fslmaths\n", "fslmaths('bighead_cropped') \\\n", " .mas( 'bighead_cropped_brain_mask') \\\n", " .run( 'bighead_cropped_brain')\n", "\n", "render('bighead_cropped bighead_cropped_brain -cm hot')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, you can also use the `fslmaths` wrapper with in-memory images:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "wholehead = Image('bighead_cropped')\n", "brainmask = Image('bighead_cropped_brain_mask')\n", "\n", "eroded = fslmaths(brainmask).ero().ero().run()\n", "erodedbrain = fslmaths(wholehead).mas(eroded).run()\n", "\n", "fig = ortho(wholehead .data, (80, 112, 85), cmap=plt.cm.gray)\n", "fig = ortho(brainmask .data, (80, 112, 85), cmap=plt.cm.summer, fig=fig)\n", "fig = ortho(erodedbrain.data, (80, 112, 85), cmap=plt.cm.inferno, fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## The `FileTree`\n", "\n", "\n", "The\n", "[`fsl.utils.filetree`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html)\n", "library provides functionality which allows you to work with *structured data\n", "directories*, such as HCP or BIDS datasets. You can use `filetree` for both\n", "reading and for creating datasets.\n", "\n", "\n", "This practical gives a very brief introduction to the `filetree` library -\n", "refer to the [full\n", "documentation](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.html)\n", "to get a feel for how powerful it can be.\n", "\n", "\n", "\n", "### Describing your data\n", "\n", "\n", "To introduce `filetree`, we'll begin with a small example. Imagine that we\n", "have a dataset which looks like this:\n", "\n", "\n", "> ```\n", "> mydata\n", "> ├── sub_A\n", "> │   ├── ses_1\n", "> │   │   └── T1w.nii.gz\n", "> │   ├── ses_2\n", "> │   │   └── T1w.nii.gz\n", "> │   └── T2w.nii.gz\n", "> ├── sub_B\n", "> │   ├── ses_1\n", "> │   │   └── T1w.nii.gz\n", "> │   ├── ses_2\n", "> │   │   └── T1w.nii.gz\n", "> │   └── T2w.nii.gz\n", "> └── sub_C\n", "> ├── ses_1\n", "> │   └── T1w.nii.gz\n", "> ├── ses_2\n", "> │   └── T1w.nii.gz\n", "> └── T2w.nii.gz\n", "> ```\n", "\n", "\n", "(Run the code cell below to create a dummy data set with the above structure):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%bash\n", "for sub in A B C; do\n", " subdir=mydata/sub_$sub/\n", " mkdir -p $subdir\n", " cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $subdir/T2w.nii.gz\n", " for ses in 1 2; do\n", " sesdir=$subdir/ses_$ses/\n", " mkdir $sesdir\n", " cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz $sesdir/T1w.nii.gz\n", " done\n", "done" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To use `filetree` with this dataset, we must first describe its structure - we\n", "do this by creating a `.tree` file:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile mydata.tree\n", "sub_{subject}\n", " T2w.nii.gz\n", " ses_{session}\n", " T1w.nii.gz" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A `.tree` file is simply a description of the structure of your data\n", "directory - it describes the *file types* (also known as *templates*) which\n", "are present in the dataset (`T1w` and `T2w`), and the *variables* which are\n", "implicitly present in the structure of the dataset (`subject` and `session`).\n", "\n", "\n", "\n", "### Using the `FileTree`\n", "\n", "\n", "Now that we have a `.tree` file which describe our data, we can create a\n", "`FileTree` to work with it:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.utils.filetree import FileTree\n", "\n", "# Create a FileTree, giving\n", "# it our tree specification,\n", "# and the path to our data.\n", "tree = FileTree.read('mydata.tree', 'mydata')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can list all of the T1 images via the `FileTree.get_all` method. The\n", "`glob_vars='all'` option tells the `FileTree` to fill in the `T1w` template\n", "with all possible combinations of variables. The `FileTree.extract_variables`\n", "method accepts a file path, and gives you back the variable values contained\n", "within:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for t1file in tree.get_all('T1w', glob_vars='all'):\n", " fvars = tree.extract_variables('T1w', t1file)\n", " print(t1file, fvars)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `FileTree.update` method allows you to \"fill in\" variable values; it\n", "returns a new `FileTree` object which can be used on a selection of the\n", "data set:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "treeA = tree.update(subject='A')\n", "for t1file in treeA.get_all('T1w', glob_vars='all'):\n", " fvars = treeA.extract_variables('T1w', t1file)\n", " print(t1file, fvars)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Building a processing pipeline with `FileTree`\n", "\n", "\n", "Let's say we want to run BET on all of our T1 images. Let's start by modifying\n", "our `.tree` definition to include the BET outputs:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile mydata.tree\n", "sub_{subject}\n", " T2w.nii.gz\n", " ses_{session}\n", " T1w.nii.gz\n", " T1w_brain.nii.gz\n", " T1w_brain_mask.nii.gz" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can use the `FileTree` to generate the relevant file names for us,\n", "which we can then pass on to BET. Here we'll use the `FileTree.get_all_trees`\n", "method to create a sub-tree for each subject and each session:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.wrappers import bet\n", "tree = FileTree.read('mydata.tree', 'mydata')\n", "for subtree in tree.get_all_trees('T1w', glob_vars='all'):\n", " t1file = subtree.get('T1w')\n", " t1brain = subtree.get('T1w_brain')\n", " print('Running BET: {} -> {} ...'.format(t1file, t1brain))\n", " bet(t1file, t1brain, mask=True)\n", "print('Done!')\n", "\n", "example = tree.update(subject='A', session='1')\n", "render('{} {} -ot mask -o -w 2 -mc 0 1 0'.format(\n", " example.get('T1w'),\n", " example.get('T1w_brain_mask')))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### The `FileTreeQuery`\n", "\n", "\n", "The `filetree` module contains another class called the\n", "[`FileTreeQuery`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.filetree.query.html),\n", "which provides an interface that is more convenient if you are reading data\n", "from large datasets with many different file types and variables.\n", "\n", "\n", "When you create a `FileTreeQuery`, it scans the entire data directory and\n", "identifies all of the values that are present for each variable defined in the\n", "`.tree` file:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.utils.filetree import FileTreeQuery\n", "tree = FileTree.read('mydata.tree', 'mydata')\n", "query = FileTreeQuery(tree)\n", "print('T1w variables:', query.variables('T1w'))\n", "print('T2w variables:', query.variables('T2w'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `FileTreeQuery.query` method will return the paths to all existing files\n", "which match a set of variable values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('All files for subject A')\n", "for template in query.templates:\n", " print(' {} files:'.format(template))\n", " for match in query.query(template, subject='A'):\n", " print(' ', match.filename)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Calling shell commands\n", "\n", "\n", "The\n", "[`fsl.utils.run`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.run.html)\n", "module provides the `run` and `runfsl` functions, which are wrappers around\n", "the built-in [`subprocess`\n", "library](https://docs.python.org/3/library/subprocess.html).\n", "\n", "\n", "The default behaviour of `run` is to return the standard output of the\n", "command:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.utils.run import run\n", "\n", "# You can pass the command\n", "# and its arguments as a single\n", "# string, or as a sequence\n", "print('Lines in this notebook:', run('wc -l 08_fslpy.md').strip())\n", "print('Words in this notebook:', run(['wc', '-w', '08_fslpy.md']).strip())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But you can control what `run` returns, depending on your needs. Let's create\n", "a little script to demonstrate the options:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile mycmd\n", "#!/usr/bin/env bash\n", "exitcode=$1\n", "\n", "echo \"Standard output!\"\n", "echo \"Standard error :(\" >&2\n", "\n", "exit $exitcode" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And let's not forget to make it executable:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!chmod a+x mycmd" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use the `stdout`, `stderr` and `exitcode` arguments to control the\n", "return value:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('run(\"./mycmd 0\"): ',\n", " run(\"./mycmd 0\").strip())\n", "print('run(\"./mycmd 0\", stdout=False): ',\n", " run(\"./mycmd 0\", stdout=False))\n", "print('run(\"./mycmd 0\", exitcode=True):',\n", " run(\"./mycmd 0\", exitcode=True))\n", "print('run(\"./mycmd 0\", stdout=False, exitcode=True):',\n", " run(\"./mycmd 0\", stdout=False, exitcode=True))\n", "print('run(\"./mycmd 0\", stderr=True): ',\n", " run(\"./mycmd 0\", stderr=True))\n", "print('run(\"./mycmd 0\", stdout=False, stderr=True): ',\n", " run(\"./mycmd 0\", stdout=False, stderr=True).strip())\n", "print('run(\"./mycmd 0\", stderr=True, exitcode=True):',\n", " run(\"./mycmd 0\", stderr=True, exitcode=True))\n", "\n", "print('run(\"./mycmd 1\", exitcode=True):',\n", " run(\"./mycmd 1\", exitcode=True))\n", "print('run(\"./mycmd 1\", stdout=False, exitcode=True):',\n", " run(\"./mycmd 1\", stdout=False, exitcode=True))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So if only one of `stdout`, `stderr`, or `exitcode` is `True`, `run` will only\n", "return the corresponding value. Otherwise `run` will return a tuple which\n", "contains the requested outputs.\n", "\n", "\n", "If you run a command which returns a non-0 exit code, the default behaviour\n", "(if you don't set `exitcode=True`) is for a `RuntimeError` to be raised:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "run(\"./mycmd 99\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### The `runfsl` function\n", "\n", "\n", "The `runfsl` function is a wrapper around `run` which simply makes sure that\n", "the command you are calling is inside the `$FSLDIR/bin/` directory. It has the\n", "same usage as the `run` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.utils.run import runfsl\n", "runfsl('bet bighead_cropped bighead_cropped_brain')\n", "runfsl('fslroi bighead_cropped_brain bighead_slices 0 -1 0 -1 90 3')\n", "runfsl('fast -o bighead_fast bighead_slices')\n", "\n", "render('-vl 80 112 91 -xh -yh '\n", " 'bighead_cropped '\n", " 'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '\n", " 'bighead_fast_seg.nii.gz -ot label -o')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Submitting to the cluster\n", "\n", "\n", "Both the `run` and `runfsl` accept an argument called `submit`, which allows\n", "you to submit jobs to be executed on the cluster via the FSL `fsl_sub`\n", "command.\n", "\n", "\n", "> Cluster submission is handled by the\n", "> [`fsl.utils.fslsub`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html)\n", "> module - it contains lower level functions for managing and querying jobs\n", "> that have been submitted to the cluster. The functions defined in this\n", "> module can be used directly if you have more complicated requirements.\n", "\n", "\n", "The semantics of the `run` and `runfsl` functions are slightly different when\n", "you use the `submit` option - when you submit a job, the `run`/`runfsl`\n", "functions will return immediately, and will return a string containing the job\n", "ID:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jobid = run('ls', submit=True)\n", "print('Job ID:', jobid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once the job finishes, we should be able to read the usual `.o` and `.e`\n", "files:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stdout = f'ls.o{jobid}'\n", "print('Job output')\n", "print(open(stdout).read())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All of the `fsl.wrappers` functions also accept the `submit` argument:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jobid = bet('08_fslpy/bighead', 'bighead_brain', submit=True)\n", "print('Job ID:', jobid)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> But an error will occur if you try to pass in-memory images, or `LOAD` any\n", "> outputs when you call a wrapper function with `submit=True`.\n", "\n", "\n", "After submitting a job, you can use the `wait` function to wait until a job\n", "has completed:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fsl.utils.run import wait\n", "jobid = bet('08_fslpy/bighead', 'bighead_brain', submit=True)\n", "print('Job ID:', jobid)\n", "wait(jobid)\n", "print('Done!')\n", "render('08_fslpy/bighead bighead_brain -cm hot')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you use `submit=True`, you can also specify cluster submission options -\n", "you can include any arguments that are accepted by the\n", "[`fslsub.submit`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.utils.fslsub.html#fsl.utils.fslsub.submit)\n", "function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "jobs = []\n", "jobs.append(runfsl('robustfov -i 08_fslpy/bighead -r bighead_cropped', submit=True, queue='short.q'))\n", "jobs.append(runfsl('bet bighead_cropped bighead_brain', submit=True, queue='short.q', wait_for=jobs[-1]))\n", "jobs.append(runfsl('fslroi bighead_brain bighead_slices 0 -1 111 3 0 -1', submit=True, queue='short.q', wait_for=jobs[-1]))\n", "jobs.append(runfsl('fast -o bighead_fast bighead_slices', submit=True, queue='short.q', wait_for=jobs[-1]))\n", "print('Waiting for', jobs, '...')\n", "wait(jobs)\n", "\n", "render('-vl 80 112 91 -xh -zh -hc '\n", " 'bighead_brain '\n", " 'bighead_slices.nii.gz -cm brain_colours_1hot -b 30 '\n", " 'bighead_fast_seg.nii.gz -ot label -o')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Redirecting output\n", "\n", "\n", "The `log` option, accepted by both `run` and `fslrun`, allows for more\n", "fine-grained control over what is done with the standard output and error\n", "streams.\n", "\n", "\n", "You can use `'tee'` to redirect the standard output and error streams of the\n", "command to the standard output and error streams of the calling command (your\n", "python script):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print('Teeing:')\n", "_ = run('./mycmd 0', log={'tee' : True})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or you can use `'stdout'` and `'stderr'` to redirect the standard output and\n", "error streams of the command to files:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('stdout.log', 'wt') as o, \\\n", " open('stderr.log', 'wt') as e:\n", " run('./mycmd 0', log={'stdout' : o, 'stderr' : e})\n", "print('\\nRedirected stdout:')\n", "!cat stdout.log\n", "print('\\nRedirected stderr:')\n", "!cat stderr.log" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, you can use `'cmd'` to log the command itself to a file (useful for\n", "pipeline logging):" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "with open('commands.log', 'wt') as cmdlog:\n", " run('./mycmd 0', log={'cmd' : cmdlog})\n", " run('wc -l 08_fslpy.md', log={'cmd' : cmdlog})\n", "\n", "print('\\nCommand log:')\n", "!cat commands.log" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## FSL atlases\n", "\n", "\n", "The\n", "[`fsl.data.atlases`](https://users.fmrib.ox.ac.uk/~paulmc/fsleyes/fslpy/latest/fsl.data.atlases.html)\n", "module provides access to all of the atlas images that are stored in the\n", "`$FSLDIR/data/atlases/` directory of a standard FSL installation. It can be\n", "used to load and query probabilistic and label-based atlases.\n", "\n", "\n", "The `atlases` module needs to be initialised using the `rescanAtlases` function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import fsl.data.atlases as atlases\n", "atlases.rescanAtlases()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Querying atlases\n", "\n", "\n", "You can list all of the available atlases using `listAtlases`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for desc in atlases.listAtlases():\n", " print(desc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`listAtlases` returns a list of `AtlasDescription` objects, each of which\n", "contains descriptive information about one atlas. You can retrieve the\n", "`AtlasDescription` for a specific atlas via the `getAtlasDescription`\n", "function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "desc = atlases.getAtlasDescription('harvardoxford-cortical')\n", "print(desc.name)\n", "print(desc.atlasID)\n", "print(desc.specPath)\n", "print(desc.atlasType)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each `AtlasDescription` maintains a list of `AtlasLabel` objects, each of\n", "which represents one region that is defined in the atlas. You can access all\n", "of the `AtlasLabel` objects via the `labels` attribute:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for lbl in desc.labels[:5]:\n", " print(lbl)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Or you can retrieve a specific label using the `find` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# search by region name\n", "print(desc.find(name='Occipital Pole'))\n", "\n", "# or by label value\n", "print(desc.find(value=48))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Loading atlas images\n", "\n", "\n", "The `loadAtlas` function can be used to load the atlas image:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# For probabilistic atlases, you\n", "# can ask for the 3D ROI image\n", "# by setting loadSummary=True.\n", "# You can also request a\n", "# resolution - by default the\n", "# highest resolution version\n", "# will be loaded.\n", "lblatlas = atlases.loadAtlas('harvardoxford-cortical',\n", " loadSummary=True,\n", " resolution=2)\n", "\n", "# By default you will get the 4D\n", "# probabilistic atlas image (for\n", "# atlases for which this is\n", "# available).\n", "probatlas = atlases.loadAtlas('harvardoxford-cortical',\n", " resolution=2)\n", "\n", "print(lblatlas)\n", "print(probatlas)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Working with atlases\n", "\n", "\n", "Both `LabelAtlas` and `ProbabilisticAtlas` objects have a method called `get`,\n", "which can be used to extract ROI images for a specific region:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stddir = op.expandvars('${FSLDIR}/data/standard/')\n", "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n", "\n", "frontal = lblatlas.get(name='Frontal Pole').data\n", "frontal = np.ma.masked_where(frontal < 1, frontal)\n", "\n", "fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)\n", "fig = ortho(frontal, (45, 54, 45), cmap=plt.cm.winter, fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Calling `get` on a `ProbabilisticAtlas` will return a probability image:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stddir = op.expandvars('${FSLDIR}/data/standard/')\n", "std2mm = Image(op.join(stddir, 'MNI152_T1_2mm'))\n", "\n", "frontal = probatlas.get(name='Frontal Pole').data\n", "frontal = np.ma.masked_where(frontal < 1, frontal)\n", "\n", "fig = ortho(std2mm.data, (45, 54, 45), cmap=plt.cm.gray)\n", "fig = ortho(frontal, (45, 54, 45), cmap=plt.cm.inferno, fig=fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `get` method can be used to retrieve an image for a region by:\n", "- an `AtlasLabel` object\n", "- The region index\n", "- The region value\n", "- The region name\n", "\n", "\n", "`LabelAtlas` objects have a method called `label`, which can be used to\n", "interrogate the atlas at specific locations:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# The label method accepts 3D\n", "# voxel or world coordinates\n", "val = lblatlas.label((25, 52, 43), voxel=True)\n", "lbl = lblatlas.find(value=val)\n", "print('Region at voxel [25, 52, 43]: {} [{}]'.format(val, lbl.name))\n", "\n", "\n", "# or a 3D weighted or binary mask\n", "mask = np.zeros(lblatlas.shape)\n", "mask[30:60, 30:60, 30:60] = 1\n", "mask = Image(mask, header=lblatlas.header)\n", "\n", "lbls, props = lblatlas.label(mask)\n", "print('Labels in mask:')\n", "for lbl, prop in zip(lbls, props):\n", " lblname = lblatlas.find(value=lbl).name\n", " print(' {} [{}]: {:0.2f}%'.format(lbl, lblname, prop))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`ProbabilisticAtlas` objects have an analogous method called `values`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "vals = probatlas.values((25, 52, 43), voxel=True)\n", "print('Regions at voxel [25, 52, 43]:')\n", "for idx, val in enumerate(vals):\n", " if val > 0:\n", " lbl = probatlas.find(index=idx)\n", " print(' {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val))\n", "\n", "print('Average proportions of regions within mask:')\n", "vals = probatlas.values(mask)\n", "for idx, val in enumerate(vals):\n", " if val > 0:\n", " lbl = probatlas.find(index=idx)\n", " print(' {} [{}]: {:0.2f}%'.format(lbl.value, lbl.name, val))" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 2 }