test_featanalysis.py 16.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
55
56
57
58
59
60
61
#!/usr/bin/env python
#
# test_featanalysis.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#

import              os
import os.path   as op
import itertools as it
import              glob
import              shutil
import              textwrap
import              collections

import numpy     as np

import pytest

import tests
import fsl.data.featanalysis as featanalysis
import fsl.data.featdesign   as featdesign
import fsl.data.image        as fslimage
import fsl.utils.path        as fslpath


def test_isFEATImage():
    paths = ['analysis.feat/filtered_func_data.nii.gz',
             'analysis.feat/filtered_func_data.txt',
             'analysis.feat/design.fsf',
             'analysis.feat/design.mat',
             'analysis.feat/design.con',
             'analysis.bleat/filtered_func_data.nii.gz']

    with tests.testdir(paths) as testdir:
        for p in paths:
            expected = p == 'analysis.feat/filtered_func_data.nii.gz'
            assert featanalysis.isFEATImage(op.join(testdir, p)) == expected


def test_isFEATDir():

    # We need these files for a directory
    # to be considered a FEAT directory
    paths = ['analysis.feat/filtered_func_data.nii.gz',
             'analysis.feat/design.fsf',
             'analysis.feat/design.mat',
             'analysis.feat/design.con']

    with tests.testdir(paths) as testdir:
        assert featanalysis.isFEATDir(op.join(testdir, 'analysis.feat'))

    # If the directory does not end in .feat,
    # then it's not a feat directory
    with tests.testdir([p.replace('feat', 'bleat') for p in paths]) as testdir:
        assert not featanalysis.isFEATDir(op.join(testdir, 'analysis.bleat'))

    # If the directory doesn't exist, then
    # it's not a feat directory
    assert not featanalysis.isFEATDir('nonexistent.feat')

Paul McCarthy's avatar
Paul McCarthy committed
62
    # If any of the above files are not
63
64
65
66
67
68
69
70
71
    # present, it is not a FEAT directory
    perms = it.chain(it.combinations(paths, 1),
                     it.combinations(paths, 2),
                     it.combinations(paths, 3))
    for p in perms:
        with tests.testdir(p) as testdir:
            assert not featanalysis.isFEATDir(
                op.join(testdir, 'analysis.feat'))

Paul McCarthy's avatar
Paul McCarthy committed
72

73
74
75
76
77
78
79
80
def test_hasStats():

    with tests.testdir(['analysis.feat/stats/zstat1.nii.gz']) as testdir:
        featdir = op.join(testdir, 'analysis.feat')
        assert featanalysis.hasStats(featdir)

    with tests.testdir(['analysis.feat/stats/zstat1.txt']) as testdir:
        featdir = op.join(testdir, 'analysis.feat')
Paul McCarthy's avatar
Paul McCarthy committed
81
        assert not featanalysis.hasStats(featdir)
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96


def test_hasMelodicDir():
    paths = ['analysis.feat/filtered_func_data.ica/melodic_IC.nii.gz']
    with tests.testdir(paths) as testdir:
        featdir = op.join(testdir, 'analysis.feat')
        assert featanalysis.hasMelodicDir(featdir)


def test_getAnalysisDir():

    paths = ['analysis.feat/filtered_func_data.nii.gz',
             'analysis.feat/design.fsf',
             'analysis.feat/design.mat',
             'analysis.feat/design.con']
Paul McCarthy's avatar
Paul McCarthy committed
97

98
99
100
101
102
103
104
105
106
107
108
    testpaths = ['analysis.feat/filtered_func_data.nii.gz',
                 'analysis.feat/stats/zstat1.nii.gz',
                 'analysis.feat/logs/feat4_post',
                 'analysis.feat/.ramp.gif']

    with tests.testdir(paths) as testdir:
        expected = op.join(testdir, 'analysis.feat')
        for t in testpaths:
            t = op.join(testdir, t)
            assert featanalysis.getAnalysisDir(t) == expected

Paul McCarthy's avatar
Paul McCarthy committed
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
def test_getTopLevelAnalysisDir():
    testcases = [
        ('analysis.feat/filtered_func_data.ica/melodic_IC.nii.gz', 'analysis.feat'),
        ('analysis.feat/filtered_func_data.nii.gz', 'analysis.feat'),
        ('analysis.gfeat/cope1.feat/stats/zstat1.nii.gz', 'analysis.gfeat'),
        ('filtered_func_data.ica/melodic_mix', 'filtered_func_data.ica'),
        ('rest.ica/filtered_func_data.ica/melodic_IC.nii.gz', 'rest.ica')
    ]

    for path, expected in testcases:
        assert featanalysis.getTopLevelAnalysisDir(path) == expected


def test_getReportFile():

    testcases = [(['analysis.feat/report.html'], True),
                 (['analysis.feat/filtered_func_data.nii.gz'], False)]

    for paths, expected in testcases:
        with tests.testdir(paths) as testdir:
Paul McCarthy's avatar
Paul McCarthy committed
130

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
            featdir = op.join(testdir, 'analysis.feat')

            if expected:
                expected = op.join(featdir, 'report.html')
            else:
                expected = None

            assert featanalysis.getReportFile(featdir) == expected


def test_loadContrasts():
    # (design.con contents, expected names, expected vectors)
    goodtests = [
        ("""
         /ContrastName1 c1
         /ContrastName2 c2
         /ContrastName3 c3
Paul McCarthy's avatar
Paul McCarthy committed
148
         /NumContrasts 3
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
         /Matrix
         1 0 0
         0 1 0
         0 0 1
         """,
         ['c1', 'c2', 'c3'],
         [[1, 0, 0], [0, 1, 0], [0, 0, 1]]),
        ("""
         /NumContrasts 2
         /Matrix
         1 0 0 0
         0 1 0 0
         """,
         ['1', '2'],
         [[1, 0, 0, 0], [0, 1, 0, 0]]),
        ("""
         /NumContrasts 1
         /ContrastName1 My contrast
         /Matrix
         5
         """,
         ['My contrast'], [[5]])
    ]
    badtests = [
        """
        /Matrix
        1 0 0
        0 1 0
        """,
        """
        /NumContrasts 2
        /Matrix
        1 0
        0 1 1
        """,
        """
        /NumContrasts 3
        /Matrix
        1 0 0
        0 1 1
        """,
    ]
Paul McCarthy's avatar
Paul McCarthy committed
191

192
    with pytest.raises(Exception):
Paul McCarthy's avatar
Paul McCarthy committed
193
        featanalysis.loadContrasts('no file')
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
235
236
237
238
239
240
241
242

    with tests.testdir() as testdir:
        featdir = op.join(testdir, 'analysis.feat')
        for contents, expnames, expvectors in goodtests:
            designcon = op.join(featdir, 'design.con')
            tests.make_dummy_file(designcon, textwrap.dedent(contents).strip())

            result = featanalysis.loadContrasts(featdir)
            assert result[0] == expnames
            assert result[1] == expvectors

        for contents in badtests:
            designcon = op.join(featdir, 'design.con')
            tests.make_dummy_file(designcon, textwrap.dedent(contents).strip())

            with pytest.raises(Exception):
                featanalysis.loadContrasts(featdir)


def test_loadSettings():

    contents = """
    set random_setting true
    any lines that don't start with "set" should be ignored
    # regardless of whether they are commented or not
    set fmri(blah) 0.66
    set something     "quoted"
    set somethingelse 'quotedagain'
    set fmri_thing(no) none
    # set comment commented out
    set athing with spaces in the value
    """

    expected = collections.OrderedDict((
        ('random_setting', 'true'),
        ('blah',           '0.66'),
        ('something',      'quoted'),
        ('somethingelse',  'quotedagain'),
        ('fmri_thing(no)', 'none'),
        ('athing',         'with spaces in the value'),
    ))

    contents = textwrap.dedent(contents).strip()

    with pytest.raises(Exception):
        featanalysis.loadSettings('no file')

    with tests.testdir() as testdir:
        featdir = op.join(testdir, 'analysis.feat')
243
244
245
246
        designfsf = op.join(featdir, 'design.fsf')
        tests.make_dummy_file(designfsf, contents)
        assert featanalysis.loadSettings(featdir) == expected
        assert featanalysis.loadFsf(designfsf) == expected
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277


def test_loadDesign():

    datadir = op.join(op.dirname(__file__), 'testdata', 'test_feat')
    featdir = op.join(datadir, '1stlevel_1.feat')

    settings = featanalysis.loadSettings(featdir)
    design   = featanalysis.loadDesign(featdir, settings)

    assert isinstance(design, featdesign.FEATFSFDesign)
    assert len(design.getEVs())     == 10
    assert design.getDesign().shape == (45, 10)


def test_getThresholds():
    datadir  = op.join(op.dirname(__file__), 'testdata', 'test_feat')
    featdir  = op.join(datadir, '1stlevel_1.feat')
    settings = featanalysis.loadSettings(featdir)

    thresholds = featanalysis.getThresholds(settings)
    assert np.isclose(thresholds['p'], 0.05)
    assert np.isclose(thresholds['z'], 2.3)


def test_isFirstLevelAnalysis():
    datadir  = op.join(op.dirname(__file__), 'testdata', 'test_feat')
    featdirs = ['1stlevel_1.feat',  '1stlevel_2.feat', '1stlevel_3.feat',
                '2ndlevel_1.gfeat', '2ndlevel_2.gfeat']

    for featdir in featdirs:
Paul McCarthy's avatar
Paul McCarthy committed
278

279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
        expected = featdir.startswith('1')
        featdir  = op.join(datadir, featdir)
        settings = featanalysis.loadSettings(featdir)

        assert featanalysis.isFirstLevelAnalysis(settings) == expected


def test_loadClusterResults():
    datadir  = op.join(op.dirname(__file__), 'testdata', 'test_feat')
    featdirs = ['1stlevel_1.feat',  '1stlevel_2.feat', '1stlevel_3.feat',
                '2ndlevel_1.gfeat/cope1.feat', '2ndlevel_1.gfeat/cope2.feat',
                '2ndlevel_2.gfeat/cope1.feat', '2ndlevel_2.gfeat/cope2.feat']
    ncontrasts = [2, 2, 2, 1, 1, 1, 1]
    nclusters  = [[1, 5], [2, 2], [3, 5], [7], [1], [10], [27]]

    with pytest.raises(Exception):
        featanalysis.loadClusterResults('notafeatdir')

    for i, featdir in enumerate(featdirs):

        firstlevel = featdir.startswith('1')
        featdir    = op.join(datadir, featdir)

        with tests.testdir() as testdir:

304
            # work from a copy of the test data directory
305
306
307
308
            newfeatdir = op.join(testdir, 'analysis.feat')
            shutil.copytree(op.join(datadir, featdir), newfeatdir)
            featdir = newfeatdir

309
310
311
312
            # For higher level analyses, the
            # loadClusterResults function peeks
            # at the FEAT input data file
            # header, so we have to generate it.
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
            if not firstlevel:
                datafile = op.join(featdir, 'filtered_func_data.nii.gz')
                data  = np.random.randint(1, 10, (91, 109, 91))
                xform = np.array([[-2, 0, 0,   90],
                                  [ 0, 2, 0, -126],
                                  [ 0, 0, 2,  -72],
                                  [ 0, 0, 0,    1]])
                fslimage.Image(data, xform=xform).save(datafile)

            settings = featanalysis.loadSettings(featdir)
            for c in range(ncontrasts[i]):
                clusters = featanalysis.loadClusterResults(
                    featdir, settings, c)

                assert len(clusters) == nclusters[i][c]

            # Test calling the function on a feat dir
            # which doesn't have any cluster results
            if i == len(featdirs) - 1:
                for clustfile in glob.glob(op.join(featdir, 'cluster*txt')):
                    os.remove(clustfile)
                assert featanalysis.loadClusterResults(
                    featdir, settings, 0) is None

337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    # The above loop just checks that the number of
    # clusters loaded for each analysis was correct.
    # Below we check that the cluster data was loaded
    # correctly, just for one analysis
    featdir  = op.join(datadir, '1stlevel_1.feat')
    settings = featanalysis.loadSettings(featdir)
    cluster  = featanalysis.loadClusterResults(featdir, settings, 0)[0]
    expected = {
        'index'    : 1,
        'nvoxels'  : 296,
        'p'        : 1.79e-27,
        'logp'     : 26.7,
        'zmax'     : 6.03,
        'zmaxx'    : 34,
        'zmaxy'    : 10,
        'zmaxz'    : 1,
        'zcogx'    : 31.4,
        'zcogy'    : 12.3,
        'zcogz'    : 1.72,
        'copemax'  : 612,
        'copemaxx' : 34,
        'copemaxy' : 10,
        'copemaxz' : 1,
        'copemean' : 143
    }

    for k, v in expected.items():
        assert np.isclose(v, getattr(cluster, k))

366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425

def test_getDataFile():
    paths = ['analysis.feat/filtered_func_data.nii.gz',
             'analysis.feat/design.fsf',
             'analysis.feat/design.mat',
             'analysis.feat/design.con']

    with tests.testdir(paths) as testdir:
        featdir = op.join(testdir, 'analysis.feat')
        expect  = op.join(featdir, 'filtered_func_data.nii.gz')

        assert featanalysis.getDataFile(featdir) == expect

    paths = ['analysis.feat/filtered_func_data.txt',
             'analysis.feat/design.fsf',
             'analysis.feat/design.mat',
             'analysis.feat/design.con']

    with tests.testdir(paths) as testdir:
        featdir = op.join(testdir, 'analysis.feat')

        with pytest.raises(fslpath.PathError):
            assert featanalysis.getDataFile(featdir)


def test_getMelodicFile():
    testcases = [
        (['analysis.feat/filtered_func_data.ica/melodic_IC.nii.gz'], True),
        (['analysis.feat/filtered_func_data.ica/melodic_IC.txt'], False),
    ]

    for paths, shouldPass in testcases:
        with tests.testdir(paths) as testdir:
            featdir = op.join(testdir, 'analysis.feat')
            icadir  = op.join(featdir, 'filtered_func_data.ica')
            expect  = op.join(icadir,  'melodic_IC.nii.gz')

            if shouldPass:
                assert featanalysis.getMelodicFile(featdir) == expect
            else:
                with pytest.raises(fslpath.PathError):
                    featanalysis.getMelodicFile(featdir)



def test_getResidualFile():
    testcases = [
        (['analysis.feat/stats/res4d.nii.gz'], True),
        (['analysis.feat/stats/res4d.txt'], False),
    ]

    for paths, shouldPass in testcases:
        with tests.testdir(paths) as testdir:
            featdir = op.join(testdir, 'analysis.feat')
            expect  = op.join(featdir, 'stats', 'res4d.nii.gz')

            if shouldPass:
                assert featanalysis.getResidualFile(featdir) == expect
            else:
                with pytest.raises(fslpath.PathError):
Paul McCarthy's avatar
Paul McCarthy committed
426
427
                    featanalysis.getResidualFile(featdir)

428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449

def test_getPEFile():
    testcases = [
        (['analysis.feat/stats/pe1.nii.gz',
          'analysis.feat/stats/pe2.nii.gz'], True),
        (['analysis.feat/stats/pe1.nii.gz'], True),
        (['analysis.feat/stats/pe0.nii.gz'], False),
        (['analysis.feat/stats/pe1.txt'],    False),
    ]

    for paths, shouldPass in testcases:
        with tests.testdir(paths) as testdir:
            featdir = op.join(testdir, 'analysis.feat')

            for pei in range(len(paths)):
                expect = op.join(
                    featdir, 'stats', 'pe{}.nii.gz'.format(pei + 1))

                if shouldPass:
                    assert featanalysis.getPEFile(featdir, pei) == expect
                else:
                    with pytest.raises(fslpath.PathError):
Paul McCarthy's avatar
Paul McCarthy committed
450
                        featanalysis.getPEFile(featdir, pei)
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473


def test_getCOPEFile():
    testcases = [
        (['analysis.feat/stats/cope1.nii.gz',
          'analysis.feat/stats/cope2.nii.gz'], True),
        (['analysis.feat/stats/cope1.nii.gz'], True),
        (['analysis.feat/stats/cope0.nii.gz'], False),
        (['analysis.feat/stats/cope1.txt'],    False),
    ]

    for paths, shouldPass in testcases:
        with tests.testdir(paths) as testdir:
            featdir = op.join(testdir, 'analysis.feat')

            for ci in range(len(paths)):
                expect = op.join(
                    featdir, 'stats', 'cope{}.nii.gz'.format(ci + 1))

                if shouldPass:
                    assert featanalysis.getCOPEFile(featdir, ci) == expect
                else:
                    with pytest.raises(fslpath.PathError):
Paul McCarthy's avatar
Paul McCarthy committed
474
475
                        featanalysis.getCOPEFile(featdir, ci)

476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497

def test_getZStatFile():
    testcases = [
        (['analysis.feat/stats/zstat1.nii.gz',
          'analysis.feat/stats/zstat2.nii.gz'], True),
        (['analysis.feat/stats/zstat1.nii.gz'], True),
        (['analysis.feat/stats/zstat0.nii.gz'], False),
        (['analysis.feat/stats/zstat1.txt'],    False),
    ]

    for paths, shouldPass in testcases:
        with tests.testdir(paths) as testdir:
            featdir = op.join(testdir, 'analysis.feat')

            for zi in range(len(paths)):
                expect = op.join(
                    featdir, 'stats', 'zstat{}.nii.gz'.format(zi + 1))

                if shouldPass:
                    assert featanalysis.getZStatFile(featdir, zi) == expect
                else:
                    with pytest.raises(fslpath.PathError):
Paul McCarthy's avatar
Paul McCarthy committed
498
499
                        featanalysis.getZStatFile(featdir, zi)

500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521

def test_getClusterMaskFile():
    testcases = [
        (['analysis.feat/cluster_mask_zstat1.nii.gz',
          'analysis.feat/cluster_mask_zstat2.nii.gz'], True),
        (['analysis.feat/cluster_mask_zstat1.nii.gz'], True),
        (['analysis.feat/cluster_mask_zstat0.nii.gz'], False),
        (['analysis.feat/cluster_mask_zstat1.txt'],    False),
    ]

    for paths, shouldPass in testcases:
        with tests.testdir(paths) as testdir:
            featdir = op.join(testdir, 'analysis.feat')

            for ci in range(len(paths)):
                expect = op.join(
                    featdir, 'cluster_mask_zstat{}.nii.gz'.format(ci + 1))

                if shouldPass:
                    assert featanalysis.getClusterMaskFile(featdir, ci) == expect
                else:
                    with pytest.raises(fslpath.PathError):
Paul McCarthy's avatar
Paul McCarthy committed
522
                        featanalysis.getClusterMaskFile(featdir, ci)