In Nipype, interfaces are python modules that allow you to use various external packages (e.g. FSL, SPM or FreeSurfer), even if they themselves are written in another programming language than python. Such an interface knows what sort of options an external program has and how to execute it.
To illustrate why interfaces are so useful, let's have a look at the brain extraction algorithm BET from FSL. Once in its original framework and once in the Nipype framework.
In [ ]:
%pylab inline
from nilearn.plotting import plot_anat
plot_anat('/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz', title='original',
display_mode='ortho', dim=-1, draw_cross=False, annotate=False)
Out[ ]:
In its simplest form, you can run BET by just specifying the input image and tell it what to name the output image:
bet <input> <output>
In [ ]:
%%bash
FILENAME=/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w
bet ${FILENAME}.nii.gz /output/sub-01_ses-test_T1w_bet.nii.gz
Let's take a look at the results:
In [ ]:
plot_anat('/output/sub-01_ses-test_T1w_bet.nii.gz', title='original',
display_mode='ortho', dim=-1, draw_cross=False, annotate=False)
Out[ ]:
Perfect! Exactly what we want. Hmm... what else could we want from BET? Well, it's actually a fairly complicated program. As is the case for all FSL binaries, just call it with no arguments to see all its options.
In [ ]:
%%bash
bet
We see that BET can also return a binary brain mask as a result of the skull-strip, which can be useful for masking our GLM analyses (among other things). Let's run it again including that option and see the result.
In [ ]:
%%bash
FILENAME=/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w
bet ${FILENAME}.nii.gz /output/sub-01_ses-test_T1w_bet.nii.gz -m
In [ ]:
plot_anat('/output/sub-01_ses-test_T1w_bet_mask.nii.gz', title='original',
display_mode='ortho', dim=-1, draw_cross=False, annotate=False)
Out[ ]:
Now let's look at the BET interface in Nipype. First, we have to import it.
In [ ]:
from nipype.interfaces.fsl import BET
Now that we have the BET function accessible, we just have to specify the input and output file. And finally we have to run the command. So exactly like in the original framework.
In [ ]:
skullstrip = BET()
skullstrip.inputs.in_file = "/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz"
skullstrip.inputs.out_file = "/output/T1w_nipype_bet.nii.gz"
res = skullstrip.run()
If we now look at the results from Nipype, we see that it is exactly the same as before.
In [ ]:
plot_anat('/output/T1w_nipype_bet.nii.gz', title='original',
display_mode='ortho', dim=-1, draw_cross=False, annotate=False)
Out[ ]:
This is not surprising, because Nipype used exactly the same bash code that we were using in the original framework example above. To verify this, we can call the cmdline
function of the constructed BET instance.
In [ ]:
print(skullstrip.cmdline)
Another way to set the inputs on an interface object is to use them as keyword arguments when you construct the interface instance. Let's write the Nipype code from above in this way, but let's also add the option to create a brain mask.
In [ ]:
skullstrip = BET(in_file="/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz",
out_file="/output/T1w_nipype_bet.nii.gz",
mask=True)
res = skullstrip.run()
Now if we plot this, we see again that this worked exactly as before. No surprise there.
In [ ]:
plot_anat('/output/T1w_nipype_bet_mask.nii.gz', title='original',
display_mode='ortho', dim=-1, draw_cross=False, annotate=False)
Out[ ]:
But how did we know what the names of the input parameters are? In the original framework we were able to just run BET
, without any additional parameters to get an information page. In the Nipype framework we can achieve the same thing by using the help()
function on an interface class. For the BET example, this is:
In [ ]:
BET.help()
As you can see, we get three different informations. First, a general explanation of the class.
Wraps command **bet**
Use FSL BET command for skull stripping.
For complete details, see the `BET Documentation.
<http://www.fmrib.ox.ac.uk/fsl/bet2/index.html>`_
Examples
--------
>>> from nipype.interfaces import fsl
>>> from nipype.testing import example_data
>>> btr = fsl.BET()
>>> btr.inputs.in_file = example_data('structural.nii')
>>> btr.inputs.frac = 0.7
>>> res = btr.run() # doctest: +SKIP
Second, a list of all possible input parameters.
Inputs::
[Mandatory]
in_file: (an existing file name)
input file to skull strip
flag: %s, position: 0
[Optional]
args: (a string)
Additional parameters to the command
flag: %s
center: (a list of at most 3 items which are an integer (int or
long))
center of gravity in voxels
flag: -c %s
environ: (a dictionary with keys which are a value of type 'str' and
with values which are a value of type 'str', nipype default value:
{})
Environment variables
frac: (a float)
fractional intensity threshold
flag: -f %.2f
functional: (a boolean)
apply to 4D fMRI data
flag: -F
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
ignore_exception: (a boolean, nipype default value: False)
Print an error message instead of throwing an exception in case the
interface fails to run
mask: (a boolean)
create binary mask image
flag: -m
mesh: (a boolean)
generate a vtk mesh brain surface
flag: -e
no_output: (a boolean)
Don't generate segmented output
flag: -n
out_file: (a file name)
name of output skull stripped image
flag: %s, position: 1
outline: (a boolean)
create surface outline image
flag: -o
output_type: ('NIFTI_PAIR' or 'NIFTI_PAIR_GZ' or 'NIFTI_GZ' or
'NIFTI')
FSL output type
padding: (a boolean)
improve BET if FOV is very small in Z (by temporarily padding end
slices)
flag: -Z
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
radius: (an integer (int or long))
head radius
flag: -r %d
reduce_bias: (a boolean)
bias field and neck cleanup
flag: -B
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
remove_eyes: (a boolean)
eye & optic nerve cleanup (can be useful in SIENA)
flag: -S
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
robust: (a boolean)
robust brain centre estimation (iterates BET several times)
flag: -R
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
skull: (a boolean)
create skull image
flag: -s
surfaces: (a boolean)
run bet2 and then betsurf to get additional skull and scalp surfaces
(includes registrations)
flag: -A
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
t2_guided: (a file name)
as with creating surfaces, when also feeding in non-brain-extracted
T2 (includes registrations)
flag: -A2 %s
mutually_exclusive: functional, reduce_bias, robust, padding,
remove_eyes, surfaces, t2_guided
terminal_output: ('stream' or 'allatonce' or 'file' or 'none')
Control terminal output: `stream` - displays to terminal immediately
(default), `allatonce` - waits till command is finished to display
output, `file` - writes output to file, `none` - output is ignored
threshold: (a boolean)
apply thresholding to segmented brain image and mask
flag: -t
vertical_gradient: (a float)
vertical gradient in fractional intensity threshold (-1, 1)
flag: -g %.2f
And third, a list of all possible output parameters.
Outputs::
inskull_mask_file: (a file name)
path/name of inskull mask (if generated)
inskull_mesh_file: (a file name)
path/name of inskull mesh outline (if generated)
mask_file: (a file name)
path/name of binary brain mask (if generated)
meshfile: (a file name)
path/name of vtk mesh file (if generated)
out_file: (a file name)
path/name of skullstripped file (if generated)
outline_file: (a file name)
path/name of outline file (if generated)
outskin_mask_file: (a file name)
path/name of outskin mask (if generated)
outskin_mesh_file: (a file name)
path/name of outskin mesh outline (if generated)
outskull_mask_file: (a file name)
path/name of outskull mask (if generated)
outskull_mesh_file: (a file name)
path/name of outskull mesh outline (if generated)
skull_mask_file: (a file name)
path/name of skull mask (if generated)
So here we see that Nipype also has output parameters. This is very practical. Because instead of typing the full path name to the mask volume, we can also more directly use the mask_file
parameter.
In [ ]:
print(res.outputs.mask_file)
To execute any interface class we use the run
method on that object. For FSL, Freesurfer, and other programs, this will just make a system call with the command line we saw above. For MATLAB-based programs like SPM, it will actually generate a .m
file and run a MATLAB process to execute it. All of that is handled in the background.
But what happens if we didn't specify all necessary inputs? For instance, you need to give BET a file to work on. If you try and run it without setting the input in_file
, you'll get a Python exception before anything actually gets executed:
In [ ]:
skullstrip2 = BET()
skullstrip2.run()
Nipype also knows some things about what sort of values should get passed to the inputs, and will raise (hopefully) informative exceptions when they are violated -- before anything gets processed. For example, BET just lets you say "create a mask," it doesn't let you name it. You may forget this, and try to give it a name. In this case, Nipype will raise a TraitError
telling you what you did wrong:
In [ ]:
skullstrip.inputs.mask = "mask_file.nii"
Additionally, Nipype knows that, for inputs corresponding to files you are going to process, they should exist in your file system. If you pass a string that doesn't correspond to an existing file, it will error and let you know:
In [ ]:
skullstrip.inputs.in_file = "/data/oops_a_typo.nii"
It turns out that for default output files, you don't even need to specify a name. Nipype will know what files are going to be created and will generate a name for you:
In [ ]:
skullstrip = BET(in_file="/data/ds000114/sub-01/ses-test/anat/sub-01_ses-test_T1w.nii.gz")
print(skullstrip.cmdline)
Note that it is going to write the output file to the local directory.
What if you just ran this interface and wanted to know what it called the file that was produced? As you might have noticed before, calling the run
method returned an object called InterfaceResult
that we saved under the variable res
. Let's inspect that object:
In [ ]:
res = skullstrip.run()
print(res.outputs)
We see that four possible files can be generated by BET. Here we ran it in the most simple way possible, so it just generated an out_file
, which is the skull-stripped image. Let's see what happens when we generate a mask. By the way, you can also set inputs at runtime by including them as arguments to the run
method:
In [ ]:
res2 = skullstrip.run(mask=True)
print(res2.outputs)
Nipype knows that if you ask for a mask, BET is going to generate it in a particular way and makes that information available to you.
A major motivating objective for Nipype is to streamline the integration of different analysis packages, so that you can use the algorithms you feel are best suited to your particular problem.
Say that you want to use BET, as SPM does not offer a way to create an explicit mask from functional data, but that otherwise you want your processing to occur in SPM. Although possible to do this in a MATLAB script, it might not be all that clean, particularly if you want your skullstrip to happen in the middle of your workflow (for instance, after realignment). Nipype provides a unified representation of interfaces across analysis packages.
For more on this, check out the Interfaces and the Workflow tutorial.