fsl.wrappers.wrapperutils

This module contains functions and decorators used by the FSL wrapper functions.

The cmdwrapper() and fslwrapper() functions are convenience decorators which allow you to write your wrapper function such that it simply generates the command-line needed to respectively run a standard shell command or a FSL command. For example:

@fslwrapper
def fslreorient2std(input, output):
    return ['fslreorient2std', input, output]

When this fslreorient2std function is called, the fslwrapper decorator will take care of invoking the command in a standardised way.

The applyArgStyle() function can be used to automatically convert keyword arguments into command-line arguments, based on a set of standard patterns. For example:

@fslwrapper
def flirt(src, ref, **kwargs):
    cmd  = ['flirt', '-in', src, '-ref', ref]
    return cmd + applyArgStyle('-=', **kwargs)

The fileOrImage() and fileOrArray() functions can be used to decorate a wrapper function such that in-memory nibabel images or Numpy arrays can be passed in as arguments - they will be automatically saved out to files, and then the file names passed into the wrapper function. For example:

@fileOrImage('src', 'ref')
@fslwrapper
def flirt(src, ref, **kwargs):
    cmd  = ['flirt', '-in', src, '-ref', ref]
    return cmd + applyArgStyle('-=', **kwargs)

Now this flirt function can be called either with file names, or nibabel images.

Note

Because the fileOrImage() and fileOrArray() decorators manipulate the return value of the decorated function, they should be applied after any other decorators. Furthermore, if you need to apply both a fileOrImage and fileOrArray decorator to a function, they should be grouped together, e.g.:

@fileOrImage('a', 'b')
@fileOrArray('c', 'd')
@fslwrapper
def func(**kwargs):
    ...

Command outputs can also be loaded back into memory by using the special LOAD value when calling a wrapper function. For example:

@fileOrImage('src', 'ref', 'out')
@fslwrapper
def flirt(src, ref, **kwargs):
    cmd  = ['flirt', '-in', src, '-ref', ref]
    return cmd + applyArgStyle('-=', **kwargs)

If we set the out argument to LOAD, the output image will be loaded and returned:

src     = nib.load('src.nii')
ref     = nib.load('ref.nii')
aligned = flirt(src, ref, out=LOAD)['out']
fsl.wrappers.wrapperutils.cmdwrapper(func)[source]

This decorator can be used on functions which generate a command line. It will pass the return value of the function to the fsl.utils.run.run() function in a standardised manner.

fsl.wrappers.wrapperutils.fslwrapper(func)[source]

This decorator can be used on functions which generate a FSL command line. It will pass the return value of the function to the fsl.utils.run.runfsl() function in a standardised manner.

fsl.wrappers.wrapperutils.SHOW_IF_TRUE = <object object>

Constant to be used in the valmap passed to the applyArgStyle() function.

When a SHOW_IF_TRUE argument is True, it is added to the generated command line arguments.

fsl.wrappers.wrapperutils.HIDE_IF_TRUE = <object object>

Constant to be used in the valmap passed to the applyArgStyle() function.

When a HIDE_IF_TRUE argument is True, it is suppressed from the generated command line arguments.

fsl.wrappers.wrapperutils.applyArgStyle(style, valsep=None, argmap=None, valmap=None, singlechar_args=False, **kwargs)[source]

Turns the given kwargs into command line options. This function is intended to be used to automatically generate command line options from arguments passed into a Python function.

The style and valsep arguments control how key-value pairs are converted into command-line options:

style

valsep

Result

'-'

' '

-name val1 val2 val3

'-'

'"'

-name "val1 val2 val3"

'-'

','

-name val1,val2,val3

'--'

' '

--name val1 val2 val3

'--'

'"'

--name "val1 val2 val3"

'--'

','

--name val1,val2,val3

'-='

' '

Not supported

'-='

'"'

-name="val1 val2 val3"

'-='

','

-name=val1,val2,val3

'--='

' '

Not supported

'--='

'"'

--name="val1 val2 val3"

'--='

','

--name=val1,val2,val3

Parameters
  • style – Controls how the kwargs are converted into command-line options - must be one of '-', '--', '-=', or '--='.

  • valsep – Controls how the values passed to command-line options which expect multiple arguments are delimited - must be one of ' ', ',' or '"'. Defaults to ' ' if '=' not in style, ',' otherwise.

  • argmap – Dictionary of {kwarg-name : cli-name} mappings. This can be used if you want to use different argument names in your Python function for the command-line options.

  • valmap

    Dictionary of {cli-name : value} mappings. This can be used to define specific semantics for some command-line options. Acceptable values for value are as follows

    • SHOW_IF_TRUE - if the argument is present, and True in kwargs, the command line option will be added (without any arguments).

    • HIDE_IF_TRUE - if the argument is present, and False in kwargs, the command line option will be added (without any arguments).

    • Any other constant value. If the argument is present in kwargs, its command-line option will be added, with the constant value as its argument.

    The argument for any options not specified in the valmap will be converted into strings.

  • singlechar_args – If True, single character arguments always take a single hyphen prefix (e.g. -h) regardless of the style.

  • kwargs – Arguments to be converted into command-line options.

Returns

A list containing the generated command-line options.

fsl.wrappers.wrapperutils.namedPositionals(func, args)[source]

Given a function, and a sequence of positional arguments destined for that function, identifies the name for each positional argument. Variable positional arguments are given an automatic name.

Parameters
  • func – Function which will accept args as positionals.

  • args – Tuple of positional arguments to be passed to func.

fsl.wrappers.wrapperutils.LOAD = <object object>

Constant used by the FileOrThing class to indicate that an output file should be loaded into memory and returned as a Python object.

class fsl.wrappers.wrapperutils.FileOrThing(func, prepIn, prepOut, load, removeExt, *args, **kwargs)[source]

Bases: object

Decorator which ensures that certain arguments which are passed into the decorated function are always passed as file names. Both positional and keyword arguments can be specified.

The FileOrThing class is not intended to be used directly - see the fileOrImage() and fileOrArray() decorator functions for more details.

These decorators are intended for functions which wrap a command-line tool, i.e. where some inputs/outputs need to be specified as file names.

Inputs

Any arguments which are not of type Thing are passed through to the decorated function unmodified. Arguments which are of type Thing are saved to a temporary file, and the name of that file is passed to the function.

Outputs

If an argument is given the special LOAD value, it is assumed to be an output argument. In this case, it is replaced with a temporary file name then, after the function has completed, that file is loaded into memory, and the value returned (along with the function’s output, and any other arguments with a value of LOAD).

Return value

Functions decorated with a FileOrThing decorator will always return a dict-like object, where the function’s actual return value is accessible via an attribute called stdout. All output arguments with a value of LOAD will be present as dictionary entries, with the keyword argument names used as keys; these values will also be accessible as attributes of the results dict, when possible. Any LOAD output arguments which were not generated by the function will not be present in the dictionary.

Cluster submission

The above description holds in all situations, except when an argument called submit is passed, and is set to a value which evaluates to True. In this case, the FileOrThing decorator will pass all arguments straight through to the decorated function, and will return its return value unchanged.

This is because most functions that are decorated with the fileOrImage() or fileOrArray() decorators will invoke a call to run.run() or runfsl(), where a value of submit=True will cause the command to be executed asynchronously on a cluster platform.

A ValueError will be raised if the decorated function is called with submit=True, and with any in-memory objects or LOAD symbols.

Example

As an example of using the fileOrArray decorator on a function which concatenates two files containing affine transformations, and saves the output to a file:

# if atob, btoc, or output are passed
# in as arrays, they are converted to
# file names.
@fileOrArray('atob', 'btoc', 'output')
def concat(atob, btoc, output=None):

    # inputs are guaranteed to be files
    atob = np.loadtxt(atob)
    btoc = np.loadtxt(atoc)

    atoc = np.dot(btoc, atob)

    if output is not None:
        np.savetxt(output, atoc)

    return 'Done'

Because we have decorated the concat function with fileToArray(), it can be called with either file names, or Numpy arrays:

# All arguments are passed through
# unmodified - the output will be
# saved to a file called atoc.mat.
concat('atob.txt', 'btoc.txt', 'atoc.mat')

# The function's return value
# is accessed via an attribute called
# "stdout" on the dict
assert concat('atob.txt', 'btoc.txt', 'atoc.mat').stdout == 'Done'

# Outputs to be loaded into memory
# are returned in a dictionary,
# with argument names as keys. Values
# can be accessed as dict items, or
# as attributes.
atoc = concat('atob.txt', 'btoc.txt', LOAD)['atoc']
atoc = concat('atob.txt', 'btoc.txt', LOAD).atoc

# In-memory inputs are saved to
# temporary files, and those file
# names are passed to the concat
# function.
atoc = concat(np.diag([2, 2, 2, 0]),
              np.diag([3, 3, 3, 3]), LOAD).atoc

Using with other decorators

FileOrThing decorators can be chained with other FileOrThing decorators, and other decorators. When multiple FileOrThing decorators are used on a single function, the outputs from each decorator are merged together into a single dict-like object.

FileOrThing decorators can be used with any other decorators as long as they do not manipulate the return value, and as long as the FileOrThing decorators are adjacent to each other.

class Results(stdout)[source]

Bases: dict

A custom dict type used to return outputs from a function decorated with FileOrThing. All outputs are stored as dictionary items, with the argument name as key, and the output object (the “thing”) as value.

Where possible (i.e. for outputs named with a valid Python identifier), the outputs are also made accessible as attributes of the Results object.

The decorated function’s actual return value is accessible via the stdout() property.

property stdout

Access the return value of the decorated function.

fsl.wrappers.wrapperutils.fileOrImage(*args, **kwargs)[source]

Decorator which can be used to ensure that any NIfTI images are saved to file, and output images can be loaded and returned as nibabel image objects or Image objects.

fsl.wrappers.wrapperutils.fileOrArray(*args, **kwargs)[source]

Decorator which can be used to ensure that any Numpy arrays are saved to text files, and output files can be loaded and returned as Numpy arrays.

fsl.wrappers.wrapperutils.fileOrText(*args, **kwargs)[source]

Decorator which can be used to ensure that any text output (e.g. log file) are saved to text files, and output files can be loaded and returned as strings.

To be able to distinguish between input values and input file paths, the fileOrText decorator requires that input and output file paths are passed in as pathlib.Path objects. For example, given a function like this:

@fileOrText()
def myfunc(infile, outfile):
    ...

if we want to pass file paths for both infile and outfile, we would do this:

from pathlib import Path
myfunc(Path('input.txt'), Path('output.txt'))

Input values may be passed in as normal strings, e.g.:

myfunc('input data', Path('output.txt'))

Output values can be loaded as normal via the LOAD symbol, e.g.:

myfunc(Path('input.txt'), LOAD)