wrapperutils.py 24.3 KB
Newer Older
1
2
#!/usr/bin/env python
#
Paul McCarthy's avatar
Paul McCarthy committed
3
4
# wrapperutils.py - Functions and decorators used by the FSL wrapper
# functions.
5
6
7
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
Paul McCarthy's avatar
Paul McCarthy committed
8
9
10
11
"""This module contains functions and decorators used by the FSL wrapper
functions.


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
The :func:`cmdwrapper` and :func:`fslwrapper` functions are conenience
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.


Paul McCarthy's avatar
Paul McCarthy committed
27
The :func:`applyArgStyle` function can be used to automatically convert
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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 :func:`fileOrImage` and :func:`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 exmaple::


    @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.


55
56
57
58
59
60
61
.. note:: Because the :func:`fileOrImage` and :func:`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')
Paul McCarthy's avatar
Paul McCarthy committed
62
              @fileOrArray('c', 'd')
63
64
65
66
67
              @fslwrapper
              def func(**kwargs):
                  ...


68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
Command outputs can also be loaded back into memory by using the special
:data:`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']
Paul McCarthy's avatar
Paul McCarthy committed
85
"""
86
87
88
89


import os.path as op
import            os
Paul McCarthy's avatar
Paul McCarthy committed
90
import            sys
91
92
93
94
95
96
97
98
import            inspect
import            tempfile
import            warnings
import            functools
import            collections

import            six
import nibabel as nib
Paul McCarthy's avatar
Paul McCarthy committed
99
import numpy   as np
100
101

import fsl.utils.tempdir as tempdir
102
import fsl.utils.run     as run
103
104
105
import fsl.data.image    as fslimage


Paul McCarthy's avatar
Paul McCarthy committed
106
107
108
109
110
def _update_wrapper(wrapper, wrapped, *args, **kwargs):
    """Replacement for the built-in ``functools.update_wrapper``. This
    implementation ensures that the wrapper function has an attribute
    called ``__wrapped__``, which refers to the ``wrapped`` function.

111
    This custom function is only needed in Python versions < 3.4.
Paul McCarthy's avatar
Paul McCarthy committed
112
113
114
115
116
    """

    wrapper = functools.update_wrapper(wrapper, wrapped, *args, **kwargs)

    # Python >= 3.4 does things right
Paul McCarthy's avatar
Paul McCarthy committed
117
    if (sys.version_info[0] * 10 + sys.version_info[1]) < 34:
Paul McCarthy's avatar
Paul McCarthy committed
118
119
        wrapper.__wrapped__ = wrapped
    return wrapper
120
121


Paul McCarthy's avatar
Paul McCarthy committed
122
123
124
125
126
127
def _unwrap(func):
    """Replacement for the built-in ``inspect.unwrap`` function, which
    is not present in Python versions prior to 3.4.
    """

    # Python >= 3.4 has an inspect.unwrap function
Paul McCarthy's avatar
Paul McCarthy committed
128
    if (sys.version_info[0] * 10 + sys.version_info[1]) >= 34:
Paul McCarthy's avatar
Paul McCarthy committed
129
130
131
132
133
134
135
136
137
        return inspect.unwrap(func)

    # Otherwise we follow the __wrapped__ chain ourselves
    if hasattr(func, '__wrapped__'):
        return _unwrap(func.__wrapped__)

    return func


138
139
140
141
142
143
def cmdwrapper(func):
    """This decorator can be used on functions which generate a command line.
    It will pass the return value of the function to the
    :func:`fsl.utils.run.run` function in a standardised manner.
    """
    def wrapper(*args, **kwargs):
144
145
146
        stdout = kwargs.pop('stdout', True)
        stderr = kwargs.pop('stderr', False)
        exitcode = kwargs.pop('exitcode', False)
147
        submit = kwargs.pop('submit', None)
148
149
        log    = kwargs.pop('log',    {'tee' : True})
        cmd    = func(*args, **kwargs)
150
        return run.run(cmd, stderr=stderr, log=log, submit=submit, stdout=stdout, exitcode=exitcode)
151
152
153
154
155
156
157
158
159
    return _update_wrapper(wrapper, func)


def fslwrapper(func):
    """This decorator can be used on functions which generate a FSL command
    line. It will pass the return value of the function to the
    :func:`fsl.utils.run.runfsl` function in a standardised manner.
    """
    def wrapper(*args, **kwargs):
160
161
162
        stdout = kwargs.pop('stdout', True)
        stderr = kwargs.pop('stderr', False)
        exitcode = kwargs.pop('exitcode', False)
163
        submit = kwargs.pop('submit', None)
164
165
        log    = kwargs.pop('log',    {'tee' : True})
        cmd    = func(*args, **kwargs)
166
        return run.runfsl(cmd, stderr=stderr, log=log, submit=submit, stdout=stdout, exitcode=exitcode)
167
168
169
    return _update_wrapper(wrapper, func)


Paul McCarthy's avatar
Paul McCarthy committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
SHOW_IF_TRUE = object()
"""Constant to be used in the ``valmap`` passed to the :func:`applyArgStyle`
function.

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


HIDE_IF_TRUE = object()
"""Constant to be used in the ``valmap`` passed to the :func:`applyArgStyle`
function.

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


188
def applyArgStyle(style, valsep=None, argmap=None, valmap=None, singlechar_args=False, **kwargs):
Paul McCarthy's avatar
Paul McCarthy committed
189
190
191
192
    """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.

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
    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``
    =========  ==========  ===========================


Paul McCarthy's avatar
Paul McCarthy committed
215
    :arg style:  Controls how the ``kwargs`` are converted into command-line
216
217
218
219
220
                 options - must be one of ``'-'``, ``'--'``, ``'-='``, or
                 ``'--='``.

    :arg valsep: Controls how the values passed to command-line options
                 which expect multiple arguments are delimited - must be
221
222
                 one of ``' '``, ``','`` or ``'"'``. Defaults to ``' '``
                 if ``'=' not in style``, ``','`` otherwise.
Paul McCarthy's avatar
Paul McCarthy committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

    :arg 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.

    :arg 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

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

                  - :data:`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.
246

247
248
249
    :arg singlechar_args: If True, single character arguments always take a single
                          hyphen prefix (e.g. -h) regardless of the style

Paul McCarthy's avatar
Paul McCarthy committed
250
251
252
253
254
    :arg kwargs: Arguments to be converted into command-line options.

    :returns:    A list containing the generated command-line options.
    """

255
256
257
258
    if valsep is None:
        if '=' in style: valsep = ','
        else:            valsep = ' '

Paul McCarthy's avatar
Paul McCarthy committed
259
260
    if style not in ('-', '--', '-=', '--='):
        raise ValueError('Invalid style: {}'.format(style))
261
262
263
264
265
266
267
268
269
    if valsep not in (' ', ',', '"'):
        raise ValueError('Invalid valsep: {}'.format(valsep))

    # we don't handle the case where '=' in
    # style, and valsep == ' ', because no
    # sane CLI app would do this. Right?
    if '=' in style and valsep == ' ':
        raise ValueError('Incompatible style and valsep: s={} v={}'.format(
            style, valsep))
Paul McCarthy's avatar
Paul McCarthy committed
270
271
272
273
274

    if argmap is None: argmap = {}
    if valmap is None: valmap = {}

    def fmtarg(arg):
275
        if   style in ('-',  '-=') or (singlechar_args and len(arg) == 1):  arg =  '-{}'.format(arg)
276
277
278
        elif style in ('--', '--='): arg = '--{}'.format(arg)
        return arg

279
    # always returns a sequence
Paul McCarthy's avatar
Paul McCarthy committed
280
    def fmtval(val):
281
282
        if     isinstance(val, collections.Sequence) and \
           not isinstance(val, six.string_types):
283
284
285
286
287

            val = [str(v) for v in val]
            if   valsep == ' ': return val
            elif valsep == '"': return [' '   .join(val)]
            else:               return [valsep.join(val)]
288
        else:
289
290
291
292
293
294
295
296
            return [str(val)]

    # val is assumed to be a sequence
    def fmtargval(arg, val):
        # if '=' in style, val will
        # always be a single string
        if '=' in style: return ['{}={}'.format(arg, val[0])]
        else:            return [arg] + val
297
298
299
300
301
302

    args = []

    for k, v in kwargs.items():

        k    = argmap.get(k, k)
Paul McCarthy's avatar
Paul McCarthy committed
303
304
305
        mapv = valmap.get(k, fmtval(v))
        k    = fmtarg(k)

306

307
308
309
310
        if mapv in (SHOW_IF_TRUE, HIDE_IF_TRUE):
            if (mapv is SHOW_IF_TRUE and     v) or \
               (mapv is HIDE_IF_TRUE and not v):
                args.append(k)
311
        else:
312
            args.extend(fmtargval(k, mapv))
313
314
315
316

    return args


317
def namedPositionals(func, args):
318
    """Given a function, and a sequence of positional arguments destined
319
    for that function, identifies the name for each positional argument.
320
    Variable positional arguments are given an automatic name.
321

322
323
    :arg func: Function which will accept ``args`` as positionals.
    :arg args: Tuple of positional arguments to be passed to ``func``.
324
    """
Paul McCarthy's avatar
Paul McCarthy committed
325

326
327
328
329
330
331
332
333
334
335
    # Current implementation will
    # result in naming collisions
    # for something like this:
    #
    # def func(args0, *args):
    #     ...
    # because of automatic vararg
    # naming. But who would write
    # a function like that anyway?

336
337
    # Remove any decorators
    # from the function
Paul McCarthy's avatar
Paul McCarthy committed
338
339
    func = _unwrap(func)

340
341
342
    # getargspec is the only way to
    # get the names of positional
    # arguments in Python 2.x.
Paul McCarthy's avatar
Paul McCarthy committed
343
    if sys.version_info[0] < 3:
344
345
346
        spec     = inspect.getargspec(func)
        argnames = spec.args
        varargs  = spec.varargs
Paul McCarthy's avatar
Paul McCarthy committed
347

348
349
    # But getargspec is deprecated
    # in python 3.x
Paul McCarthy's avatar
Paul McCarthy committed
350
351
352
353
354
355
    else:

        # getfullargspec is deprecated in
        # python 3.5, but not in python 3.6.
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=DeprecationWarning)
356
357
358
            spec     = inspect.getfullargspec(func)
            argnames = spec.args
            varargs  = spec.varargs
359

360
361
362
    # we only care about the arguments
    # that are being passed in
    argnames = argnames[:len(args)]
363

364
365
366
367
    # make up names for varargs
    nvarargs = len(args) - len(argnames)
    if varargs is not None and nvarargs > 0:
        argnames += ['{}{}'.format(varargs, i) for i in range(nvarargs)]
368

369
    return argnames
370
371


Paul McCarthy's avatar
Paul McCarthy committed
372
LOAD = object()
Paul McCarthy's avatar
Paul McCarthy committed
373
374
"""Constant used by the :class:`_FileOrThing` class to indicate that an output
file should be loaded into memory and returned as a Python object.
375
376
377
"""


Paul McCarthy's avatar
Paul McCarthy committed
378
379
380
381
382
383
384
385
386
387
class _FileOrThing(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
    :func:`fileOrImage` and :func:`fileOrArray` decorator functions for more
    details.

388

Paul McCarthy's avatar
Paul McCarthy committed
389
390
391
392
393
394
395
396
397
398
399
400
    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.

401

Paul McCarthy's avatar
Paul McCarthy committed
402
    **Outputs**
403
404


Paul McCarthy's avatar
Paul McCarthy committed
405
    If an argument is given the special :data:`LOAD` value, it is assumed
Paul McCarthy's avatar
Paul McCarthy committed
406
407
408
    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,
Paul McCarthy's avatar
Paul McCarthy committed
409
    and any other arguments with a value of ``LOAD``).
Paul McCarthy's avatar
Paul McCarthy committed
410
411
412
413
414
415


    **Return value**


    Functions decorated with a ``_FileOrThing`` decorator will always return a
416
417
418
419
420
    ``dict``-like object, where the function's actual return value is
    accessible via an attribute called `output`. All output arguments with a
    value of ``LOAD`` will be present as dictionary entries, with the keyword
    argument names used as keys. Any ``LOAD``ed output arguments which were not
    generated by the function will not be present in the dictionary.
Paul McCarthy's avatar
Paul McCarthy committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444


    **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)

445
446
            return 'Done'

Paul McCarthy's avatar
Paul McCarthy committed
447
448
449
450

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

451

Paul McCarthy's avatar
Paul McCarthy committed
452
453
        # All arguments are passed through
        # unmodified - the output will be
454
        # saved to a file called atoc.mat.
Paul McCarthy's avatar
Paul McCarthy committed
455
456
        concat('atob.txt', 'btoc.txt', 'atoc.mat')

457
458
459
460
461
462
463
464
465
        # The function's return value
        # is accessed via an attribute called
        # "output" on the dict
        assert concat('atob.txt', 'btoc.txt', 'atoc.mat').output == 'Done'

        # Outputs to be loaded into memory
        # are returned in a dictionary,
        # with argument names as keys.
        atoc = concat('atob.txt', 'btoc.txt', LOAD)['atoc']
Paul McCarthy's avatar
Paul McCarthy committed
466

467
468
469
470
471
472
473
474
475
        # 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**
Paul McCarthy's avatar
Paul McCarthy committed
476
477
478
479
480
481
482
483
484


    ``_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
485
    **as long as** they do not manipulate the return value.
486
487
488
    """


489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
    class _Results(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.

        The decorated function's actual return value is accessible via the
        :meth:`output` property.
        """
        def __init__(self, output):
            self.__output = output

        @property
        def output(self):
            """Access the return value of the decorated function. """
            return self.__output


507
    def __init__(self, func, prepIn, prepOut, load, *things):
Paul McCarthy's avatar
Paul McCarthy committed
508
509
        """Initialise a ``_FileOrThing`` decorator.

510
511
        :arg func:    The function to be decorated.

512
513
        :arg prepIn:  Function which returns a file name to be used in
                      place of an input argument.
Paul McCarthy's avatar
Paul McCarthy committed
514

515
516
        :arg prepOut: Function which generates a file name to use for
                      arguments that were set to :data:`LOAD`.
517

518
519
520
        :arg load:    Function which is called to load items for arguments
                      that were set to :data:`LOAD`. Must accept a file path
                      as its sole argument.
521

522
        :arg things:  Names of all arguments which will be handled by
523
524
525
                      this ``_FileOrThing`` decorator. If not provided,
                      *all* arguments passed to the function will be
                      handled.
526
527
528
529
530
531

        The ``prepIn`` and ``prepOut`` functions must accept the following
        positional arguments:

          - A directory in which all temporary input/output files should be
            stored
Paul McCarthy's avatar
Paul McCarthy committed
532

533
534
535
536
          - The name of the keyword argument to be processed

          - The argument value that was passed in
        """
537
        self.__func    = func
538
539
540
541
        self.__prepIn  = prepIn
        self.__prepOut = prepOut
        self.__load    = load
        self.__things  = things
Paul McCarthy's avatar
Paul McCarthy committed
542
543


544
    def __call__(self, *args, **kwargs):
545
        """Function which calls ``func``, ensuring that any arguments of
Paul McCarthy's avatar
Paul McCarthy committed
546
        type ``Thing`` are saved to temporary files, and any arguments
Paul McCarthy's avatar
Paul McCarthy committed
547
        with the value :data:`LOAD` are loaded and returned.
548

549
        All other arguments are passed through to ``func``.
550
        """
Paul McCarthy's avatar
Paul McCarthy committed
551

552
553
        func     = self.__func
        argnames = namedPositionals(func, args)
554
555

        # Create a tempdir to store any temporary
Paul McCarthy's avatar
Paul McCarthy committed
556
        # input/output things, but don't change
557
558
559
560
        # into it, as file paths passed to the
        # function may be relative.
        with tempdir.tempdir(changeto=False) as td:

561
562
            # Replace any things with file names.
            # Also get a list of LOAD outputs
563
564
            args, kwargs, outfiles = self.__prepareArgs(
                td, argnames, args, kwargs)
565
566

            # Call the function
567
            result = func(*args, **kwargs)
568

569
570
571
572
573
574
575
            # make a _Reults object to store
            # the output. If we are decorating
            # another _FileOrThing, the
            # results will get merged together
            # into a single _Results dict.
            if not isinstance(result, _FileOrThing._Results):
                result = _FileOrThing._Results(result)
576

577
578
            # Load the LOADed outputs
            for oname, ofile in outfiles.items():
579

580
581
                if not op.exists(ofile): oval = None
                else:                    oval = self.__load(ofile)
582

583
                result[oname] = oval
584

585
            return result
586
587


588
    def __prepareArgs(self, workdir, argnames, args, kwargs):
589
590
591
592
593
594
595
        """Prepares all input and output arguments to be passed to the
        decorated function. Any arguments with a value of :data:`LOAD` are
        passed to the ``prepOut`` function specified at :meth:`__init__`.
        All other arguments are passed through the ``prepIn`` function.

        :arg workdir: Directory in which all temporary files should be stored.

596
597
598
        :arg args:    Positional arguments to be passed to the decorated
                      function.

599
600
601
602
        :arg kwargs:  Keyword arguments to be passed to the decorated function.

        :returns:     A tuple containing:

603
604
605
                        - An updated copy of ``args``.

                        - An updated copy of ``kwargs``.
606
607
608

                        - A dictionary of ``{ name : filename }`` mappings,
                          for all arguments with a value of ``LOAD``.
609
610
        """

611
        outfiles = dict()
612

613
614
615
        allargs  = {k : v for k, v in zip(argnames, args)}
        allargs.update(kwargs)

616
617
        if len(self.__things) > 0: things = self.__things
        else:                      things = allargs.keys()
618

619
620
621
        for name in things:

            val = allargs.get(name, None)
622

623
            if val is None:
624
625
                continue

626
            if val is LOAD:
627
628
629
630

                outfile = self.__prepOut(workdir, name, val)

                if outfile is not None:
631
                    allargs[ name] = outfile
632
633
                    outfiles[name] = outfile
            else:
Paul McCarthy's avatar
Paul McCarthy committed
634

635
                infile = self.__prepIn(workdir, name, val)
Paul McCarthy's avatar
Paul McCarthy committed
636

637
                if infile is not None:
638
639
640
641
                    allargs[name] = infile

        args   = [allargs.pop(k) for k in argnames]
        kwargs = allargs
642

643
        return args, kwargs, outfiles
644
645


Paul McCarthy's avatar
Paul McCarthy committed
646
647
648
def fileOrImage(*imgargs):
    """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``
649
    image objects or :class:`.Image` objects.
Paul McCarthy's avatar
Paul McCarthy committed
650
651
    """

652
653
654
655
656
657
    # keep track of the input argument
    # types on each call, so we know
    # whether to return a fsl.Image or
    # a nibabel image
    intypes = []

658
    def prepIn(workdir, name, val):
Paul McCarthy's avatar
Paul McCarthy committed
659

660
        infile = None
Paul McCarthy's avatar
Paul McCarthy committed
661

662
663
664
665
666
        if isinstance(val, fslimage.Image):
            intypes.append(fslimage.Image)

        elif isinstance(val, nib.nifti1.Nifti1Image):
            intypes.append(nib.nifti1.Nifti1Image)
667
668
669
670

        if isinstance(val, fslimage.Image):
            val = val.nibImage

Paul McCarthy's avatar
Paul McCarthy committed
671
        if isinstance(val, nib.nifti1.Nifti1Image):
672
            infile = val.get_filename()
Paul McCarthy's avatar
Paul McCarthy committed
673
674
675

            # in-memory image - we have
            # to save it out to a file
676
677
            if infile is None:
                hd, infile = tempfile.mkstemp(fslimage.defaultExt())
Paul McCarthy's avatar
Paul McCarthy committed
678
                os.close(hd)
679
                val.to_filename(infile)
Paul McCarthy's avatar
Paul McCarthy committed
680

681
        return infile
Paul McCarthy's avatar
Paul McCarthy committed
682

683
684
    def prepOut(workdir, name, val):
        return op.join(workdir, '{}.nii.gz'.format(name))
Paul McCarthy's avatar
Paul McCarthy committed
685

686
    def load(path):
Paul McCarthy's avatar
Paul McCarthy committed
687
688
689
        # create an independent in-memory
        # copy of the image file
        img = nib.load(path)
690
691
692
693
694
695
696
697
698
699
700
701
702
703

        # if any arguments were fsl images,
        # that takes precedence.
        if fslimage.Image in intypes:
            return fslimage.Image(img.get_data(), header=img.header)
        # but if all inputs were file names,
        # nibabel takes precedence
        elif nib.nifti1.Nifti1Image in intypes or len(intypes) == 0:
            return nib.nifti1.Nifti1Image(img.get_data(), None, img.header)

        # this function should not be called
        # under any other circumstances
        else:
            raise RuntimeError('Cannot handle type: {}'.format(intypes))
Paul McCarthy's avatar
Paul McCarthy committed
704

705
706
707
708
    def decorator(func):
        fot = _FileOrThing(func, prepIn, prepOut, load, *imgargs)

        def wrapper(*args, **kwargs):
709
710
711
            result = fot(*args, **kwargs)
            intypes[:] = []
            return result
712
713
714
715

        return _update_wrapper(wrapper, func)

    return decorator
Paul McCarthy's avatar
Paul McCarthy committed
716
717
718
719
720
721
722


def fileOrArray(*arrargs):
    """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.
    """

723
    def prepIn(workdir, name, val):
Paul McCarthy's avatar
Paul McCarthy committed
724

725
        infile = None
Paul McCarthy's avatar
Paul McCarthy committed
726
727

        if isinstance(val, np.ndarray):
728
            hd, infile = tempfile.mkstemp('.txt')
Paul McCarthy's avatar
Paul McCarthy committed
729
            os.close(hd)
730
            np.savetxt(infile, val, fmt='%0.18f')
Paul McCarthy's avatar
Paul McCarthy committed
731

732
        return infile
Paul McCarthy's avatar
Paul McCarthy committed
733

734
735
    def prepOut(workdir, name, val):
        return op.join(workdir, '{}.txt'.format(name))
Paul McCarthy's avatar
Paul McCarthy committed
736

737
    load = np.loadtxt
Paul McCarthy's avatar
Paul McCarthy committed
738

739
740
741
742
743
744
745
746
747
    def decorator(func):
        fot = _FileOrThing(func, prepIn, prepOut, load, *arrargs)

        def wrapper(*args, **kwargs):
            return fot(*args, **kwargs)

        return _update_wrapper(wrapper, func)

    return decorator