test_wrapperutils.py 28.3 KB
Newer Older
1
2
3
4
5
6
7
#!/usr/bin/env python
#
# test_wrapperutils.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#

8
9
10
import os.path as op
import            os
import            shlex
11
import            pathlib
12
13
14
15
import            textwrap

try: from unittest import mock
except ImportError: import mock
16

17
import six
18
19
import pytest

20
21
22
23
import numpy as np
import nibabel as nib

import fsl.utils.tempdir         as tempdir
24
import fsl.utils.run             as run
25
import fsl.utils.fslsub          as fslsub
26
import fsl.data.image            as fslimage
27
28
29
import fsl.wrappers.wrapperutils as wutils


30
31
from .. import mockFSLDIR, cleardir, checkdir, testdir
from ..test_run import mock_submit
32
33


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
86
87
88
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def test_applyArgStyle():

    kwargs = {
        'name'  : 'val',
        'name2' : ['val1', 'val2'],
    }

    # these combinations of style+valsep should
    # raise an error
    with pytest.raises(ValueError):
        wutils.applyArgStyle(style='-=',  valsep=' ', **kwargs)
    with pytest.raises(ValueError):
        wutils.applyArgStyle(style='--=', valsep=' ', **kwargs)

    # unsupported style/valsep
    with pytest.raises(ValueError):
        wutils.applyArgStyle('?', **kwargs)
    with pytest.raises(ValueError):
        wutils.applyArgStyle('-', valsep='b', **kwargs)

    # style, valsep, expected_result.
    # Order of arguments is not guaranteed
    tests = [
        ('-',   ' ', [' -name  val', '-name2   val1 val2']),
        ('-',   '"', [' -name  val', '-name2  "val1 val2"']),
        ('-',   ',', [' -name  val', '-name2   val1,val2']),

        ('--',  ' ', ['--name  val', '--name2  val1 val2']),
        ('--',  '"', ['--name  val', '--name2 "val1 val2"']),
        ('--',  ',', ['--name  val', '--name2  val1,val2']),

        ('-=',  '"', [' -name=val', '-name2="val1 val2"']),
        ('-=',  ',', [' -name=val', '-name2=val1,val2']),

        ('--=', '"', ['--name=val', '--name2="val1 val2"']),
        ('--=', ',', ['--name=val', '--name2=val1,val2']),
    ]

    for style, valsep, exp in tests:
        exp    = [shlex.split(e) for e in exp]
        result = wutils.applyArgStyle(style, valsep=valsep, **kwargs)

        assert result in (exp[0] + exp[1], exp[1] + exp[0])


def test_applyArgStyle_argmap():

    kwargs = {
        'name1' : 'val1',
        'name2' : 'val2',
    }

    argmap = {
        'name1' : 'n',
        'name2' : 'm',
    }

    # order not guaranteed
    exp = [shlex.split('-n val1 -m val2'),
           shlex.split('-m val2 -n val1')]

    assert wutils.applyArgStyle('-', argmap=argmap, **kwargs) in exp


def test_applyArgStyle_valmap():

    valmap = {
        'a' : wutils.SHOW_IF_TRUE,
        'b' : wutils.HIDE_IF_TRUE,
    }

    # kwargs, expected
    tests = [
        ({                          }, ['']),
        ({ 'a' : False,             }, ['']),
        ({ 'a' : True,              }, ['-a']),
        ({              'b' : False }, ['-b']),
        ({              'b' : True  }, ['']),
        ({ 'a' : False, 'b' : True  }, ['']),
        ({ 'a' : True,  'b' : True  }, ['-a']),
        ({ 'a' : False, 'b' : False }, ['-b']),
        ({ 'a' : False, 'b' : True  }, ['']),
        ({ 'a' : True,  'b' : False }, ['-a -b', '-b -a']),
        ({ 'a' : True,  'b' : True  }, ['-a']),
    ]

    for kwargs, expected in tests:
        expected = [shlex.split(e) for e in expected]
        assert wutils.applyArgStyle('-', valmap=valmap, **kwargs) in expected


def test_applyArgStyle_argmap_valmap():

    argmap = {'a1' : 'a', 'a2' : 'b'}
    valmap = {
        'a' : wutils.SHOW_IF_TRUE,
        'b' : wutils.HIDE_IF_TRUE,
    }

    # kwargs, expected
    tests = [
        ({                            }, ['']),
        ({ 'a1' : False,              }, ['']),
        ({ 'a1' : True,               }, ['-a']),
        ({               'a2' : False }, ['-b']),
        ({               'a2' : True  }, ['']),
        ({ 'a1' : False, 'a2' : True  }, ['']),
        ({ 'a1' : True,  'a2' : True  }, ['-a']),
        ({ 'a1' : False, 'a2' : False }, ['-b']),
        ({ 'a1' : False, 'a2' : True  }, ['']),
        ({ 'a1' : True,  'a2' : False }, ['-a -b', '-b -a']),
        ({ 'a1' : True,  'a2' : True  }, ['-a']),
    ]

    for kwargs, expected in tests:
        expected = [shlex.split(e) for e in expected]
        assert wutils.applyArgStyle(
            '-', argmap=argmap, valmap=valmap, **kwargs) in expected


Paul McCarthy's avatar
Paul McCarthy committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def test_namedPositionals():
    def func1(): pass
    def func2(a, b, c): pass
    def func3(a, b, c, d=None, e=None): pass
    def func4(*args): pass
    def func5(*args, **kwargs): pass
    def func6(a, b, *args): pass
    def func7(a, b, *args, **kwargs): pass

    tests = [
        (func1, [],        []),
        (func2, [1, 2, 3], ['a', 'b', 'c']),
        (func3, [1, 2, 3], ['a', 'b', 'c']),
        (func4, [1, 2, 3], ['args0', 'args1', 'args2']),
        (func5, [1, 2, 3], ['args0', 'args1', 'args2']),
        (func6, [1, 2, 3], ['a', 'b', 'args0']),
        (func7, [1, 2, 3], ['a', 'b', 'args0']),
    ]

    for func, args, expected in tests:
        result = wutils.namedPositionals(func, args)
        assert list(result) == list(expected)
176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

def test_fileOrArray():

    @wutils.fileOrArray('arr1', 'other', 'output')
    def func(arr1, **kwargs):
        arr1  = np.loadtxt(arr1)
        other = np.loadtxt(kwargs['other'])
        np.savetxt(kwargs['output'], (arr1 * other))

    with tempdir.tempdir():

        arr1     = np.array([[1,  2], [ 3,  4]])
        other    = np.array([[5,  6], [ 7,  8]])
        expected = np.array([[5, 12], [21, 32]])
        np.savetxt('arr1.txt',  arr1)
        np.savetxt('other.txt', other)

        # file  file  file
        func('arr1.txt', other='other.txt', output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # file  file  array
        result = func('arr1.txt', other='other.txt', output=wutils.LOAD)['output']
        assert np.all(result == expected)

        # file  array file
        func('arr1.txt', other=other, output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # file  array array
        result = func('arr1.txt', other=other, output=wutils.LOAD)['output']
        assert np.all(result == expected)

        # array file  file
        func(arr1, other='other.txt', output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # array file  array
        result = func(arr1, other='other.txt', output=wutils.LOAD)['output']
        assert np.all(result == expected)

        # array array file
        func(arr1, other=other, output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # array array array
        result = func(arr1, other=other, output=wutils.LOAD)['output']
        assert np.all(result == expected)


def test_fileOrImage():

    @wutils.fileOrImage('img1', 'img2', 'output')
    def func(img1, **kwargs):
Paul McCarthy's avatar
Paul McCarthy committed
235
        img1   = np.asanyarray(nib.load(img1).dataobj)
Paul McCarthy's avatar
Paul McCarthy committed
236
        img2   = np.asanyarray(nib.load(kwargs['img2']).dataobj)
237
238
239
240
241
242
243
        output = nib.nifti1.Nifti1Image(img1 * img2, np.eye(4))
        nib.save(output, kwargs['output'])

    with tempdir.tempdir():

        img1     = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
        img2     = nib.nifti1.Nifti1Image(np.array([[5,  6], [ 7,  8]]), np.eye(4))
244
        img3     = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
245
246
247
248
249
250
        expected = np.array([[5, 12], [21, 32]])
        nib.save(img1, 'img1.nii')
        nib.save(img2, 'img2.nii')

        # file  file  file
        func('img1.nii', img2='img2.nii', output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
251
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
252
253
254
255
        os.remove('output.nii')

        # file  file  array
        result = func('img1.nii', img2='img2.nii', output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
256
        assert np.all(np.asanyarray(result.dataobj) == expected)
257
258
259

        # file  array file
        func('img1.nii', img2=img2, output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
260
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
261
262
263
264
        os.remove('output.nii')

        # file  array array
        result = func('img1.nii', img2=img2, output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
265
        assert np.all(np.asanyarray(result.dataobj) == expected)
266
267
268

        # array file  file
        func(img1, img2='img2.nii', output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
269
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
270
271
272
273
        os.remove('output.nii')

        # array file  array
        result = func(img1, img2='img2.nii', output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
274
        assert np.all(np.asanyarray(result.dataobj) == expected)
275
276
277

        # array array file
        func(img1, img2=img2, output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
278
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
279
280
281
282
        os.remove('output.nii')

        # array array array
        result = func(img1, img2=img2, output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
283
        assert np.all(np.asanyarray(result.dataobj) == expected)
284

285
286
        # in-memory image, file, file
        result = func(img3, img2='img2.nii', output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
287
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
288
289
        os.remove('output.nii')

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
        # fslimage, file, load
        result = func(fslimage.Image(img1), img2='img2.nii',
                      output=wutils.LOAD)['output']
        assert isinstance(result, fslimage.Image)
        assert np.all(result[:].squeeze() == expected)

        # fslimage, fslimage, load
        result = func(fslimage.Image(img1), img2=fslimage.Image(img2),
                      output=wutils.LOAD)['output']
        assert isinstance(result, fslimage.Image)
        assert np.all(result[:].squeeze() == expected)

        # fslimage, nib.image, load
        result = func(fslimage.Image(img1), img2=img2,
                      output=wutils.LOAD)['output']
        assert isinstance(result, fslimage.Image)
        assert np.all(result[:].squeeze() == expected)

        # nib.image, nib.image, load
        result = func(img1, img2=img2, output=wutils.LOAD)['output']
        assert isinstance(result, nib.nifti1.Nifti1Image)
Paul McCarthy's avatar
Paul McCarthy committed
311
        assert np.all(np.asanyarray(result.dataobj)[:] == expected)
312

313

314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def test_fileOrThing_sequence():

    @wutils.fileOrArray('arrs', 'out')
    def func(arrs, out):

        if isinstance(arrs, six.string_types):
            arrs = [arrs]

        arrs = [np.loadtxt(a) for a in arrs]
        res  = np.sum(arrs, axis=0)

        np.savetxt(out, res)

    inputs  = [np.random.randint(1, 10, (3, 3)) for i in range(4)]
    infiles = ['input{}.txt'.format(i) for i in range(len(inputs))]
    exp     = np.sum(inputs, axis=0)

    with tempdir.tempdir():

        for ifile, idata in zip(infiles, inputs):
            np.savetxt(ifile, idata)

        func(inputs, 'result.txt')
        assert np.all(np.loadtxt('result.txt') == exp)

        assert np.all(func(inputs, wutils.LOAD)['out'] == exp)

        func(inputs[0], 'result.txt')
        assert np.all(np.loadtxt('result.txt') == inputs[0])

        assert np.all(func(inputs[0], wutils.LOAD)['out'] == inputs[0])

        func(infiles, 'result.txt')
        assert np.all(np.loadtxt('result.txt') == exp)

        assert np.all(func(infiles, wutils.LOAD)['out'] == exp)

        func(infiles[0], 'result.txt')
        assert np.all(np.loadtxt('result.txt') == inputs[0])

        assert np.all(func(infiles[0], wutils.LOAD)['out'] == inputs[0])


357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def test_fileOrText():

    @wutils.fileOrText('input', 'output')
    def func(input, output):
        data = open(input).read()
        data = ''.join(['{}{}'.format(c, c) for c in data])
        open(output, 'wt').write(data)

    with tempdir.tempdir():

        data = 'abcdefg'
        exp  = 'aabbccddeeffgg'

        open('input.txt', 'wt').write(data)

        func(pathlib.Path('input.txt'), pathlib.Path('output.txt'))
        assert open('output.txt').read() == exp

        func('abcdefg', pathlib.Path('output.txt'))
        assert open('output.txt').read() == exp

        assert func('12345', wutils.LOAD).output == '1122334455'


381
def test_fileOrThing_outprefix():
382
383
384

    @wutils.fileOrImage('img', outprefix='output_base')
    def basefunc(img, output_base):
Paul McCarthy's avatar
Paul McCarthy committed
385
        img = np.asanyarray(nib.load(img).dataobj)
386
387
388
389
390
391
392

        out1 = nib.nifti1.Nifti1Image(img * 5,  np.eye(4))
        out2 = nib.nifti1.Nifti1Image(img * 10, np.eye(4))

        nib.save(out1, '{}_times5.nii.gz' .format(output_base))
        nib.save(out2, '{}_times10.nii.gz'.format(output_base))

393

394
395
    with tempdir.tempdir() as td:
        img  = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
Paul McCarthy's avatar
Paul McCarthy committed
396
397
        exp1 = np.asanyarray(img.dataobj) * 5
        exp2 = np.asanyarray(img.dataobj) * 10
398
399
400
        nib.save(img, 'img.nii')

        basefunc('img.nii', 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
401
402
        assert np.all(np.asanyarray(nib.load('myout_times5.nii.gz') .dataobj) == exp1)
        assert np.all(np.asanyarray(nib.load('myout_times10.nii.gz').dataobj) == exp2)
403
404
405
        cleardir(td, 'myout*')

        basefunc(img, 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
406
407
        assert np.all(np.asanyarray(nib.load('myout_times5.nii.gz') .dataobj) == exp1)
        assert np.all(np.asanyarray(nib.load('myout_times10.nii.gz').dataobj) == exp2)
408
409
410
        cleardir(td, 'myout*')

        res = basefunc(img, 'myout', myout_times5=wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
411
        assert np.all(np.asanyarray(res['myout_times5'].dataobj) == exp1)
412
413
414
        cleardir(td, 'myout*')

        res = basefunc(img, 'myout', myout_times10=wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
415
        assert np.all(np.asanyarray(res['myout_times10'].dataobj) == exp2)
416
417
418
        cleardir(td, 'myout*')

        res = basefunc(img, 'myout', myout=wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
419
420
        assert np.all(np.asanyarray(res['myout_times5'] .dataobj) == exp1)
        assert np.all(np.asanyarray(res['myout_times10'].dataobj) == exp2)
421
422
423
        cleardir(td, 'myout*')


424
def test_fileOrThing_outprefix_differentTypes():
425
426
427
428
429

    @wutils.fileOrImage('img', outprefix='outpref')
    def func(img, outpref):

        img  = nib.load(img)
Paul McCarthy's avatar
Paul McCarthy committed
430
        img  = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 2, np.eye(4))
431
432
433
434
435
436
437
438
439
        text = '1234567890'

        nib.save(img, '{}_image.nii.gz' .format(outpref))

        with open('{}_text.txt'.format(outpref), 'wt') as f:
            f.write(text)

    with tempdir.tempdir() as td:
        img  = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
Paul McCarthy's avatar
Paul McCarthy committed
440
        expi = np.asanyarray(img.dataobj) * 2
441
442
443
        expt = '1234567890'

        func(img, 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
444
        assert np.all(np.asanyarray(nib.load('myout_image.nii.gz') .dataobj) == expi)
445
446
447
448
449
450
        with open('myout_text.txt', 'rt') as f:
            assert f.read().strip() == expt
        cleardir(td, 'myout*')

        res = func(img, 'myout', myout_image=wutils.LOAD)
        assert list(res.keys()) == ['myout_image']
Paul McCarthy's avatar
Paul McCarthy committed
451
        assert np.all(np.asanyarray(res['myout_image'].dataobj) == expi)
452
453
454
455
        cleardir(td, 'myout*')

        res = func(img, 'myout', myout=wutils.LOAD)
        assert list(res.keys()) == ['myout_image']
Paul McCarthy's avatar
Paul McCarthy committed
456
        assert np.all(np.asanyarray(res['myout_image'].dataobj) == expi)
457
458
459
460
461
462
463
        cleardir(td, 'myout*')

        res = func(img, 'myout', myout_text=wutils.LOAD)
        assert list(res.keys()) == []
        cleardir(td, 'myout*')


464
def test_fileOrThing_outprefix_directory():
465
466
467
468
469
470
471
472

    import logging
    logging.basicConfig()
    logging.getLogger('fsl.wrappers').setLevel(logging.DEBUG)

    @wutils.fileOrImage('img', outprefix='outpref')
    def func(img, outpref):
        img  = nib.load(img)
Paul McCarthy's avatar
Paul McCarthy committed
473
474
        img2 = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 2, np.eye(4))
        img4 = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 4, np.eye(4))
475

476
        outdir = op.abspath('{}_imgs'.format(outpref))
477

478
        os.mkdir(outdir)
479

480
481
        nib.save(img2, op.join(outdir, 'img2.nii.gz'))
        nib.save(img4, op.join(outdir, 'img4.nii.gz'))
482

483
484
    with tempdir.tempdir() as td:
        img  = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
Paul McCarthy's avatar
Paul McCarthy committed
485
486
        exp2 = np.asanyarray(img.dataobj) * 2
        exp4 = np.asanyarray(img.dataobj) * 4
487
488
489
490
491
492
493

        res = func(img, 'myout')
        assert len(res) == 0
        checkdir(td,
                 op.join('myout_imgs', 'img2.nii.gz'),
                 op.join('myout_imgs', 'img4.nii.gz'))
        cleardir(td, 'myout*')
494

495
496
        res = func(img, 'myout', myout_imgs=wutils.LOAD)
        assert len(res) == 2
Paul McCarthy's avatar
Paul McCarthy committed
497
498
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img2')].dataobj) == exp2)
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img4')].dataobj) == exp4)
499

Paul McCarthy's avatar
Paul McCarthy committed
500
        res = func(img, 'myout', **{op.join('myout_imgs', 'img2') : wutils.LOAD})
501
        assert len(res) == 1
Paul McCarthy's avatar
Paul McCarthy committed
502
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img2')].dataobj) == exp2)
503

Paul McCarthy's avatar
Paul McCarthy committed
504
        res = func(img, 'myout', **{op.join('myout_imgs', 'img') : wutils.LOAD})
505
        assert len(res) == 2
Paul McCarthy's avatar
Paul McCarthy committed
506
507
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img2')].dataobj) == exp2)
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img4')].dataobj) == exp4)
508
509

        os.mkdir('foo')
Paul McCarthy's avatar
Paul McCarthy committed
510
        res = func(img, op.join('foo', 'myout'))
511
512
513
514
515
516
517
        assert len(res) == 0
        checkdir(td,
                 op.join('foo', 'myout_imgs', 'img2.nii.gz'),
                 op.join('foo', 'myout_imgs', 'img4.nii.gz'))
        cleardir(td, 'foo')

        os.mkdir('foo')
Paul McCarthy's avatar
Paul McCarthy committed
518
        res = func(img, op.join('foo', 'myout'), **{op.join('foo', 'myout') : wutils.LOAD})
519
        assert len(res) == 2
Paul McCarthy's avatar
Paul McCarthy committed
520
521
        assert np.all(np.asanyarray(res[op.join('foo', 'myout_imgs', 'img2')].dataobj) == exp2)
        assert np.all(np.asanyarray(res[op.join('foo', 'myout_imgs', 'img4')].dataobj) == exp4)
522

523

524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588

def test_fileOrThing_results():
    @wutils.fileOrArray('input', 'regular_output', outprefix='outpref')
    def func(input, regular_output, outpref):

        input = np.loadtxt(input)

        regout   = input * 2
        prefouts = []
        for i in range(3, 6):
            prefouts.append(input * i)

        np.savetxt(regular_output, regout)
        for i, o in enumerate(prefouts):
            np.savetxt('{}_{}.txt'.format(outpref, i), o)

        return ('return', 'value')

    input  = np.random.randint(1, 10, (3, 3))
    infile = 'input.txt'
    exp    = [input * i for i in range(2, 6)]

    with tempdir.tempdir():

        np.savetxt(infile, input)

        result = func('input.txt', 'regout.txt', 'outpref')
        assert len(result) == 0
        assert result.stdout == ('return', 'value')
        assert (np.loadtxt('regout.txt') == exp[0]).all()
        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

        result = func(input, 'regout.txt', 'outpref')
        assert len(result) == 0
        assert result.stdout == ('return', 'value')
        assert (np.loadtxt('regout.txt') == exp[0]).all()
        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

        result = func(input, wutils.LOAD, 'outpref')
        assert len(result) == 1
        assert result.stdout == ('return', 'value')
        assert (result .regular_output == exp[0]).all()
        assert (result['regular_output'] == exp[0]).all()
        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

        # todo outpref
        result = func(input, wutils.LOAD, wutils.LOAD)
        assert len(result) == 4
        assert result.stdout == ('return', 'value')
        assert (result .regular_output == exp[0]).all()
        assert (result['regular_output'] == exp[0]).all()

        assert (result .outpref_0   == exp[1]).all()
        assert (result['outpref_0'] == exp[1]).all()
        assert (result .outpref_1   == exp[2]).all()
        assert (result['outpref_1'] == exp[2]).all()
        assert (result .outpref_2   == exp[3]).all()
        assert (result['outpref_2'] == exp[3]).all()

        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

Paul McCarthy's avatar
Paul McCarthy committed
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
        result = func(input, wutils.LOAD, wutils.LOAD)
        assert len(result) == 4


def test_FileOrThing_invalid_identifiers():
    # unlikely to ever happen, but let's test arguments with
    # names that are not valid python identifiers
    @wutils.fileOrArray('in val', '2out')
    def func(**kwargs):

        infile  = kwargs['in val']
        outfile = kwargs['2out']

        input = np.loadtxt(infile)
        np.savetxt(outfile, input * 2)

        return ('return', 'value')

    input  = np.random.randint(1, 10, (3, 3))
    infile = 'input.txt'
    exp    = input * 2

    with tempdir.tempdir():

        np.savetxt(infile, input)

        res = func(**{'in val' : infile, '2out' : 'output.txt'})
        assert res.stdout == ('return', 'value')
        assert (np.loadtxt('output.txt') == exp).all()

        res = func(**{'in val' : input, '2out' : 'output.txt'})
        assert res.stdout == ('return', 'value')
        assert (np.loadtxt('output.txt') == exp).all()

        res = func(**{'in val' : input, '2out' : wutils.LOAD})
        assert res.stdout == ('return', 'value')
        assert (res['2out'] == exp).all()

627
628


629
def test_chained_fileOrImageAndArray():
630
631
632
633
634
635
    @wutils.fileOrImage('image', 'outimage')
    @wutils.fileOrArray('array', 'outarray')
    def func(image, array, outimage, outarray):
        image = nib.load(image)
        array = np.loadtxt(array)

Paul McCarthy's avatar
Paul McCarthy committed
636
        outimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
637
638
639

        np.savetxt(outarray, array * 2)
        outimg.to_filename(outimage)
640
641
642
643

    image = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
    array = np.array([[5, 6, 7, 8]])

Paul McCarthy's avatar
Paul McCarthy committed
644
    expimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
645
646
    exparr = array * 2

647
648
649
650
651
    with tempdir.tempdir():

        nib.save(image, 'image.nii')
        np.savetxt('array.txt', array)

652
        func('image.nii', 'array.txt', 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
653
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
654
655
656
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        func('image.nii', array, 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
657
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
658
659
660
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        func( image, 'array.txt', 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
661
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
662
663
664
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        func( image, array, 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
665
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
666
667
668
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        res = func(image, array, wutils.LOAD, 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
669
        assert np.all(np.asanyarray(res['outimage'].dataobj) == np.asanyarray(expimg.dataobj))
670
671
672
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        res = func(image, array, 'outimg.nii', wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
673
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
674
675
676
        assert np.all(res['outarray'] == exparr)

        res = func(image, array, wutils.LOAD, wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
677
        assert np.all(np.asanyarray(res['outimage'].dataobj) == np.asanyarray(expimg.dataobj))
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
        assert np.all(res['outarray'] == exparr)


def test_fileOrThing_chained_outprefix():

    import logging
    logging.basicConfig()
    logging.getLogger('fsl.wrappers').setLevel(logging.DEBUG)

    @wutils.fileOrImage('image', 'outimage', outprefix='out')
    @wutils.fileOrArray('array', 'outarray', outprefix='out')
    def func(image, array, out, **kwa):

        image = nib.load(image)
        array = np.loadtxt(array)

Paul McCarthy's avatar
Paul McCarthy committed
694
        outimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
695
696
697
698
699
700
701
702
        outarr = array * 2

        np.savetxt('{}_array.txt'.format(out), outarr)
        outimg.to_filename('{}_image.nii'.format(out))

    image = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
    array = np.array([[5, 6, 7, 8]])

Paul McCarthy's avatar
Paul McCarthy committed
703
    expimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
704
705
706
707
708
    exparr = array * 2

    with tempdir.tempdir():

        func(image, array, 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
709
        assert np.all(np.asanyarray(nib.load('myout_image.nii').dataobj) == np.asanyarray(expimg.dataobj))
710
711
712
        assert np.all(np.loadtxt('myout_array.txt') == exparr)

        res = func(image, array, wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
713
        assert np.all(np.asanyarray(res['out_image'].dataobj) == np.asanyarray(expimg.dataobj))
714
        assert np.all(res['out_array'] == exparr)
715
716


717
def test_fileOrThing_submit_cmdonly():
718
719

    @wutils.fileOrImage('input', 'output')
720
    def func(input, output, submit=False, cmdonly=False):
721
722
723

        if submit:
            return 'submitted!'
724
725
        if cmdonly:
            return 'cmdonly!'
726
727
728
729
730
731
732
733
734
735
736
737
738
739

        img = nib.load(input)
        img = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 2, np.eye(4))

        nib.save(img, output)

    with tempdir.tempdir() as td:
        img = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
        exp = np.asanyarray(img.dataobj) * 2
        nib.save(img, 'input.nii.gz')

        result = func(img, wutils.LOAD)
        assert np.all(np.asanyarray(result['output'].dataobj) == exp)

740
741
        assert func('input.nii.gz', 'output.nii.gz', submit=True)  == 'submitted!'
        assert func('input.nii.gz', 'output.nii.gz', cmdonly=True) == 'cmdonly!'
742
743
744
745
746
747
748
749
750

        with pytest.raises(ValueError):
            func(img, wutils.LOAD, submit=True)
        with pytest.raises(ValueError):
            func(img, 'output.nii.gz', submit=True)
        with pytest.raises(ValueError):
            func('input.nii.gz', wutils.LOAD, submit=True)


751
752
753
754
755
756
757
758
def test_cmdwrapper():
    @wutils.cmdwrapper
    def func(a, b):
        return ['func', str(a), str(b)]

    with run.dryrun():
        assert func(1, 2)[0] == 'func 1 2'

Paul McCarthy's avatar
Paul McCarthy committed
759
760
    assert func(1, 2, cmdonly=True) == ['func', '1', '2']

761
762
763
764
765
766

def test_fslwrapper():
    @wutils.fslwrapper
    def func(a, b):
        return ['func', str(a), str(b)]

Paul McCarthy's avatar
Paul McCarthy committed
767
    with mockFSLDIR(bin=('func',)) as fsldir:
768
        expected = '{} 1 2'.format(op.join(fsldir, 'bin', 'func'))
Paul McCarthy's avatar
Paul McCarthy committed
769
770
771
        with run.dryrun():
            assert func(1, 2)[0] == expected

772
        assert func(1, 2, cmdonly=True) == list(shlex.split(expected))
773
774
775
776
777
778
779
780
781
782
783
784
785


_test_script = textwrap.dedent("""
#!/usr/bin/env bash
echo "test_script running: $1 $2"
exit 0
""").strip()


def _test_script_func(a, b):
    return ['test_script', str(a), str(b)]


Paul McCarthy's avatar
Paul McCarthy committed
786
@pytest.mark.unixtest
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
def test_cmdwrapper_submit():

    test_func = wutils.cmdwrapper(_test_script_func)
    newpath = op.pathsep.join(('.', os.environ['PATH']))

    with tempdir.tempdir(), \
         mock.patch('fsl.utils.fslsub.submit', mock_submit), \
         mock.patch.dict(os.environ, {'PATH' : newpath}):

        with open('test_script', 'wt') as f:
            f.write(_test_script)
        os.chmod('test_script', 0o755)

        jid = test_func(1, 2, submit=True)

802
        assert jid == '12345'
803
804
805
806
807
808
809

        stdout, stderr = fslsub.output('12345')

        assert stdout.strip() == 'test_script running: 1 2'
        assert stderr.strip() == ''


Paul McCarthy's avatar
Paul McCarthy committed
810
@pytest.mark.unixtest
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def test_fslwrapper_submit():

    test_func = wutils.fslwrapper(_test_script_func)

    with mockFSLDIR() as fsldir, \
         mock.patch('fsl.utils.fslsub.submit', mock_submit):

        test_file = op.join(fsldir, 'bin', 'test_script')

        with open(test_file, 'wt') as f:
            f.write(_test_script)
        os.chmod(test_file, 0o755)

        jid = test_func(1, 2, submit=True)

Paul McCarthy's avatar
Paul McCarthy committed
826
        assert jid == '12345'
827
828
829
830
831
832
833
834
835
836

        stdout, stderr = fslsub.output('12345')

        assert stdout.strip() == 'test_script running: 1 2'
        assert stderr.strip() == ''

        kwargs = {'name' : 'abcde', 'ram' : '4GB'}

        jid = test_func(1, 2, submit=kwargs)

Paul McCarthy's avatar
Paul McCarthy committed
837
        assert jid == '12345'
838
839
840

        stdout, stderr = fslsub.output('12345')

Paul McCarthy's avatar
Paul McCarthy committed
841
842
        experr = '\n'.join(['{}: {}'.format(k, kwargs[k])
                            for k in sorted(kwargs.keys())])
843
844
845

        assert stdout.strip() == 'test_script running: 1 2'
        assert stderr.strip() == experr
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863


@pytest.mark.unixtest
def test_cmdwrapper_fileorthing_cmdonly():

    test_func = wutils.fileOrImage('a')(wutils.cmdwrapper(_test_script_func))
    newpath   = op.pathsep.join(('.', os.environ['PATH']))
    with tempdir.tempdir(), \
         mock.patch.dict(os.environ, {'PATH' : newpath}):

        with open('test_script', 'wt') as f:
            f.write(_test_script)
        os.chmod('test_script', 0o755)

        ran = test_func('1', '2')
        cmd = test_func('1', '2', cmdonly=True)
        assert ran.stdout[0].strip() == 'test_script running: 1 2'
        assert cmd                   == ['test_script', '1', '2']