Пример #1
0
def test_getMeanFile():
    paths = [
        'analysis.ica/melodic_IC.nii.gz', 'analysis.ica/melodic_mix',
        'analysis.ica/melodic_FTmix', 'analysis.ica/mean.nii.gz'
    ]

    paths = [op.join(*p.split('/')) for p in paths]

    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        expected = op.join(testdir, 'analysis.ica', 'mean.nii.gz')

        assert mela.getMeanFile(meldir) == expected

    paths = [
        'analysis.ica/melodic_IC.nii.gz', 'analysis.ica/melodic_mix',
        'analysis.ica/melodic_FTmix', 'analysis.ica/mean.txt'
    ]

    paths = [op.join(*p.split('/')) for p in paths]

    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        with pytest.raises(fslpath.PathError):
            mela.getMeanFile(meldir)
Пример #2
0
def test_MelodicImage_create():

    # non existent
    with pytest.raises(Exception):
        meli.MelodicImage('badfile')

    # bad file
    paths = [
        'analysis.ica/melodic_IC.nii.gz', 'analysis.ica/melodic_mix',
        'analysis.ica/melodic_FTmix'
    ]
    with tests.testdir(paths) as testdir:
        path = op.join(testdir, 'analysis.ica/melodic_IC.nii.gz')
        with pytest.raises(Exception):
            meli.MelodicImage(path)

    with tests.testdir() as testdir:
        meldir = _create_dummy_melodic_analysis(testdir)
        icfile = op.join(meldir, 'melodic_IC.nii.gz')
        icfilenosuf = op.join(meldir, 'melodic_IC')

        # Should be able to specify the
        # melodic dir, or the IC image
        meli.MelodicImage(meldir)
        meli.MelodicImage(icfile)
        meli.MelodicImage(icfilenosuf)
Пример #3
0
def test_MelodicImage_create():

    # non existent
    with pytest.raises(Exception):
        meli.MelodicImage('badfile')

    # bad file
    paths = [
        'analysis.ica/melodic_IC.nii.gz', 'analysis.ica/melodic_mix',
        'analysis.ica/melodic_FTmix'
    ]
    paths = [op.join(*p.split('/')) for p in paths]
    with tests.testdir(paths) as testdir:
        path = op.join(testdir, 'analysis.ica', 'melodic_IC.nii.gz')
        with pytest.raises(Exception):
            meli.MelodicImage(path)

    for ic_prefix in ['melodic_IC', 'melodic_oIC']:

        with tests.testdir() as testdir:
            meldir = _create_dummy_melodic_analysis(testdir,
                                                    ic_prefix=ic_prefix)
            icfile = op.join(meldir, '{}.nii.gz'.format(ic_prefix))
            icfilenosuf = op.join(meldir, ic_prefix)

            # Should be able to specify the
            # melodic dir, or the IC image
            i = meli.MelodicImage(meldir)
            i = meli.MelodicImage(icfile)
            i = meli.MelodicImage(icfilenosuf)
            i = None
Пример #4
0
def test_MelodicImage_tr():

    # If data file not present, tr should default to 1.0
    with tests.testdir() as testdir:
        meldir = _create_dummy_melodic_analysis(testdir, with_data=False)
        img = meli.MelodicImage(meldir)

        assert img.tr == 1

    # Otherwise, it should be set to the datafile tr
    with tests.testdir() as testdir:
        meldir = _create_dummy_melodic_analysis(testdir, tr=5)
        img = meli.MelodicImage(meldir)
        assert img.tr == 5

    # The TR can be updated
    with tests.testdir() as testdir:

        cbCalled = [False]

        def trChanged(*a):
            cbCalled[0] = True

        meldir = _create_dummy_melodic_analysis(testdir, with_data=False)
        img = meli.MelodicImage(meldir)

        img.register('cbname', trChanged, topic='tr')

        img.tr = 8

        assert cbCalled[0]
        assert img.tr == 8
Пример #5
0
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')

    # If any of the above files are not
    # 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'))
Пример #6
0
def test_getAnalysisDir():
    paths = [
        'analysis.ica/melodic_IC.nii.gz', 'analysis.ica/melodic_mix',
        'analysis.ica/melodic_FTmix'
    ]

    testpaths = [
        'analysis.ica/melodic_IC.nii.gz', 'analysis.ica/log.txt',
        'analysis.ica/stats/thresh_zstat1.nii.gz',
        'analysis.ica/report/00index.html'
    ]

    with tests.testdir(paths) as testdir:
        expected = op.join(testdir, 'analysis.ica')
        for tp in testpaths:
            assert mela.getAnalysisDir(op.join(testdir, tp)) == expected

    paths = [
        'analysis.ica/melodic_blob.nii.gz', 'analysis.ica/melodic_mix',
        'analysis.ica/melodic_FTmix'
    ]

    with tests.testdir(paths) as testdir:
        for tp in testpaths:
            assert mela.getAnalysisDir(op.join(testdir, tp)) is None
Пример #7
0
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')
        assert not featanalysis.hasStats(featdir)
Пример #8
0
def test_getFTMixFile():
    paths = ['analysis.ica/melodic_IC.nii.gz',
             'analysis.ica/melodic_mix',
             'analysis.ica/melodic_FTmix']

    with tests.testdir(paths) as testdir:
        meldir   = op.join(testdir, 'analysis.ica')
        expected = op.join(testdir, 'analysis.ica/melodic_FTmix')
        assert mela.getFTMixFile(meldir) == expected
        
    paths = ['analysis.ica/melodic_IC.ni.gz',
             'analysis.ica/melodic_mix']
    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        assert mela.getFTMixFile(meldir) is None 
Пример #9
0
def test_init_writeOnExit():

    atexit_funcs = []

    def mock_atexit_register(func, *args, **kwargs):
        atexit_funcs.append((func, args, kwargs))

    testdata = {
        'setting1': 123,
        'setting2': 'Blahblah',
        'setting3': [1, 2, ('three', 4)]
    }

    with tests.testdir() as testdir, \
         mock.patch('fsl.utils.settings.atexit.register', mock_atexit_register):

        s = settings.Settings('test', cfgdir=testdir)

        for k, v in testdata.items():
            s.write(k, v)

        assert len(atexit_funcs) == 1

        f, a, kwa = atexit_funcs[0]
        f(*a, **kwa)

        with open(op.join(testdir, 'config.pkl'), 'rb') as f:
            readback = pickle.load(f)
            assert testdata == readback
Пример #10
0
def test_listFiles():

    ns1files  = ['namespace1/setting1.txt',
                 'namespace1/setting2.txt',
                 'namespace1/setting3.txt']
    ns2files  = ['namespace2/setting1.txt',
                 'namespace2/setting2.txt',
                 'namespace2/setting3.txt']

    with tests.testdir() as testdir:

        s = settings.Settings(cfgid='test', cfgdir=testdir, writeOnExit=False)

        assert s.listFiles() == []

        for fn in ns1files + ns2files:
            with s.writeFile(fn) as f:
                f.write(fn)

        assert list(sorted(s.listFiles())) == list(sorted(ns1files + ns2files))

        assert list(sorted(s.listFiles('namespace1/*'))) == list(sorted(ns1files))
        assert list(sorted(s.listFiles('namespace2/*'))) == list(sorted(ns2files))
        assert list(sorted(s.listFiles('namespace?/*'))) == list(sorted(ns1files + ns2files))
        assert list(sorted(s.listFiles('*.txt')))        == list(sorted(ns1files + ns2files))

        assert list(sorted(s.listFiles('*/setting1.txt'))) == list(sorted([ns1files[0]] + [ns2files[0]]))
Пример #11
0
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')
        designfsf = op.join(featdir, 'design.fsf')
        tests.make_dummy_file(designfsf, contents)
        assert featanalysis.loadSettings(featdir) == expected
        assert featanalysis.loadFsf(designfsf) == expected
Пример #12
0
def test_clear():

    testsettings = [('setting1', '1'), ('setting2', '2'), ('setting3', '3')]
    testfiles = [('path/to/file1.txt', 'testfile1 contents'),
                 ('path/to/another/file2.txt', 'testfile2 contents'),
                 ('file3.txt', 'testfile3 contents')]

    # TODO File

    with tests.testdir() as testdir:

        s = settings.Settings(cfgid='test', cfgdir=testdir, writeOnExit=False)

        for k, v in testsettings:
            s.write(k, v)

        for p, c in testfiles:
            with s.writeFile(p) as f:
                f.write(c)

        for k, v in testsettings:
            assert s.read(k) == v

        for p, c in testfiles:
            assert s.readFile(p) == c

        s.clear()

        for k, v in testsettings:
            assert s.read(k) is None

        for p, c in testfiles:
            assert s.readFile(p) is None
Пример #13
0
def test_loadLabelFile_customLabels():

    included = [2, 3, 4, 5]
    contents = '[{}]\n'.format([i + 1 for i in included])

    defIncLabel = 'Unclassified noise'
    defExcLabel = 'Signal'

    with tests.testdir() as testdir:
        fname = op.join(testdir, 'labels.txt')

        with open(fname, 'wt') as f:
            f.write(contents)

        # Check default labels
        _, labels = fixlabels.loadLabelFile(fname)
        for i, ilbls in enumerate(labels):
            assert len(ilbls) == 1
            if i in included:
                assert ilbls[0] == defIncLabel
            else:
                assert ilbls[0] == defExcLabel

        # Check custom labels
        incLabel = 'Included'
        excLabel = 'Excluded label'
        _, labels = fixlabels.loadLabelFile(fname,
                                            includeLabel=incLabel,
                                            excludeLabel=excLabel)
        for i, ilbls in enumerate(labels):
            assert len(ilbls) == 1
            if i in included:
                assert ilbls[0] == incLabel
            else:
                assert ilbls[0] == excLabel
Пример #14
0
def test_save():

    expected = textwrap.dedent("""
    1, Signal, Default mode, False
    2, Unknown, False
    3, Unclassified noise, True
    4, Movement, True
    [3, 4]
    """).strip()

    lbls = vollbls.VolumeLabels(4)
    lbls.addLabel(0, 'Signal')
    lbls.addLabel(0, 'Default mode')
    lbls.addLabel(1, 'Unknown')
    lbls.addLabel(2, 'Unclassified noise')
    lbls.addLabel(3, 'Movement')

    with tests.testdir() as testdir:

        fname = op.join(testdir, 'labels.txt')

        # Test saving without dirname
        lbls.save(fname)
        exp = '.\n{}'.format(expected)
        with open(fname, 'rt') as f:
            assert f.read().strip() == exp.strip()

        # And with dirname
        lbls.save(fname, 'path/to/analysis.ica')
        exp = 'path/to/analysis.ica\n{}'.format(expected)

        with open(fname, 'rt') as f:
            assert f.read().strip() == exp.strip()
Пример #15
0
def test_load_aromafile():

    contents = """2, 3, 5""".strip()
    expected = [['unknown'], ['movement'], ['movement'], ['unknown'],
                ['movement']]

    with tests.testdir() as testdir:
        fname = op.join(testdir, 'labels.txt')
        with open(fname, 'wt') as f:
            f.write(contents)

        # Too many labels in the file
        lblobj = vollbls.VolumeLabels(3)
        with pytest.raises(fixlbls.InvalidLabelFileError):
            lblobj.load(fname)

        # Not enough labels in the file -
        # this is ok. Remaining labels
        # should be given 'Unknown'
        lblobj = vollbls.VolumeLabels(6)
        lblobj.load(fname)
        for i in range(4):
            assert lblobj.getLabels(i) == expected[i]
        assert lblobj.getLabels(5) == ['unknown']

        # Right number of labels
        lblobj = vollbls.VolumeLabels(5)
        lblobj.load(fname)
        for i in range(4):
            assert lblobj.getLabels(i) == expected[i]
Пример #16
0
def test_DTIFitTensor():

    with tests.testdir() as testdir:

        with pytest.raises(Exception):
            dtifit.DTIFitTensor(testdir)

        v1file = op.join(testdir, 'dti_V1.nii')
        v2file = op.join(testdir, 'dti_V2.nii')
        v3file = op.join(testdir, 'dti_V3.nii')
        l1file = op.join(testdir, 'dti_L1.nii')
        l2file = op.join(testdir, 'dti_L2.nii')
        l3file = op.join(testdir, 'dti_L3.nii')

        v1 = tests.make_random_image(v1file, (5, 5, 5, 3)).get_data()
        v2 = tests.make_random_image(v2file, (5, 5, 5, 3)).get_data()
        v3 = tests.make_random_image(v3file, (5, 5, 5, 3)).get_data()
        l1 = tests.make_random_image(l1file, (5, 5, 5))   .get_data()
        l2 = tests.make_random_image(l2file, (5, 5, 5))   .get_data()
        l3 = tests.make_random_image(l3file, (5, 5, 5))   .get_data()

        dtiobj = dtifit.DTIFitTensor(testdir)

        assert np.all(np.isclose(dtiobj.V1()[:], v1))
        assert np.all(np.isclose(dtiobj.V2()[:], v2))
        assert np.all(np.isclose(dtiobj.V3()[:], v3))
        assert np.all(np.isclose(dtiobj.L1()[:], l1))
        assert np.all(np.isclose(dtiobj.L2()[:], l2))
        assert np.all(np.isclose(dtiobj.L3()[:], l3))

        v1 = fslimage.Image(v1file)

        assert np.all(np.isclose(dtiobj.voxToWorldMat, v1.voxToWorldMat))
        assert np.all(np.isclose(dtiobj.shape[:3],     v1.shape[:3]))
        assert np.all(np.isclose(dtiobj.pixdim[:3],    v1.pixdim[:3]))
Пример #17
0
def _test_image_indexed_read4D(threaded):

    with tests.testdir() as testdir:

        filename = op.join(testdir, 'image.nii.gz')

        # Data range grows with volume
        nvols = 50
        data = np.zeros((50, 50, 50, nvols))
        for vol in range(nvols):
            data[..., vol] = vol

        fslimage.Image(data).save(filename)

        img = fslimage.Image(filename,
                             loadData=False,
                             calcRange=False,
                             indexed=True,
                             threaded=threaded)

        # Test reading slice through
        # 4D (e.g. voxel time course)
        #
        # n.b. This is SUPER SLOW!!
        voxels = tests.random_voxels((50, 50, 50), 5)
        for i, xyz in enumerate(voxels):

            x, y, z = [int(v) for v in xyz]
            data = img[x, y, z, :]

            if threaded:
                img.getImageWrapper().getTaskThread().waitUntilIdle()

            assert np.all(data == np.arange(nvols))
Пример #18
0
def test_getDataFile():

    testcases = [
        ([
            'analysis.ica/filtfunc.ica/melodic_IC.nii.gz',
            'analysis.ica/filtfunc.ica/melodic_mix',
            'analysis.ica/filtfunc.ica/melodic_FTmix',
            'analysis.ica/filtered_func_data.nii.gz'
        ], 'analysis.ica/filtfunc.ica',
         'analysis.ica/filtered_func_data.nii.gz'),
        ([
            'analysis.feat/filtfunc.ica/melodic_IC.nii.gz',
            'analysis.feat/filtfunc.ica/melodic_mix',
            'analysis.feat/filtfunc.ica/melodic_FTmix',
            'analysis.feat/filtered_func_data.nii.gz'
        ], 'analysis.feat/filtfunc.ica',
         'analysis.feat/filtered_func_data.nii.gz'),
        (['no/analysis/dirs/here/melodic_IC.nii.gz'], 'no/analysis/dirs/here/',
         None),
        ([
            'analysis.feat/analysis.ica/melodic_IC.nii.gz',
            'analysis.feat/analysis.ica/melodic_mix',
            'analysis.feat/analysis.ica/melodic_FTmix'
        ], 'analysis.feat/analysis.ica', None),
    ]

    for paths, meldir, expected in testcases:
        paths = [op.join(*p.split('/')) for p in paths]
        if expected is not None:
            expected = op.join(*expected.split('/'))
        with tests.testdir(paths) as testdir:
            assert mela.getDataFile(meldir) == expected
Пример #19
0
def test_initialise():

    # Assuming that initialise()
    # has not yet been called
    assert settings.read('nothing') is None
    assert settings.read('nothing', 'default') == 'default'
    settings.write('nothing', 'nothing')
    settings.delete('nothing')
    assert settings.readFile('nothing') is None
    settings.writeFile('nothing', 'nothing')
    settings.deleteFile('nothing')
    assert settings.filePath() is None
    assert settings.readAll() == {}
    assert settings.listFiles() == []
    settings.clear()

    with tests.testdir() as testdir:

        settings.initialise(cfgid='test', cfgdir=testdir, writeOnExit=False)

        assert settings.settings.configID == 'test'
        assert settings.settings.configDir == testdir

        settings.write('setting', 'value')

        assert settings.read('setting') == 'value'
        assert settings.read('nothing') is None
Пример #20
0
def test_loadLabelFile_good():

    for filecontents, expMelDir, expLabels, expIdxs in goodfiles:

        with tests.testdir() as testdir:

            if expMelDir is not None:
                expMelDir = op.join(testdir, expMelDir)

            fname = op.join(testdir, 'labels.txt')
            with open(fname, 'wt') as f:
                f.write(filecontents.strip())

            resMelDir, resLabels = fixlabels.loadLabelFile(fname)
            assert resMelDir == expMelDir
            assert len(resLabels) == len(expLabels)
            for exp, res in zip(expLabels, resLabels):
                assert exp == res

            resMelDir, resLabels, resIdxs = fixlabels.loadLabelFile(
                fname, returnIndices=True)
            assert resMelDir == expMelDir
            assert resIdxs == expIdxs
            assert len(resLabels) == len(expLabels)
            for exp, res in zip(expLabels, resLabels):
                assert exp == res
Пример #21
0
def test_writeConfigFile():

    with tests.testdir() as testdir:

        testdata = {
            'setting1': 123,
            'setting2': 'Blahblah',
            'setting3': [1, 2, ('three', 4)]
        }

        s = settings.Settings(cfgid='test', cfgdir=testdir, writeOnExit=False)

        for k, v in testdata.items():
            s.write(k, v)

        for k, v in testdata.items():
            assert s.read(k) == v

        s.writeConfigFile()

        with open(op.join(testdir, 'config.pkl'), 'rb') as f:
            readback = pickle.load(f)
            assert testdata == readback

        # should fail gracefuly
        # if write is not possible
        s = settings.Settings(cfgid='test', cfgdir=testdir, writeOnExit=False)

    # testdir has been removed,
    # but call should not crash
    s.writeConfigFile()
Пример #22
0
def test_readall():

    testsettings = [('namespace1.setting1', '1'),
                    ('namespace1.setting2', '2'),
                    ('namespace1.setting3', '3'),
                    ('namespace2.setting1', '4'),
                    ('namespace2.setting2', '5'),
                    ('namespace2.setting3', '6')]

    with tests.testdir() as testdir:

        s = settings.Settings(cfgid='test', cfgdir=testdir, writeOnExit=False)

        assert s.readAll() == {}

        for k, v in testsettings:
            s.write(k, v)

        assert s.readAll() == dict(testsettings)

        ns1 = [(k, v) for k, v in testsettings if k.startswith('namespace1')]
        ns2 = [(k, v) for k, v in testsettings if k.startswith('namespace2')]

        assert s.readAll('namespace1.*') == dict(ns1)
        assert s.readAll('namespace2.*') == dict(ns2)
        assert s.readAll('*setting*')    == dict(testsettings)
Пример #23
0
def test_FEATImage_imageAccessors():

    for featdir in TEST_ANALYSES.keys():

        shape = TEST_ANALYSES[featdir]['shape']
        xform = TEST_ANALYSES[featdir]['xform']

        with tests.testdir() as testdir:

            if 'realdata' not in featdir:
                featdir = tests.make_mock_feat_analysis(
                    op.join(datadir, featdir), testdir, shape, xform)
            else:
                featdir = op.join(datadir, featdir)

            shape4D = shape
            shape = shape4D[:3]

            fi = featimage.FEATImage(featdir)
            nevs = fi.numEVs()
            ncons = fi.numContrasts()

            # Testing the FEATImage intenral cache
            for i in range(2):
                assert fi.getResiduals().shape == shape4D

                for ev in range(nevs):
                    assert fi.getPE(ev).shape == shape
                for con in range(ncons):
                    assert fi.getCOPE(con).shape == shape
                    assert fi.getZStats(con).shape == shape
                    assert fi.getClusterMask(con).shape == shape
Пример #24
0
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):
                        featanalysis.getClusterMaskFile(featdir, ci)
Пример #25
0
def test_extra_atlases():

    with tests.testdir() as testdir:

        atlas1spec = _make_dummy_atlas(testdir, 'My atlas 1', 'myatlas1',
                                       'MyAtlas1')
        atlas2spec = _make_dummy_atlas(testdir, 'My atlas 2', 'myatlas2',
                                       'MyAtlas2')

        badspec = op.join(testdir, 'badSpec.xml')
        with open(badspec, 'wt') as f:
            f.write('Bwahahahah!')

        extraAtlases = ':'.join([
            'myatlas1={}'.format(atlas1spec), 'myatlas2={}'.format(atlas2spec),
            'badatlas1=non-existent-path', 'badatlas2={}'.format(badspec)
        ])

        with mock.patch('fsl.data.atlases.fslsettings.read',
                        return_value=extraAtlases), \
             mock.patch('fsl.data.atlases.fslsettings.write',
                        return_value=None):

            reg = atlases.registry
            reg.rescanAtlases()

            assert reg.hasAtlas('myatlas1')
            assert reg.hasAtlas('myatlas2')
            assert not reg.hasAtlas('badatlas1')
            assert not reg.hasAtlas('badatlas2')
Пример #26
0
def test_getNumComponents():
    paths = ['analysis.ica/melodic_IC.nii.gz',
             'analysis.ica/melodic_mix',
             'analysis.ica/melodic_FTmix']

    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        icfile = op.join(meldir,  'melodic_IC.nii.gz')

        tests.make_random_image(icfile, (10, 10, 10, 17))

        assert mela.getNumComponents(meldir) == 17

    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        with pytest.raises(Exception):
            mela.getNumComponents(meldir)
Пример #27
0
def test_readdefault():

    with tests.testdir() as testdir:

        s = settings.Settings(cfgid='test', cfgdir=testdir, writeOnExit=False)

        assert s.read('non-existent') is None
        assert s.read('non-existent', 'default') == 'default'
Пример #28
0
def test_getReportFile():
    paths = ['analysis.ica/filtfunc.ica/melodic_IC.nii.gz',
             'analysis.ica/filtfunc.ica/melodic_mix',
             'analysis.ica/filtfunc.ica/melodic_FTmix',
             'analysis.ica/report.html']

    with tests.testdir(paths) as testdir:
        meldir   = op.join(testdir, 'analysis.ica/filtfunc.ica')
        expected = op.join(testdir, 'analysis.ica/report.html')
        assert op.abspath(mela.getReportFile(meldir)) == expected
        
    paths = ['analysis.ica/filtfunc.ica/melodic_IC.ni.gz',
             'analysis.ica/filtfunc.ica/melodic_mix',
             'analysis.ica/filtfunc.ica/melodic_FTmix']
    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        assert mela.getReportFile(meldir) is None 
Пример #29
0
def test_getICFile():
    paths = ['analysis.ica/melodic_IC.nii.gz',
             'analysis.ica/melodic_mix',
             'analysis.ica/melodic_FTmix']

    with tests.testdir(paths) as testdir:
        meldir   = op.join(testdir, 'analysis.ica')
        expected = op.join(testdir, 'analysis.ica/melodic_IC.nii.gz')
        assert mela.getICFile(meldir) == expected
        
    paths = ['analysis.ica/melodic_IC.txt',
             'analysis.ica/melodic_mix',
             'analysis.ica/melodic_FTmix']

    with tests.testdir(paths) as testdir:
        meldir = op.join(testdir, 'analysis.ica')
        with pytest.raises(fslpath.PathError):
            mela.getICFile(meldir) 
Пример #30
0
def test_getDTIFitDataPrefix_and_isDTIFitPath():
    def make_dtifit_dir(dir, prefix, suffixes):
        for s in suffixes:
            path = op.join(dir, '{}{}'.format(prefix, s))
            with open(path, 'wt') as f:
                f.write(path)

    prefixes = ['dti', 'blob', 'random-prefix', '01234']
    suffixes = [
        '_V1.nii', '_V2.nii', '_V3.nii', '_L1.nii', '_L2.nii', '_L3.nii'
    ]
    badSuffixes = [
        '_V1.txt', '_V2.nii', '_V3.nii', '_L1.txt', '_L2.tar', '_L3.nii'
    ]

    # Valid dtifit directories
    with tests.testdir() as testdir:
        for p in prefixes:

            tests.cleardir(testdir)
            make_dtifit_dir(testdir, p, suffixes)
            assert dtifit.getDTIFitDataPrefix(testdir) == p
            assert dtifit.isDTIFitPath(testdir)

    # Invalid dtifit dir - one file missing
    with tests.testdir() as testdir:
        make_dtifit_dir(testdir, 'dti', suffixes[:-1])
        assert dtifit.getDTIFitDataPrefix(testdir) is None
        assert not dtifit.isDTIFitPath(testdir)

    # Invalid dtifit dir - non-nifti files
    with tests.testdir() as testdir:
        make_dtifit_dir(testdir, 'dti', badSuffixes)
        assert dtifit.getDTIFitDataPrefix(testdir) is None
        assert not dtifit.isDTIFitPath(testdir)

    # Ambiguous dtifit dir - multiple
    # potential prefixes. Should return
    # the first (alphabetical) one.
    with tests.testdir() as testdir:
        make_dtifit_dir(testdir, 'dti1', suffixes)
        make_dtifit_dir(testdir, 'dti2', suffixes)
        assert dtifit.getDTIFitDataPrefix(testdir) == 'dti1'
        assert dtifit.isDTIFitPath(testdir)