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

Merge branch 'enh/fslstats' into 'master'

Enh/fslstats

See merge request fsl/fslpy!213
parents 85609e78 2e47fd50
No related branches found
No related tags found
No related merge requests found
Showing with 494 additions and 213 deletions
...@@ -2,16 +2,16 @@ This document contains the ``fslpy`` release history in reverse chronological ...@@ -2,16 +2,16 @@ This document contains the ``fslpy`` release history in reverse chronological
order. order.
3.0.0 (Under development) 3.0.0 (Sunday 29th March 2020)
------------------------- ------------------------------
Added Added
^^^^^ ^^^^^
* New wrapper functions for the FSL :func:`.prelude` and :func:`applyxfm4D` * New wrapper functions for the FSL :class:`.fslstats`, :func:`.prelude` and
commands. :func:`applyxfm4D` commands.
* New ``firstDot`` option to the :func:`.path.getExt`, * New ``firstDot`` option to the :func:`.path.getExt`,
:func:`.path.removeExt`, and :func:`.path.splitExt`, functions, offering :func:`.path.removeExt`, and :func:`.path.splitExt`, functions, offering
rudimentary support for double-barrelled filenames. rudimentary support for double-barrelled filenames.
...@@ -19,6 +19,7 @@ Added ...@@ -19,6 +19,7 @@ Added
affine, which is applied to the input image before the deformation field. affine, which is applied to the input image before the deformation field.
* New :class:`.SubmitParams` class, providing a higer level interface for * New :class:`.SubmitParams` class, providing a higer level interface for
cluster submission. cluster submission.
* New :meth:`.FileTree.load_json` and :meth:`.FileTree.save_json` methods.
Changed Changed
...@@ -26,6 +27,10 @@ Changed ...@@ -26,6 +27,10 @@ Changed
* ``fslpy`` now requires a minimum Python version of 3.7. * ``fslpy`` now requires a minimum Python version of 3.7.
* The default value for the ``partial_fill`` option to :meth:`.FileTree.read`
has been changed to ``False``. Accordingly, the :class:`.FileTreeQuery`
calls the :meth:`.FileTree.partial_fill` method on the ``FileTree`` it is
given.
* The :func:`.gifti.relatedFiles` function now supports files with * The :func:`.gifti.relatedFiles` function now supports files with
BIDS-style naming conventions. BIDS-style naming conventions.
* The :func:`.run.run` and :func:`.run.runfsl` functions now pass through any * The :func:`.run.run` and :func:`.run.runfsl` functions now pass through any
...@@ -54,6 +59,8 @@ Changed ...@@ -54,6 +59,8 @@ Changed
* The :func:`.fileOrText` decorator has been updated to work with input * The :func:`.fileOrText` decorator has been updated to work with input
values - file paths must be passed in as ``pathlib.Path`` objects, so they values - file paths must be passed in as ``pathlib.Path`` objects, so they
can be differentiated from input values. can be differentiated from input values.
* Loaded :class:`.Image` objects returned by :mod:`fsl.wrappers` functions
are now named according to the wrapper function argument name.
Fixed Fixed
...@@ -69,6 +76,24 @@ Fixed ...@@ -69,6 +76,24 @@ Fixed
a single set of coordinates. a single set of coordinates.
Removed
^^^^^^^
* Removed the deprecated ``.StatisticAtlas.proportions``,
``.StatisticAtlas.coordProportions``, and
``.StatisticAtlas.maskProportions`` methods.
* Removed the deprecated ``indexed`` option to :meth:`.Image.__init__`.
* Removed the deprecated ``.Image.resample`` method.
* Removed the deprecated ``.image.loadIndexedImageFile`` function.
* Removed the deprecatd ``.FileTreeQuery.short_names`` and
``.Match.short_name`` properties.
* Removed the deprecated ``.idle.inIdle``, ``.idle.cancelIdle``,
``.idle.idleReset``, ``.idle.getIdleTimeout``, and
``.idle.setIdleTimeout`` functions.
* Removed the deprecated ``resample.calculateMatrix`` function.
2.8.4 (Monday 2nd March 2020) 2.8.4 (Monday 2nd March 2020)
----------------------------- -----------------------------
......
...@@ -58,7 +58,6 @@ import fsl.utils.image.resample as resample ...@@ -58,7 +58,6 @@ import fsl.utils.image.resample as resample
import fsl.transform.affine as affine import fsl.transform.affine as affine
import fsl.utils.notifier as notifier import fsl.utils.notifier as notifier
import fsl.utils.settings as fslsettings import fsl.utils.settings as fslsettings
import fsl.utils.deprecated as deprecated
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
...@@ -1085,24 +1084,6 @@ class StatisticAtlas(Atlas): ...@@ -1085,24 +1084,6 @@ class StatisticAtlas(Atlas):
return avgvals return avgvals
@deprecated.deprecated('2.6.0', '3.0.0', 'Use values instead')
def proportions(self, *args, **kwargs):
"""Deprecated - use :meth:`values` instead. """
return self.values(*args, **kwargs)
@deprecated.deprecated('2.6.0', '3.0.0', 'Use coordValues instead')
def coordProportions(self, *args, **kwargs):
"""Deprecated - use :meth:`coordValues` instead. """
return self.coordValues(*args, **kwargs)
@deprecated.deprecated('2.6.0', '3.0.0', 'Use maskValues instead')
def maskProportions(self, *args, **kwargs):
"""Deprecated - use :meth:`maskValues` instead. """
return self.maskValues(*args, **kwargs)
class ProbabilisticAtlas(StatisticAtlas): class ProbabilisticAtlas(StatisticAtlas):
"""A 4D atlas which contains one volume for each region. Each volume """A 4D atlas which contains one volume for each region. Each volume
contains probabiliy values for one region, between 0 and 100. contains probabiliy values for one region, between 0 and 100.
......
...@@ -52,7 +52,6 @@ import fsl.transform.affine as affine ...@@ -52,7 +52,6 @@ import fsl.transform.affine as affine
import fsl.utils.notifier as notifier import fsl.utils.notifier as notifier
import fsl.utils.memoize as memoize import fsl.utils.memoize as memoize
import fsl.utils.path as fslpath import fsl.utils.path as fslpath
import fsl.utils.deprecated as deprecated
import fsl.utils.bids as fslbids import fsl.utils.bids as fslbids
import fsl.data.constants as constants import fsl.data.constants as constants
import fsl.data.imagewrapper as imagewrapper import fsl.data.imagewrapper as imagewrapper
...@@ -993,7 +992,6 @@ class Image(Nifti): ...@@ -993,7 +992,6 @@ class Image(Nifti):
xform=None, xform=None,
loadData=True, loadData=True,
calcRange=True, calcRange=True,
indexed=False,
threaded=False, threaded=False,
dataSource=None, dataSource=None,
loadMeta=False, loadMeta=False,
...@@ -1002,7 +1000,7 @@ class Image(Nifti): ...@@ -1002,7 +1000,7 @@ class Image(Nifti):
:arg image: A string containing the name of an image file to load, :arg image: A string containing the name of an image file to load,
or a :mod:`numpy` array, or a :mod:`nibabel` image or a :mod:`numpy` array, or a :mod:`nibabel` image
object. object, or an ``Image``object.
:arg name: A name for the image. :arg name: A name for the image.
...@@ -1035,9 +1033,6 @@ class Image(Nifti): ...@@ -1035,9 +1033,6 @@ class Image(Nifti):
incrementally updated as more data is read from memory incrementally updated as more data is read from memory
or disk. or disk.
:arg indexed: Deprecated. Has no effect, and will be removed in
``fslpy`` 3.0.
:arg threaded: If ``True``, the :class:`.ImageWrapper` will use a :arg threaded: If ``True``, the :class:`.ImageWrapper` will use a
separate thread for data range calculation. Defaults separate thread for data range calculation. Defaults
to ``False``. Ignored if ``loadData`` is ``True``. to ``False``. Ignored if ``loadData`` is ``True``.
...@@ -1059,12 +1054,6 @@ class Image(Nifti): ...@@ -1059,12 +1054,6 @@ class Image(Nifti):
nibImage = None nibImage = None
saved = False saved = False
if indexed is not False:
warnings.warn('The indexed argument is deprecated '
'and has no effect',
category=DeprecationWarning,
stacklevel=2)
if loadData: if loadData:
threaded = False threaded = False
...@@ -1463,14 +1452,6 @@ class Image(Nifti): ...@@ -1463,14 +1452,6 @@ class Image(Nifti):
self.notify(topic='saveState') self.notify(topic='saveState')
@deprecated.deprecated('2.2.0', '3.0.0',
'Use fsl.utils.image.resample instead.')
def resample(self, *args, **kwargs):
"""Deprecated - use :func:`.image.resample` instead. """
from fsl.utils.image.resample import resample
return resample(self, *args, **kwargs)
def __getitem__(self, sliceobj): def __getitem__(self, sliceobj):
"""Access the image data with the specified ``sliceobj``. """Access the image data with the specified ``sliceobj``.
...@@ -1661,9 +1642,3 @@ def defaultExt(): ...@@ -1661,9 +1642,3 @@ def defaultExt():
outputType = os.environ.get('FSLOUTPUTTYPE', 'NIFTI_GZ') outputType = os.environ.get('FSLOUTPUTTYPE', 'NIFTI_GZ')
return options.get(outputType, '.nii.gz') return options.get(outputType, '.nii.gz')
@deprecated.deprecated('2.0.0', '3.0.0', 'Use nibabel.load instead.')
def loadIndexedImageFile(filename):
"""Deprecated - this call is equivalent to calling ``nibabel.load``. """
return nib.load(filename)
...@@ -31,8 +31,7 @@ from typing import Dict, List, Tuple ...@@ -31,8 +31,7 @@ from typing import Dict, List, Tuple
import numpy as np import numpy as np
from fsl.utils.deprecated import deprecated from . import FileTree
from . import FileTree
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
...@@ -207,15 +206,6 @@ class FileTreeQuery(object): ...@@ -207,15 +206,6 @@ class FileTreeQuery(object):
return list(self.__templatevars.keys()) return list(self.__templatevars.keys())
@property
@deprecated('2.6.0', '3.0.0', 'Use templates instead')
def short_names(self) -> List[str]:
"""Returns a list containing all templates of the ``FileTree`` that
are present in the directory.
"""
return self.templates
def query(self, template, asarray=False, **variables): def query(self, template, asarray=False, **variables):
"""Search for files of the given ``template``, which match """Search for files of the given ``template``, which match
the specified ``variables``. All hits are returned for variables the specified ``variables``. All hits are returned for variables
...@@ -292,12 +282,6 @@ class Match(object): ...@@ -292,12 +282,6 @@ class Match(object):
return self.__filename return self.__filename
@property
@deprecated('2.6.0', '3.0.0', 'Use template instead')
def short_name(self):
return self.template
@property @property
def template(self): def template(self):
return self.__template return self.__template
......
...@@ -85,8 +85,6 @@ from collections import abc ...@@ -85,8 +85,6 @@ from collections import abc
try: import queue try: import queue
except ImportError: import Queue as queue except ImportError: import Queue as queue
from fsl.utils.deprecated import deprecated
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
...@@ -597,36 +595,6 @@ def idleWhen(*args, **kwargs): ...@@ -597,36 +595,6 @@ def idleWhen(*args, **kwargs):
idleLoop.idleWhen(*args, **kwargs) idleLoop.idleWhen(*args, **kwargs)
@deprecated('2.7.0', '3.0.0', 'Use idleLoop.inIdle instead')
def inIdle(taskName):
"""Deprecated - use ``idleLoop.inIdle`` instead. """
return idleLoop.inIdle(taskName)
@deprecated('2.7.0', '3.0.0', 'Use idleLoop.cancelIdle instead')
def cancelIdle(taskName):
"""Deprecated - use ``idleLoop.cancelIdle`` instead. """
return idleLoop.cancelIdle(taskName)
@deprecated('2.7.0', '3.0.0', 'Use idleLoop.reset instead')
def idleReset():
"""Deprecated - use ``idleLoop.reset`` instead. """
return idleLoop.reset()
@deprecated('2.7.0', '3.0.0', 'Use idleLoop.callRate instead')
def getIdleTimeout():
"""Deprecated - use ``idleLoop.callRate`` instead. """
return idleLoop.callRate
@deprecated('2.7.0', '3.0.0', 'Use idleLoop.callRate instead')
def setIdleTimeout(timeout=None):
"""Deprecated - use ``idleLoop.callRate`` instead. """
idleLoop.callRate = timeout
def block(secs, delta=0.01, until=None): def block(secs, delta=0.01, until=None):
"""Blocks for the specified number of seconds, yielding to the main ``wx`` """Blocks for the specified number of seconds, yielding to the main ``wx``
loop. loop.
......
...@@ -18,7 +18,6 @@ import numpy as np ...@@ -18,7 +18,6 @@ import numpy as np
import scipy.ndimage as ndimage import scipy.ndimage as ndimage
import fsl.transform.affine as affine import fsl.transform.affine as affine
import fsl.utils.deprecated as deprecated
def resampleToPixdims(image, newPixdims, **kwargs): def resampleToPixdims(image, newPixdims, **kwargs):
...@@ -282,13 +281,3 @@ def applySmoothing(data, matrix, newShape): ...@@ -282,13 +281,3 @@ def applySmoothing(data, matrix, newShape):
sigma[ratio >= 1.1] *= 0.425 sigma[ratio >= 1.1] *= 0.425
return ndimage.gaussian_filter(data, sigma) return ndimage.gaussian_filter(data, sigma)
@deprecated.deprecated('2.8.0', '3.0.0',
'Use fsl.transform.affine.rescale instead')
def calculateMatrix(oldShape, newShape, origin):
"""Deprecated - use :func:`.affine.rescale` instead. """
xform = affine.rescale(oldShape, newShape, origin)
if np.all(np.isclose(xform, np.eye(len(oldShape) + 1))):
return None
return xform[:-1, :]
...@@ -180,13 +180,17 @@ def run(*args, **kwargs): ...@@ -180,13 +180,17 @@ def run(*args, **kwargs):
returnStderr = kwargs.pop('stderr', False) returnStderr = kwargs.pop('stderr', False)
returnExitcode = kwargs.pop('exitcode', False) returnExitcode = kwargs.pop('exitcode', False)
submit = kwargs.pop('submit', {}) submit = kwargs.pop('submit', {})
log = kwargs.pop('log', {}) log = kwargs.pop('log', None)
tee = log .get('tee', False)
logStdout = log .get('stdout', None)
logStderr = log .get('stderr', None)
logCmd = log .get('cmd', None)
args = prepareArgs(args) args = prepareArgs(args)
if log is None:
log = {}
tee = log.get('tee', False)
logStdout = log.get('stdout', None)
logStderr = log.get('stderr', None)
logCmd = log.get('cmd', None)
if not bool(submit): if not bool(submit):
submit = None submit = None
......
#!/usr/bin/env python
#
# transforms.py - Deprecated
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""The ``fsl.utils.transform`` module is deprecated - use the
:mod:`fsl.transform` module instead.
"""
import fsl.utils.deprecated as deprecated
from fsl.transform.affine import * # noqa
from fsl.transform.flirt import (flirtMatrixToSform, # noqa
sformToFlirtMatrix)
deprecated.warn('fsl.utils.transform',
vin='2.4.0',
rin='3.0.0',
msg='Use the fsl.transform module instead')
...@@ -47,7 +47,7 @@ import re ...@@ -47,7 +47,7 @@ import re
import string import string
__version__ = '2.9.0.dev0' __version__ = '3.1.0.dev0'
"""Current version number, as a string. """ """Current version number, as a string. """
......
...@@ -37,12 +37,15 @@ instead. Aliases may also be used to provide a more readable interface (e.g. ...@@ -37,12 +37,15 @@ instead. Aliases may also be used to provide a more readable interface (e.g.
the :func:`.bet` function uses ``mask`` instead of ``m``). the :func:`.bet` function uses ``mask`` instead of ``m``).
One exception to the above is :class:`.fslmaths`, which provides a more Two exceptions to the above are :class:`.fslmaths` and :class:`.fslstats`,
object-oriented interface:: which provide a more object-oriented interface::
from fsl.wrappers import fslmaths, fslstats
from fsl.wrappers import fslmaths
fslmaths('image.nii').mas('mask.nii').bin().run('output.nii') fslmaths('image.nii').mas('mask.nii').bin().run('output.nii')
imean, imin, imax = fslstats('image.nii').k('mask.nii').m.R.run()
Wrapper functions for commands which accept NIfTI image or numeric text files Wrapper functions for commands which accept NIfTI image or numeric text files
will for the most part accept either in-memory ``nibabel`` images/Numpy arrays will for the most part accept either in-memory ``nibabel`` images/Numpy arrays
...@@ -95,6 +98,7 @@ from .fnirt import (fnirt, # noqa ...@@ -95,6 +98,7 @@ from .fnirt import (fnirt, # noqa
invwarp, invwarp,
convertwarp) convertwarp)
from .fslmaths import (fslmaths,) # noqa from .fslmaths import (fslmaths,) # noqa
from .fslstats import (fslstats,) # noqa
from .fugue import (fugue, # noqa from .fugue import (fugue, # noqa
prelude, prelude,
sigloss) sigloss)
......
#!/usr/bin/env python
#
# fslstats.py - Wrapper for fslstats
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
"""This module provides the :class:`fslstats` class, which acts as a wrapper
for the ``fslstats`` command-line tool.
.. warning:: This wrapper function will only work with FSL 6.0.2 or newer.
"""
import io
import functools as ft
import numpy as np
import fsl.data.image as fslimage
from . import wrapperutils as wutils
class fslstats(object):
"""The ``fslstats`` class is a wrapper around the ``fslstats`` command-line
tool. It provides an object-oriented interface - options are specified by
chaining method calls and attribute accesses together.
.. warning:: This wrapper function will only work with FSL 6.0.2 or newer,
due to bugs in ``fslstats`` output formatting that are
present in older versions.
Any ``fslstats`` command-line option which does not require any arguments
(e.g. ``-r``) can be set by accessing an attribute on a ``fslstats``
object, e.g.::
stats = fslstats('image.nii.gz')
stats.r
``fslstats`` command-line options which do require additional arguments
(e.g. ``-k``) can be set by calling a method on an ``fslstats`` object,
e.g.::
stats = fslstats('image.nii.gz')
stats.k('mask.nii.gz')
The ``fslstats`` command can be executed via the :meth:`run` method.
Normally, the results will be returned as a scalar floating point number,
or a ``numpy`` array. Pre-options will affect the structure of the return
value - see :meth:`__init__` for details.
Attribute and method calls can be chained together, so a complete
``fslstats`` call can be performed in a single line, e.g.::
imgmin, imgmax = fslstats('image.nii.gz').k('mask.nii.gz').r.run()
"""
OPTIONS = {
'robust_minmax' : 'r',
'minmax' : 'R',
'mean_entropy' : 'e',
'mean_entropy_nz' : 'E',
'volume' : 'v',
'volume_nz' : 'V',
'mean' : 'm',
'mean_nz' : 'M',
'stddev' : 's',
'stddev_nz' : 'S',
'smallest_roi' : 'w',
'max_vox' : 'x',
'min_vox' : 'X',
'cog_mm' : 'c',
'cog_vox' : 'C',
'abs' : 'a',
'zero_naninf' : 'n',
}
"""This dict contains options which do not require any additional
arguments. They are set via attribute access on the ``fslstats``
object.
"""
ARG_OPTIONS = {
'lower_threshold' : 'l',
'upper_threshold' : 'u',
'percentile' : 'p',
'percentile_nz' : 'P',
'mask' : 'k',
'diff' : 'd',
'hist' : 'h',
'hist_bounded' : 'H',
}
"""This dict contains options which require additional arguments.
They are set via method calls on the ``fslstats`` object (with the
additional arguments passed into the method call).
"""
# add {shortopt : shortopt} mappings
# for all options to simplify code in
# the fslstats class
OPTIONS .update({v : v for v in OPTIONS .values()})
ARG_OPTIONS.update({v : v for v in ARG_OPTIONS.values()})
def __init__(self,
input,
t=False,
K=None,
sep_volumes=False,
index_mask=None):
"""Create a ``fslstats`` object.
If one of the ``t`` or ``K`` pre-options is set, e.g.::
fslstats('image_4d.nii.gz', t=True)
or::
fslstats('image_4d.nii.gz', K='mask.nii.gz')
then :meth:`run` will return a 2D ``numpy`` array of shape ``(nvols,
nvals)`` if ``t`` is set, or ``(nlabels, nvals)`` if ``K`` is set.
If both of the ``t`` and ``K`` pre-options are set, e.g.::
fslstats('image_4d.nii.gz', t=True, K='mask.nii.gz')
then the result will be a 3D numpy array of shape ``(nvols, nlabels,
nvals)``.
If neither ``t`` or ``K`` are set, then the result will be a scalar,
or a 1D ``numpy`` array.
:arg input: Input image - either a file name, or an
:class:`.Image` object, or a ``nibabel.Nifti1Image``
object.
:arg t: Produce separate results for each 3D volume in the
input image.
:arg K: Produce separate results for each sub-mask within
the provided mask image.
:arg sep_volumes: Alias for ``t``.
:arg index_mask: Alias for ``K``.
"""
if t is None: t = sep_volumes
if K is None: K = index_mask
self.__input = input
self.__options = []
# pre-options must be supplied
# before input image
if t: self.__options.append( '-t')
if K is not None: self.__options.extend(('-K', K))
self.__options.append(input)
def __getattr__(self, name):
"""Intercepts attribute accesses and accumulates ``fslstats`` command-line
flags accordingly.
"""
# options which take no args
# are called as attributes
if name in fslstats.OPTIONS:
flag = fslstats.OPTIONS[name]
args = False
# options which take args
# are called as methods
elif name in fslstats.ARG_OPTIONS:
flag = fslstats.ARG_OPTIONS[name]
args = True
else:
raise AttributeError(name)
addFlag = ft.partial(self.__addFlag, flag)
if args: return addFlag
else: return addFlag()
def __addFlag(self, flag, *args):
"""Used by :meth:`__getattr__`. Add the given flag and any arguments to
the accumulated list of command-line options.
"""
self.__options.extend(('-' + flag,) + args)
return self
def run(self, raw=False):
"""Run the ``fslstats`` command-line tool. See :meth:`__init__` for a
description of the return value.
:arg raw: Defaults to ``False``. If ``True``, the raw standard output
and error is returned, instead of a scalar/numpy array.
:returns: Result of ``fslstats`` as a scalar or ``numpy`` array.
"""
# The parsing logic below will not work
# with versions of fslstats prior to fsl
# 6.0.2, due to a quirk in the output
# formatting of older versions.
# The default behaviour of run/runfsl
# is to tee the command output streams
# to the calling process streams. We
# can disable this via log=None.
result = self.__run('fslstats', *self.__options, log=None)
if raw:
return result.stdout
result = np.genfromtxt(io.StringIO(result.stdout[0].strip()))
sepvols = '-t' in self.__options
lblmask = '-K' in self.__options
# One line of output for each volume and
# for each label (with volume the slowest
# changing). Reshape to 3D.
if sepvols and lblmask:
# We need know the number of volumes
# (or the number of labels) in order
# to know how to shape the results.
img = fslimage.Image(self.__input, loadData=False)
if img.ndim >= 4: nvols = img.shape[3]
else: nvols = 1
# reshape the result into
# (nvals, nvols, nlbls)
nlbls = int(len(result) / nvols)
result = result.reshape((nvols, nlbls, -1)).squeeze()
# Scalar - use numpy indexing weirdness
# to get our single value out.
elif result.size == 1:
result = result[()]
return result
@wutils.fileOrImage()
@wutils.fslwrapper
def __run(self, *cmd):
"""Run the given ``fslmaths`` command. """
return [str(c) for c in cmd]
...@@ -403,18 +403,18 @@ def namedPositionals(func, args): ...@@ -403,18 +403,18 @@ def namedPositionals(func, args):
LOAD = object() LOAD = object()
"""Constant used by the :class:`_FileOrThing` class to indicate that an output """Constant used by the :class:`FileOrThing` class to indicate that an output
file should be loaded into memory and returned as a Python object. file should be loaded into memory and returned as a Python object.
""" """
class _FileOrThing(object): class FileOrThing(object):
"""Decorator which ensures that certain arguments which are passed into the """Decorator which ensures that certain arguments which are passed into the
decorated function are always passed as file names. Both positional and decorated function are always passed as file names. Both positional and
keyword arguments can be specified. keyword arguments can be specified.
The ``_FileOrThing`` class is not intended to be used directly - see the The ``FileOrThing`` class is not intended to be used directly - see the
:func:`fileOrImage` and :func:`fileOrArray` decorator functions for more :func:`fileOrImage` and :func:`fileOrArray` decorator functions for more
details. details.
...@@ -445,7 +445,7 @@ class _FileOrThing(object): ...@@ -445,7 +445,7 @@ class _FileOrThing(object):
**Return value** **Return value**
Functions decorated with a ``_FileOrThing`` decorator will always return a Functions decorated with a ``FileOrThing`` decorator will always return a
``dict``-like object, where the function's actual return value is ``dict``-like object, where the function's actual return value is
accessible via an attribute called ``stdout``. All output arguments with a accessible via an attribute called ``stdout``. All output arguments with a
value of ``LOAD`` will be present as dictionary entries, with the keyword value of ``LOAD`` will be present as dictionary entries, with the keyword
...@@ -460,7 +460,7 @@ class _FileOrThing(object): ...@@ -460,7 +460,7 @@ class _FileOrThing(object):
The above description holds in all situations, except when an argument The above description holds in all situations, except when an argument
called ``submit`` is passed, and is set to a value which evaluates to called ``submit`` is passed, and is set to a value which evaluates to
``True``. In this case, the ``_FileOrThing`` decorator will pass all ``True``. In this case, the ``FileOrThing`` decorator will pass all
arguments straight through to the decorated function, and will return its arguments straight through to the decorated function, and will return its
return value unchanged. return value unchanged.
...@@ -534,27 +534,27 @@ class _FileOrThing(object): ...@@ -534,27 +534,27 @@ class _FileOrThing(object):
**Using with other decorators** **Using with other decorators**
``_FileOrThing`` decorators can be chained with other ``_FileOrThing`` ``FileOrThing`` decorators can be chained with other ``FileOrThing``
decorators, and other decorators. When multiple ``_FileOrThing`` decorators, and other decorators. When multiple ``FileOrThing``
decorators are used on a single function, the outputs from each decorator decorators are used on a single function, the outputs from each decorator
are merged together into a single dict-like object. are merged together into a single dict-like object.
``_FileOrThing`` decorators can be used with any other decorators ``FileOrThing`` decorators can be used with any other decorators
**as long as** they do not manipulate the return value, and as long as **as long as** they do not manipulate the return value, and as long as
the ``_FileOrThing`` decorators are adjacent to each other. the ``FileOrThing`` decorators are adjacent to each other.
""" """
class _Results(dict): class Results(dict):
"""A custom ``dict`` type used to return outputs from a function """A custom ``dict`` type used to return outputs from a function
decorated with ``_FileOrThing``. All outputs are stored as dictionary decorated with ``FileOrThing``. All outputs are stored as dictionary
items, with the argument name as key, and the output object (the items, with the argument name as key, and the output object (the
"thing") as value. "thing") as value.
Where possible (i.e. for outputs named with a valid Python Where possible (i.e. for outputs named with a valid Python
identifier), the outputs are also made accessible as attributes of identifier), the outputs are also made accessible as attributes of
the ``_Results`` object. the ``Results`` object.
The decorated function's actual return value is accessible via the The decorated function's actual return value is accessible via the
:meth:`stdout` property. :meth:`stdout` property.
...@@ -562,7 +562,7 @@ class _FileOrThing(object): ...@@ -562,7 +562,7 @@ class _FileOrThing(object):
def __init__(self, stdout): def __init__(self, stdout):
"""Create a ``_Results`` dict. """Create a ``Results`` dict.
:arg stdout: Return value of the decorated function (typically a :arg stdout: Return value of the decorated function (typically a
tuple containing the standard output and error of the tuple containing the standard output and error of the
...@@ -593,7 +593,7 @@ class _FileOrThing(object): ...@@ -593,7 +593,7 @@ class _FileOrThing(object):
removeExt, removeExt,
*args, *args,
**kwargs): **kwargs):
"""Initialise a ``_FileOrThing`` decorator. """Initialise a ``FileOrThing`` decorator.
:arg func: The function to be decorated. :arg func: The function to be decorated.
...@@ -604,8 +604,10 @@ class _FileOrThing(object): ...@@ -604,8 +604,10 @@ class _FileOrThing(object):
arguments that were set to :data:`LOAD`. arguments that were set to :data:`LOAD`.
:arg load: Function which is called to load items for arguments :arg load: Function which is called to load items for arguments
that were set to :data:`LOAD`. Must accept a file path that were set to :data:`LOAD`. Must accept the
as its sole argument. following arguments:
- the name of the argument
- path to the file to be loaded
:arg removeExt: Function which can remove a file extension from a file :arg removeExt: Function which can remove a file extension from a file
path. path.
...@@ -618,7 +620,7 @@ class _FileOrThing(object): ...@@ -618,7 +620,7 @@ class _FileOrThing(object):
All other positional arguments are interpreted as the names of the All other positional arguments are interpreted as the names of the
arguments to the function which will be handled by this arguments to the function which will be handled by this
``_FileOrThing`` decorator. If not provided, *all* arguments passed to ``FileOrThing`` decorator. If not provided, *all* arguments passed to
the function will be handled. the function will be handled.
...@@ -673,8 +675,8 @@ class _FileOrThing(object): ...@@ -673,8 +675,8 @@ class _FileOrThing(object):
'or LOAD with submit=True!') 'or LOAD with submit=True!')
return func(*args, **kwargs) return func(*args, **kwargs)
# If this _FileOrThing is being called # If this FileOrThing is being called
# by another _FileOrThing don't create # by another FileOrThing don't create
# another working directory. We do this # another working directory. We do this
# sneakily, by setting an attribute on # sneakily, by setting an attribute on
# the wrapped function which stores the # the wrapped function which stores the
...@@ -734,8 +736,8 @@ class _FileOrThing(object): ...@@ -734,8 +736,8 @@ class _FileOrThing(object):
passed to the ``prepOut`` function specified at :meth:`__init__`. passed to the ``prepOut`` function specified at :meth:`__init__`.
All other arguments are passed through the ``prepIn`` function. All other arguments are passed through the ``prepIn`` function.
:arg parent: ``True`` if this ``_FileOrThing`` is the first in a :arg parent: ``True`` if this ``FileOrThing`` is the first in a
chain of ``_FileOrThing`` decorators. chain of ``FileOrThing`` decorators.
:arg workdir: Directory in which all temporary files should be stored. :arg workdir: Directory in which all temporary files should be stored.
...@@ -760,7 +762,7 @@ class _FileOrThing(object): ...@@ -760,7 +762,7 @@ class _FileOrThing(object):
- A dictionary of ``{ name : filename }`` mappings, - A dictionary of ``{ name : filename }`` mappings,
for all arguments with a value of ``LOAD``. for all arguments with a value of ``LOAD``.
- A dictionary ``{ filepat : replstr }`` paths, for - A dictionary of ``{ filepat : replstr }`` paths, for
all output-prefix arguments with a value of ``LOAD``. all output-prefix arguments with a value of ``LOAD``.
""" """
...@@ -779,7 +781,7 @@ class _FileOrThing(object): ...@@ -779,7 +781,7 @@ class _FileOrThing(object):
# Prefixed outputs are only # Prefixed outputs are only
# managed by the parent # managed by the parent
# _FileOrthing in a chain of # FileOrthing in a chain of
# FoT decorators. # FoT decorators.
if not parent: if not parent:
prefix = None prefix = None
...@@ -894,11 +896,11 @@ class _FileOrThing(object): ...@@ -894,11 +896,11 @@ class _FileOrThing(object):
def __generateResult( def __generateResult(
self, workdir, result, outprefix, outfiles, prefixes): self, workdir, result, outprefix, outfiles, prefixes):
"""Loads function outputs and returns a :class:`_Results` object. """Loads function outputs and returns a :class:`Results` object.
Called by :meth:`__call__` after the decorated function has been Called by :meth:`__call__` after the decorated function has been
called. Figures out what files should be loaded, and loads them into called. Figures out what files should be loaded, and loads them into
a ``_Results`` object. a ``Results`` object.
:arg workdir: Directory which contains the function outputs. :arg workdir: Directory which contains the function outputs.
:arg result: Function return value. :arg result: Function return value.
...@@ -909,23 +911,23 @@ class _FileOrThing(object): ...@@ -909,23 +911,23 @@ class _FileOrThing(object):
:arg prefixes: Dictionary containing output-prefix patterns to be :arg prefixes: Dictionary containing output-prefix patterns to be
loaded (see :meth:`__prepareArgs`). loaded (see :meth:`__prepareArgs`).
:returns: A ``_Results`` object containing all loaded outputs. :returns: A ``Results`` object containing all loaded outputs.
""" """
# make a _Results object to store # make a Results object to store
# the output. If we are decorating # the output. If we are decorating
# another _FileOrThing, the # another FileOrThing, the
# results will get merged together # results will get merged together
# into a single _Results dict. # into a single Results dict.
if not isinstance(result, _FileOrThing._Results): if not isinstance(result, FileOrThing.Results):
result = _FileOrThing._Results(result) result = FileOrThing.Results(result)
# Load the LOADed outputs # Load the LOADed outputs
for oname, ofile in outfiles.items(): for oname, ofile in outfiles.items():
log.debug('Loading output %s: %s', oname, ofile) log.debug('Loading output %s: %s', oname, ofile)
if op.exists(ofile): oval = self.__load(ofile) if op.exists(ofile): oval = self.__load(oname, ofile)
else: oval = None else: oval = None
result[oname] = oval result[oname] = oval
...@@ -953,21 +955,23 @@ class _FileOrThing(object): ...@@ -953,21 +955,23 @@ class _FileOrThing(object):
log.debug('Loading prefixed output %s [%s]: %s', log.debug('Loading prefixed output %s [%s]: %s',
prefPat, prefName, prefixed) prefPat, prefName, prefixed)
noext = self.__removeExt(prefixed)
prefPat = prefPat.replace('\\', '\\\\')
noext = re.sub('^' + prefPat, prefName, noext)
withext = re.sub('^' + prefPat, prefName, prefixed)
# if the load function returns # if the load function returns
# None, this file is probably # None, this file is probably
# not of the correct type. # not of the correct type.
fval = self.__load(fullpath) fval = self.__load(noext, fullpath)
if fval is not None: if fval is not None:
noext = self.__removeExt(prefixed)
prefPat = prefPat.replace('\\', '\\\\')
noext = re.sub('^' + prefPat, prefName, noext)
# If there is already an item in result with the # If there is already an item in result with the
# name (stripped of prefix), then instead store # name (stripped of prefix), then instead store
# the result with the full prefixed name # the result with the full prefixed name
if noext not in result: if noext not in result:
result[noext] = fval result[noext] = fval
else: else:
withext = re.sub('^' + prefPat, prefName, prefixed)
result[withext] = fval result[withext] = fval
break break
...@@ -1014,7 +1018,7 @@ def fileOrImage(*args, **kwargs): ...@@ -1014,7 +1018,7 @@ def fileOrImage(*args, **kwargs):
def prepOut(workdir, name, val): def prepOut(workdir, name, val):
return op.join(workdir, '{}.nii.gz'.format(name)) return op.join(workdir, '{}.nii.gz'.format(name))
def load(path): def load(name, path):
if not fslimage.looksLikeImage(path): if not fslimage.looksLikeImage(path):
return None return None
...@@ -1027,7 +1031,8 @@ def fileOrImage(*args, **kwargs): ...@@ -1027,7 +1031,8 @@ def fileOrImage(*args, **kwargs):
# if any arguments were fsl images, # if any arguments were fsl images,
# that takes precedence. # that takes precedence.
if fslimage.Image in intypes: if fslimage.Image in intypes:
return fslimage.Image(data, header=img.header) return fslimage.Image(data, header=img.header, name=name)
# but if all inputs were file names, # but if all inputs were file names,
# nibabel takes precedence # nibabel takes precedence
elif nib.nifti1.Nifti1Image in intypes or len(intypes) == 0: elif nib.nifti1.Nifti1Image in intypes or len(intypes) == 0:
...@@ -1039,13 +1044,13 @@ def fileOrImage(*args, **kwargs): ...@@ -1039,13 +1044,13 @@ def fileOrImage(*args, **kwargs):
raise RuntimeError('Cannot handle type: {}'.format(intypes)) raise RuntimeError('Cannot handle type: {}'.format(intypes))
def decorator(func): def decorator(func):
fot = _FileOrThing(func, fot = FileOrThing(func,
prepIn, prepIn,
prepOut, prepOut,
load, load,
fslimage.removeExt, fslimage.removeExt,
*args, *args,
**kwargs) **kwargs)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
result = fot(*args, **kwargs) result = fot(*args, **kwargs)
...@@ -1076,18 +1081,18 @@ def fileOrArray(*args, **kwargs): ...@@ -1076,18 +1081,18 @@ def fileOrArray(*args, **kwargs):
def prepOut(workdir, name, val): def prepOut(workdir, name, val):
return op.join(workdir, '{}.txt'.format(name)) return op.join(workdir, '{}.txt'.format(name))
def load(path): def load(_, path):
try: return np.loadtxt(path) try: return np.loadtxt(path)
except Exception: return None except Exception: return None
def decorator(func): def decorator(func):
fot = _FileOrThing(func, fot = FileOrThing(func,
prepIn, prepIn,
prepOut, prepOut,
load, load,
fslpath.removeExt, fslpath.removeExt,
*args, *args,
**kwargs) **kwargs)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
return fot(*args, **kwargs) return fot(*args, **kwargs)
...@@ -1141,20 +1146,20 @@ def fileOrText(*args, **kwargs): ...@@ -1141,20 +1146,20 @@ def fileOrText(*args, **kwargs):
def prepOut(workdir, name, val): def prepOut(workdir, name, val):
return op.join(workdir, '{}.txt'.format(name)) return op.join(workdir, '{}.txt'.format(name))
def load(path): def load(_, path):
try: try:
with open(path, "r") as f: with open(path, "r") as f:
return f.read() return f.read()
except Exception: return None except Exception: return None
def decorator(func): def decorator(func):
fot = _FileOrThing(func, fot = FileOrThing(func,
prepIn, prepIn,
prepOut, prepOut,
load, load,
fslpath.removeExt, fslpath.removeExt,
*args, *args,
**kwargs) **kwargs)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
return fot(*args, **kwargs) return fot(*args, **kwargs)
......
...@@ -8,7 +8,7 @@ import pytest ...@@ -8,7 +8,7 @@ import pytest
import fsl.scripts.resample_image as resample_image import fsl.scripts.resample_image as resample_image
import fsl.utils.transform as transform import fsl.transform.affine as affine
from fsl.utils.tempdir import tempdir from fsl.utils.tempdir import tempdir
from fsl.data.image import Image from fsl.data.image import Image
...@@ -22,22 +22,22 @@ def test_resample_image_shape(): ...@@ -22,22 +22,22 @@ def test_resample_image_shape():
resample_image.main('image resampled -s 20,20,20'.split()) resample_image.main('image resampled -s 20,20,20'.split())
res = Image('resampled') res = Image('resampled')
expv2w = transform.concat( expv2w = affine.concat(
img.voxToWorldMat, img.voxToWorldMat,
transform.scaleOffsetXform([0.5, 0.5, 0.5], 0)) affine.scaleOffsetXform([0.5, 0.5, 0.5], 0))
assert np.all(np.isclose(res.shape, (20, 20, 20))) assert np.all(np.isclose(res.shape, (20, 20, 20)))
assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5))) assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5)))
assert np.all(np.isclose(res.voxToWorldMat, expv2w)) assert np.all(np.isclose(res.voxToWorldMat, expv2w))
assert np.all(np.isclose( assert np.all(np.isclose(
np.array(transform.axisBounds(res.shape, res.voxToWorldMat)) - 0.25, np.array(affine.axisBounds(res.shape, res.voxToWorldMat)) - 0.25,
transform.axisBounds(img.shape, img.voxToWorldMat))) affine.axisBounds(img.shape, img.voxToWorldMat)))
resample_image.main('image resampled -s 20,20,20 -o corner'.split()) resample_image.main('image resampled -s 20,20,20 -o corner'.split())
res = Image('resampled') res = Image('resampled')
assert np.all(np.isclose( assert np.all(np.isclose(
transform.axisBounds(res.shape, res.voxToWorldMat), affine.axisBounds(res.shape, res.voxToWorldMat),
transform.axisBounds(img.shape, img.voxToWorldMat))) affine.axisBounds(img.shape, img.voxToWorldMat)))
def test_resample_image_shape_4D(): def test_resample_image_shape_4D():
...@@ -65,9 +65,9 @@ def test_resample_image_dim(): ...@@ -65,9 +65,9 @@ def test_resample_image_dim():
resample_image.main('image resampled -d 0.5,0.5,0.5'.split()) resample_image.main('image resampled -d 0.5,0.5,0.5'.split())
res = Image('resampled') res = Image('resampled')
expv2w = transform.concat( expv2w = affine.concat(
img.voxToWorldMat, img.voxToWorldMat,
transform.scaleOffsetXform([0.5, 0.5, 0.5], 0)) affine.scaleOffsetXform([0.5, 0.5, 0.5], 0))
assert np.all(np.isclose(res.shape, (20, 20, 20))) assert np.all(np.isclose(res.shape, (20, 20, 20)))
assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5))) assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5)))
......
#!/usr/bin/env python
import os
import os.path as op
import sys
import contextlib
import pytest
import numpy as np
import fsl.utils.run as run
import fsl.utils.tempdir as tempdir
import fsl.wrappers as fw
from .. import mockFSLDIR as mockFSLDIR_base, make_random_image
mock_fslstats = """
#!{}
shape = {{outshape}}
import sys
import numpy as np
data = np.random.randint(1, 10, shape)
if len(shape) == 1:
data = data.reshape(1, -1)
np.savetxt(sys.stdout, data, fmt='%i')
""".format(sys.executable).strip()
@contextlib.contextmanager
def mockFSLDIR(shape):
with mockFSLDIR_base() as fd:
fname = op.join(fd, 'bin', 'fslstats')
script = mock_fslstats.format(outshape=shape)
with open(fname, 'wt') as f:
f.write(script)
os.chmod(fname, 0o755)
yield fd
def test_fslstats_cmdline():
with tempdir.tempdir(), run.dryrun(), mockFSLDIR(1) as fsldir:
make_random_image('image')
cmd = op.join(fsldir, 'bin', 'fslstats')
result = fw.fslstats('image').m.r.mask('mask').k('mask').r.run(True)
expected = cmd + ' image -m -r -k mask -k mask -r'
assert result[0] == expected
result = fw.fslstats('image', t=True, K='mask').m.R.u(123).s.volume.run(True)
expected = cmd + ' -t -K mask image -m -R -u 123 -s -v'
assert result[0] == expected
result = fw.fslstats('image', K='mask').n.V.p(1).run(True)
expected = cmd + ' -K mask image -n -V -p 1'
assert result[0] == expected
result = fw.fslstats('image', t=True).H(10, 1, 99).d('diff').run(True)
expected = cmd + ' -t image -H 10 1 99 -d diff'
assert result[0] == expected
# unknown option
with pytest.raises(AttributeError):
fw.fslstats('image').Q
def test_fslstats_result():
with tempdir.tempdir():
with mockFSLDIR('(1,)') as fsldir:
result = fw.fslstats('image').run()
assert np.isscalar(result)
with mockFSLDIR('(2,)') as fsldir:
result = fw.fslstats('image').run()
assert result.shape == (2,)
# 3 mask lbls, 2 values
with mockFSLDIR('(3, 2)') as fsldir:
result = fw.fslstats('image', K='mask').run()
assert result.shape == (3, 2)
# 5 vols, 2 values
with mockFSLDIR('(5, 2)') as fsldir:
result = fw.fslstats('image', t=True).run()
assert result.shape == (5, 2)
# 5 vols, 3 mask lbls, 2 values
with mockFSLDIR('(15, 2)') as fsldir:
make_random_image('image', (10, 10, 10, 5))
result = fw.fslstats('image', K='mask', t=True).run()
assert result.shape == (5, 3, 2)
# -t/-K with a 3D image
with mockFSLDIR('(4,)') as fsldir:
make_random_image('image', (10, 10, 10))
result = fw.fslstats('image', K='mask', t=True).run()
assert result.shape == (4,)
result = fw.fslstats('image', t=True).run()
assert result.shape == (4,)
result = fw.fslstats('image', K='mask').run()
assert result.shape == (4,)
...@@ -17,7 +17,7 @@ import fsl.utils.assertions as asrt ...@@ -17,7 +17,7 @@ import fsl.utils.assertions as asrt
import fsl.utils.run as run import fsl.utils.run as run
from fsl.utils.tempdir import tempdir from fsl.utils.tempdir import tempdir
from . import mockFSLDIR, make_random_image from .. import mockFSLDIR, make_random_image
def checkResult(cmd, base, args, stripdir=None): def checkResult(cmd, base, args, stripdir=None):
......
...@@ -27,8 +27,8 @@ import fsl.data.image as fslimage ...@@ -27,8 +27,8 @@ import fsl.data.image as fslimage
import fsl.wrappers.wrapperutils as wutils import fsl.wrappers.wrapperutils as wutils
from . import mockFSLDIR, cleardir, checkdir, testdir from .. import mockFSLDIR, cleardir, checkdir, testdir
from .test_run import mock_submit from ..test_run import mock_submit
def test_applyArgStyle(): def test_applyArgStyle():
......
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