wrapperutils.py 17.2 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
12
13
14
15
16
17
18
"""This module contains functions and decorators used by the FSL wrapper
functions.

.. autosummary::
   :nosignatures:

   applyArgStyle
   required
   fileOrImage
   fileOrArray
"""
19
20
21
22


import os.path as op
import            os
Paul McCarthy's avatar
Paul McCarthy committed
23
import            sys
24
25
26
27
28
29
30
31
import            inspect
import            tempfile
import            warnings
import            functools
import            collections

import            six
import nibabel as nib
Paul McCarthy's avatar
Paul McCarthy committed
32
import numpy   as np
33
34
35
36
37

import fsl.utils.tempdir as tempdir
import fsl.data.image    as fslimage


Paul McCarthy's avatar
Paul McCarthy committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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.

    This behaviour is only required in Python versions < 3.4.
    """

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

    # Python >= 3.4 does things right
    if sys.version_info[0] * 10 + sys.version_info[1] < 3.4:
        wrapper.__wrapped__ = wrapped
    return wrapper
52
53


Paul McCarthy's avatar
Paul McCarthy committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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
    if sys.version_info[0] * 10 + sys.version_info[1] < 3.4:
        return inspect.unwrap(func)

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

    return func


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.
"""
86
87
88


def applyArgStyle(style, argmap=None, valmap=None, **kwargs):
Paul McCarthy's avatar
Paul McCarthy committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    """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.

    :arg style:  Controls how the ``kwargs`` are converted into command-line
                 options - must be one of the following:
                  - `'-'`: ``-name val``
                  - `'--'`: ``--name val``
                  - `'-='`: ``-name=val``
                  - `'--='`: ``--name=val``

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

Paul McCarthy's avatar
Paul McCarthy committed
123
124
125
126
127
128
129
130
131
132
133
134
    :arg kwargs: Arguments to be converted into command-line options.

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

    if style not in ('-', '--', '-=', '--='):
        raise ValueError('Invalid style: {}'.format(style))

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

    def fmtarg(arg):
135
136
137
138
        if   style in ('-',  '-='):  arg =  '-{}'.format(arg)
        elif style in ('--', '--='): arg = '--{}'.format(arg)
        return arg

Paul McCarthy's avatar
Paul McCarthy committed
139
    def fmtval(val):
140
141
142
143
144
145
146
147
148
149
150
        if     isinstance(val, collections.Sequence) and \
           not isinstance(val, six.string_types):
            return ' '.join([str(v) for v in val])
        else:
            return str(val)

    args = []

    for k, v in kwargs.items():

        k    = argmap.get(k, k)
Paul McCarthy's avatar
Paul McCarthy committed
151
152
153
154
155
156
        mapv = valmap.get(k, fmtval(v))
        k    = fmtarg(k)

        if (mapv is SHOW_IF_TRUE and     v) or \
           (mapv is HIDE_IF_TRUE and not v):
            args.append(k)
157
158
159
160
161
162
163
164
165
166

        elif '=' in style:
            args.append('{}={}'.format(k, mapv))
        else:
            args.extend((k, mapv))

    return args


def required(*reqargs):
167
168
169
170
171
172
173
    """Decorator which makes sure that all specified arguments are present
    before calling the decorated function. Arguments which are not present
    will result in an :exc:`AssertionError`. Use as follows::

        @required('foo')
        def funcWhichRequires_foo(**kwargs):
            foo = kwargs['foo']
174
    """
Paul McCarthy's avatar
Paul McCarthy committed
175

176
    def decorator(func):
Paul McCarthy's avatar
Paul McCarthy committed
177
        def wrapper(*args, **kwargs):
178
            kwargs = argsToKwargs(func, args, kwargs)
179
180
181
            for reqarg in reqargs:
                assert reqarg in kwargs
            return func(**kwargs)
182
        return _update_wrapper(wrapper, func)
183
184
185
    return decorator


186
def argsToKwargs(func, args, kwargs=None):
187
188
    """Given a function, and a sequence of positional arguments destined
    for that function, converts the positional arguments into a dict
Paul McCarthy's avatar
Paul McCarthy committed
189
    of keyword arguments. Used by the :class:`_FileOrThing` class.
190
191
192
193
194
195
196
197
198

    :arg func:   Function which will accept ``args`` as positionals.

    :arg args:   Tuple of positional arguments to be passed to ``func``.

    :arg kwargs: Optional. If provided, assumed to be keyword arguments
                 to be passed to ``func``. The ``args`` are merged into
                 ``kwargs``. A :exc:`ValueError` is raised if one of
                 ``args`` is already present in ``kwargs``.
199
    """
Paul McCarthy's avatar
Paul McCarthy committed
200

201
202
    # Remove any decorators
    # from the function
Paul McCarthy's avatar
Paul McCarthy committed
203
204
    func = _unwrap(func)

205
206
207
    # getargspec is the only way to
    # get the names of positional
    # arguments in Python 2.x.
Paul McCarthy's avatar
Paul McCarthy committed
208
209
210
    if sys.version_info[0] < 3:
        argnames = inspect.getargspec(func).args

211
212
    # But getargspec is deprecated
    # in python 3.x
Paul McCarthy's avatar
Paul McCarthy committed
213
214
215
216
217
218
219
    else:

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

221
222
223
    if kwargs is None: kwargs = dict()
    else:              kwargs = dict(kwargs)

Paul McCarthy's avatar
Paul McCarthy committed
224
    for name, val in zip(argnames, args):
225
226
        if name in kwargs:
            raise ValueError('Argument {} repeated'.format(name))
227
228
229
230
231
        kwargs[name] = val

    return kwargs


Paul McCarthy's avatar
Paul McCarthy committed
232
LOAD = object()
Paul McCarthy's avatar
Paul McCarthy committed
233
234
"""Constant used by the :class:`_FileOrThing` class to indicate that an output
file should be loaded into memory and returned as a Python object.
235
236
237
"""


Paul McCarthy's avatar
Paul McCarthy committed
238
239
240
241
242
243
244
245
246
247
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.

248

Paul McCarthy's avatar
Paul McCarthy committed
249
250
251
252
253
254
255
256
257
258
259
260
    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.

261

Paul McCarthy's avatar
Paul McCarthy committed
262
    **Outputs**
263
264


Paul McCarthy's avatar
Paul McCarthy committed
265
    If an argument is given the special :data:`LOAD` value, it is assumed
Paul McCarthy's avatar
Paul McCarthy committed
266
267
268
    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
269
    and any other arguments with a value of ``LOAD``).
Paul McCarthy's avatar
Paul McCarthy committed
270
271
272
273
274
275


    **Return value**


    Functions decorated with a ``_FileOrThing`` decorator will always return a
276
277
278
279
280
    ``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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304


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

305
306
            return 'Done'

Paul McCarthy's avatar
Paul McCarthy committed
307
308
309
310

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

311

Paul McCarthy's avatar
Paul McCarthy committed
312
313
        # All arguments are passed through
        # unmodified - the output will be
314
        # saved to a file called atoc.mat.
Paul McCarthy's avatar
Paul McCarthy committed
315
316
        concat('atob.txt', 'btoc.txt', 'atoc.mat')

317
318
319
320
321
322
323
324
325
        # 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
326

327
328
329
330
331
332
333
334
335
        # 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
336
337
338
339
340
341
342
343
344
345


    ``_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.
346
347
348
    """


349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    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


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

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

373
374
        :arg prepOut: Function which generates a file name to use for
                      arguments that were set to :data:`LOAD`.
375

376
377
378
        :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.
379

380
381
382
383
384
385
386
387
        :arg things:  Names of all arguments which will be handled by
                      this ``_FileOrThing`` decorator.

        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
388

389
390
391
392
393
394
395
396
          - The name of the keyword argument to be processed

          - The argument value that was passed in
        """
        self.__prepIn  = prepIn
        self.__prepOut = prepOut
        self.__load    = load
        self.__things  = things
Paul McCarthy's avatar
Paul McCarthy committed
397
398


399
400
401
402
    def __call__(self, func):
        """Creates and returns the decorated function. """
        wrapper = functools.partial(self.__wrapper, func)
        return _update_wrapper(wrapper, func)
Paul McCarthy's avatar
Paul McCarthy committed
403

404

405
406
    def __wrapper(self, func, *args, **kwargs):
        """Function which calls ``func``, ensuring that any arguments of
Paul McCarthy's avatar
Paul McCarthy committed
407
        type ``Thing`` are saved to temporary files, and any arguments
Paul McCarthy's avatar
Paul McCarthy committed
408
        with the value :data:`LOAD` are loaded and returned.
409

410
        :arg func: The function being wrapped.
411

412
        All other arguments are passed through to ``func``.
413
        """
Paul McCarthy's avatar
Paul McCarthy committed
414

415
416
        # Turn all positionals into keywords
        kwargs = argsToKwargs(func, args, kwargs)
417
418

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

424
425
426
            # Replace any things with file names.
            # Also get a list of LOAD outputs
            kwargs, outfiles = self.__prepareArgs(td, kwargs)
427
428

            # Call the function
Paul McCarthy's avatar
Paul McCarthy committed
429
            result = func(**kwargs)
430

431
432
433
434
435
436
437
            # 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)
438

439
440
            # Load the LOADed outputs
            for oname, ofile in outfiles.items():
441

442
443
                if not op.exists(ofile): oval = None
                else:                    oval = self.__load(ofile)
444

445
                result[oname] = oval
446

447
            return result
448
449


450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    def __prepareArgs(self, workdir, kwargs):
        """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.

        :arg kwargs:  Keyword arguments to be passed to the decorated function.

        :returns:     A tuple containing:

                        - An updated copy of ``kwargs``, ready to be passed
                          into the function

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

        kwargs   = dict(kwargs)
470
        outfiles = dict()
471

472
        for name in self.__things:
473

474
            val = kwargs.get(name, None)
475

476
            if val is None:
477
478
                continue

479
480
481
482
483
484
485
486
            if val == LOAD:

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

                if outfile is not None:
                    kwargs[  name] = outfile
                    outfiles[name] = outfile
            else:
Paul McCarthy's avatar
Paul McCarthy committed
487

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

490
491
                if infile is not None:
                    kwargs[name] = infile
492

493
        return kwargs, outfiles
494
495


Paul McCarthy's avatar
Paul McCarthy committed
496
497
498
499
500
501
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``
    image objects.
    """

502
    def prepIn(workdir, name, val):
Paul McCarthy's avatar
Paul McCarthy committed
503

504
        infile = None
Paul McCarthy's avatar
Paul McCarthy committed
505
506

        if isinstance(val, nib.nifti1.Nifti1Image):
507
            infile = val.get_filename()
Paul McCarthy's avatar
Paul McCarthy committed
508
509
510

            # in-memory image - we have
            # to save it out to a file
511
512
            if infile is None:
                hd, infile = tempfile.mkstemp(fslimage.defaultExt())
Paul McCarthy's avatar
Paul McCarthy committed
513
                os.close(hd)
514
                val.to_filename(infile)
Paul McCarthy's avatar
Paul McCarthy committed
515

516
        return infile
Paul McCarthy's avatar
Paul McCarthy committed
517

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

521
    def load(path):
Paul McCarthy's avatar
Paul McCarthy committed
522
523
524
525
526
        # create an independent in-memory
        # copy of the image file
        img = nib.load(path)
        return nib.nifti1.Nifti1Image(img.get_data(), None, img.header)

527
    return _FileOrThing(prepIn, prepOut, load, *imgargs)
Paul McCarthy's avatar
Paul McCarthy committed
528
529
530
531
532
533
534


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

535
    def prepIn(workdir, name, val):
Paul McCarthy's avatar
Paul McCarthy committed
536

537
        infile = None
Paul McCarthy's avatar
Paul McCarthy committed
538
539

        if isinstance(val, np.ndarray):
540
            hd, infile = tempfile.mkstemp('.txt')
Paul McCarthy's avatar
Paul McCarthy committed
541
            os.close(hd)
542
            np.savetxt(infile, val, fmt='%0.18f')
Paul McCarthy's avatar
Paul McCarthy committed
543

544
        return infile
Paul McCarthy's avatar
Paul McCarthy committed
545

546
547
    def prepOut(workdir, name, val):
        return op.join(workdir, '{}.txt'.format(name))
Paul McCarthy's avatar
Paul McCarthy committed
548

549
    load = np.loadtxt
Paul McCarthy's avatar
Paul McCarthy committed
550

551
    return _FileOrThing(prepIn, prepOut, load, *arrargs)