Пример #1
0
def test_fileType():

    cmap = tw.dedent("""
    0.5 0.7 0.1
    0.5 0.7 0.1
    """).strip()

    lut = tw.dedent("""
    1 0.5 0.7 0.1 label
    2 0.5 0.7 0.1 label
    """).strip()

    vest = tw.dedent("""
    %!VEST-LUT
    <-color{0.000000,0.000000,0.000000}->
    <-color{0.010000,0.010000,0.010000}->
    """).strip()

    bad =  tw.dedent("""
    this is not a colour map file
    """).strip()

    with tempdir():
        with open('cmap.txt', 'wt') as f: f.write(cmap)
        with open('lut.txt',  'wt') as f: f.write(lut)
        with open('vest.txt', 'wt') as f: f.write(vest)
        with open('bad.txt',  'wt') as f: f.write(bad)

        assert fslcm.fileType('cmap.txt') == 'cmap'
        assert fslcm.fileType('lut.txt')  == 'lut'
        assert fslcm.fileType('vest.txt') == 'vest'

        with pytest.raises(ValueError):
            fslcm.fileType('bad.txt')
Пример #2
0
def mockFSLDIR(**kwargs):

    from fsl.utils.platform import platform as fslplatform

    oldfsldir    = fslplatform.fsldir
    oldfsldevdir = fslplatform.fsldevdir

    try:
        with tempdir() as td:
            fsldir = op.join(td, 'fsl')
            bindir = op.join(fsldir, 'bin')
            os.makedirs(bindir)
            for subdir, files in kwargs.items():
                subdir = op.join(fsldir, subdir)
                if not op.isdir(subdir):
                    os.makedirs(subdir)
                for fname in files:
                    touch(op.join(subdir, fname))
            fslplatform.fsldir = fsldir
            fslplatform.fsldevdir = None

            path = op.pathsep.join((bindir, os.environ['PATH']))

            with mock.patch.dict(os.environ, {'PATH': path}):
                yield fsldir
    finally:
        fslplatform.fsldir    = oldfsldir
        fslplatform.fsldevdir = oldfsldevdir
Пример #3
0
def run_cli_tests(prefix, tests, extras=None, scene='ortho'):

    if extras is None:
        extras = {}

    glver = os.environ.get('FSLEYES_TEST_GL', '2.1')
    glver = [int(v) for v in glver.split('.')]

    if tuple(glver) < (2, 1):
        exclude = ['tensor', ' sh', '_sh', 'spline', 'mip']
    else:
        exclude = []

    tests     = [t.strip()             for t in tests.split('\n')]
    tests     = [t                     for t in tests if t != '' and t[0] != '#']
    tests     = [re.sub('\s+', ' ', t) for t in tests]
    tests     = [re.sub('#.*', '',  t) for t in tests]
    tests     = [t.strip()             for t in tests]
    allpassed = True

    datadir  = op.join(op.dirname(__file__), 'testdata')
    benchdir = op.join(op.dirname(__file__), 'testdata', 'cli_tests')

    def fill_test(t):
        templates = re.findall('{{(.*?)}}', t)
        for temp in templates:
            t = t.replace('{{' + temp + '}}', eval(temp, {}, extras))
        return t

    with tempdir() as td:

        shutil.copytree(datadir, op.join(td, 'testdata'))
        os.chdir('testdata')

        for test in tests:

            if any([exc in test for exc in exclude]):
                print('CLI test skipped [{}] {}'.format(prefix, test))
                continue

            test      = fill_test(test)
            fname     = test.replace(' ', '_').replace('/', '_')
            fname     = '{}_{}.png'.format(prefix, fname)
            benchmark = op.join(benchdir, fname)
            testfile  = op.join(td, fname)

            try:
                run_render_test(list(test.split()), testfile, benchmark,
                                scene=scene)
                print('CLI test passed [{}] {}'.format(prefix, test))

            except Exception as e:
                allpassed = False
                print('CLI test failed [{}] {}: {}'.format(prefix, test, e))

                if op.exists(testfile):
                    print('Copying {} to {}'.format(testfile, datadir))
                    shutil.copy(testfile, datadir)

    assert allpassed
Пример #4
0
def _test_applyCommandLine(panel, overlayList, displayCtx):

    displayCtx = panel.displayCtx
    panel.sceneOpts.layout = 'horizontal'

    with tempdir():
        img = fslimage.Image(np.random.randint(1, 255, (20, 20, 20)))
        img.save('image.nii.gz')

        applycommandline.applyCommandLineArgs(
            overlayList,
            panel.displayCtx, [
                '-lo', 'vertical', 'image.nii.gz', '-b', '75', '-c', '25',
                '-g', '-0.5'
            ],
            panel=panel,
            blocking=True)

        # scene args are applied asynchronously
        waitUntilIdle()

        assert len(overlayList) == 1
        assert np.all(overlayList[0][:] == img[:])
        img = overlayList[0]
        assert displayCtx.getDisplay(img).brightness == 75
        assert displayCtx.getDisplay(img).contrast == 25
        assert displayCtx.getOpts(img).gamma == -0.5
        assert panel.sceneOpts.layout == 'vertical'
Пример #5
0
def test_fsl_ents():

    with tempdir.tempdir() as td:

        # (npts, ncomps)
        melmix = np.random.randint(1, 100, (100, 20))
        np.savetxt('melodic_mix', melmix)

        sys.argv = ['fsl_ents', td] + '-o out.txt 1 2 3'.split()
        extn.main()
        assert np.all(np.loadtxt('out.txt') == melmix[:, :3])

        with open('labels.txt', 'wt') as f:
            f.write('4, 5, 6, 7')

        extn.main([td] + '-o out.txt -ow 1 2 3 labels.txt'.split())
        assert np.all(np.loadtxt('out.txt') == melmix[:, :7])

        conf1 = np.random.randint(1, 100, (100, 1))
        conf2 = np.random.randint(1, 100, (100, 5))
        np.savetxt('conf1.txt', conf1)
        np.savetxt('conf2.txt', conf2)

        exp = np.hstack((melmix[:, :3], conf1, conf2))
        extn.main([td] + '-o out.txt -c conf1.txt -c conf2.txt -ow 1 2 3'.split())
        assert np.all(np.loadtxt('out.txt') == exp)
Пример #6
0
def _test_ExportDataSeriesAction(panel, overlayList, displayCtx):
    class FileDialog(object):
        ShowModal_return = wx.ID_OK
        GetPath_return = None

        def __init__(self, *a, **kwa):
            pass

        def ShowModal(self):
            return FileDialog.ShowModal_return

        def GetPath(self):
            return FileDialog.GetPath_return

    class MessageDialog(object):
        ShowModal_return = wx.ID_OK

        def __init__(self, *a, **kwa):
            pass

        def ShowModal(self):
            return MessageDialog.ShowModal_return

    displayCtx = panel.displayCtx
    act = eds.ExportDataSeriesAction(overlayList, displayCtx, panel)

    ds1 = ds.DataSeries(None, overlayList, displayCtx, panel)
    ds2 = ds.DataSeries(None, overlayList, displayCtx, panel)
    ds1.setData(np.arange(10), np.random.randint(1, 100, 10))
    ds2.setData(np.arange(10), np.random.randint(1, 100, 10))

    panel.dataSeries.extend((ds1, ds2))
    realYield(500)

    with tempdir.tempdir(), \
         mock.patch('wx.FileDialog', FileDialog), \
         mock.patch('wx.MessageDialog', MessageDialog):

        MessageDialog.ShowModal_return = wx.ID_CANCEL
        act()

        MessageDialog.ShowModal_return = wx.ID_YES
        FileDialog.ShowModal_return = wx.ID_CANCEL
        act()

        MessageDialog.ShowModal_return = wx.ID_NO
        FileDialog.ShowModal_return = wx.ID_OK
        FileDialog.GetPath_return = 'data.txt'
        act()

        assert op.exists('data.txt')
        os.remove('data.txt')

        MessageDialog.ShowModal_return = wx.ID_YES
        FileDialog.ShowModal_return = wx.ID_OK
        FileDialog.GetPath_return = 'data.txt'
        act()
        assert op.exists('data.txt')

    act.destroy()
Пример #7
0
def test_genComponentIndexList():

    with tempdir.tempdir():

        # sequence of 1-indexed integers/file paths
        icomps  = [1, 5, 28, 12, 42, 54]
        fcomps1 = [1, 4, 6, 3, 7]
        fcomps2 = [12, 42, 31, 1, 4, 8]

        with open('comps1.txt', 'wt') as f:
            f.write(','.join([str(l) for l in fcomps1]))
        with open('comps2.txt', 'wt') as f:
            f.write(','.join([str(l) for l in fcomps2]))

        ncomps   = 60
        comps    = icomps + ['comps1.txt', 'comps2.txt']
        expcomps = list(sorted(set(icomps + fcomps1 + fcomps2)))
        expcomps = [c - 1 for c in expcomps]

        assert extn.genComponentIndexList(comps, ncomps) == expcomps

        with pytest.raises(ValueError):
            extn.genComponentIndexList(comps + [-1], 60)
        with pytest.raises(ValueError):
            extn.genComponentIndexList(comps, 40)
Пример #8
0
def test_fsl_ents_badargs():

    with pytest.raises(SystemExit) as e:
        extn.main(['non-existent.ica', '1', '2', '3'])
    assert e.value.code != 0

    with tempdir.tempdir() as td:
        with pytest.raises(SystemExit) as e:
            extn.main([td, 'non-existent.txt', '1', '2', '3'])
        assert e.value.code != 0

        with open('outfile.txt', 'wt') as f:
            f.write('a')

        # overwrite not specified
        with pytest.raises(SystemExit) as e:
            extn.main([td, '-o', 'outfile.txt', '1', '2', '3'])
        assert e.value.code != 0

        with pytest.raises(SystemExit) as e:
            extn.main([td, '-c', 'non-existent.txt', '1', '2', '3'])
        assert e.value.code != 0


        # bad data
        melmix = np.random.randint(1, 100, (100, 5))
        np.savetxt('melodic_mix', melmix)

        with open('labels.txt', 'wt') as f:
            f.write('-1, 0, 1, 2')

        with pytest.raises(SystemExit) as e:
            extn.main([td, 'labels.txt', '1', '2', '3'])
        assert e.value.code != 0
Пример #9
0
def _test_applyCommandLine_baseDir(panel, overlayList, displayCtx):

    displayCtx = panel.displayCtx

    with tempdir():
        basedir = op.join(*'sub/dir/to/test/base/dir/'.split('/'))
        os.makedirs(basedir)

        img = fslimage.Image(np.random.randint(1, 255, (20, 20, 20)))
        img.save(op.join(basedir, 'image.nii.gz'))

        applycommandline.applyCommandLineArgs(
            overlayList,
            panel.displayCtx, [
                '-lo', 'vertical', 'image.nii.gz', '-b', '75', '-c', '25',
                '-g', '-0.5'
            ],
            baseDir=basedir,
            panel=panel,
            blocking=True)

        # scene args are applied asynchronously
        waitUntilIdle()

        assert len(overlayList) == 1
        assert np.all(overlayList[0][:] == img[:])
        img = overlayList[0]
        assert displayCtx.getDisplay(img).brightness == 75
        assert displayCtx.getDisplay(img).contrast == 25
        assert displayCtx.getOpts(img).gamma == -0.5
        assert panel.sceneOpts.layout == 'vertical'
Пример #10
0
def test_loadColourMapFile():

    cmap = tw.dedent("""
    0.0 0.5 1.0
    0.3 0.4 0.5
    0.5 0.6 0.7
    """).strip()

    vest = tw.dedent("""
    %!VEST-LUT
    <-color{0.0,0.5,1.0}->
    <-color{0.3,0.4,0.5}->
    <-color{0.5,0.6,0.7}->
    """).strip()

    exp    = np.array([[0.0, 0.5, 1.0],
                       [0.3, 0.4, 0.5],
                       [0.5, 0.6, 0.7]])
    explut = np.hstack((np.arange(1, 4).reshape(-1, 1), exp))

    with tempdir():
        with open('cmap.txt', 'wt') as f: f.write(cmap)
        with open('vest.txt', 'wt') as f: f.write(vest)

        gotcmap    = fslcm.loadColourMapFile('cmap.txt')
        gotvest    = fslcm.loadColourMapFile('vest.txt')
        gotcmaplut = fslcm.loadColourMapFile('cmap.txt', aslut=True)

        assert np.all(np.isclose(gotcmap,    exp))
        assert np.all(np.isclose(gotvest,    exp))
        assert np.all(np.isclose(gotcmaplut, explut))
def _test_report(panel, overlayList, displayCtx):
    overlayList.append(Image(op.join(datadir, '3d')))
    realYield()
    with tempdir(), MockFileDialog() as dlg:
        dlg.ShowModal_retval = wx.ID_OK
        dlg.GetPath_retval = 'report.txt'
        panel.frame.menuActions[report.DiagnosticReportAction]()
        assert op.exists('report.txt')
Пример #12
0
def test_run():

    test_script = textwrap.dedent("""
    #!/bin/bash

    echo "standard output - arguments: $@"
    echo "standard error" >&2
    exit {}
    """).strip()

    with tempdir.tempdir():

        # return code == 0
        mkexec('script.sh', test_script.format(0))

        expstdout = "standard output - arguments: 1 2 3\n"
        expstderr = "standard error\n"

        # test:
        #   - single string
        #   - packed sequence
        #   - unpacked sequence
        assert run.run('./script.sh 1 2 3') == expstdout
        assert run.run(('./script.sh', '1', '2', '3')) == expstdout
        assert run.run(*('./script.sh', '1', '2', '3')) == expstdout

        # test stdout/stderr
        stdout, stderr = run.run('./script.sh 1 2 3', stderr=True)
        assert stdout == expstdout
        assert stderr == expstderr

        # test return code
        res = run.run('./script.sh 1 2 3', exitcode=True)
        stdout, ret = res
        assert stdout == expstdout
        assert ret == 0
        stdout, stderr, ret = run.run('./script.sh 1 2 3',
                                      stderr=True,
                                      exitcode=True)
        assert stdout == expstdout
        assert stderr == expstderr
        assert ret == 0

        # stdout=False
        res = run.run('./script.sh 1 2 3', stdout=False)
        assert res == ()
        stderr = run.run('./script.sh 1 2 3', stdout=False, stderr=True)
        assert stderr == expstderr

        # return code != 0
        mkexec('./script.sh', test_script.format(255))

        with pytest.raises(RuntimeError):
            run.run('./script.sh 1 2 3')

        stdout, ret = run.run('./script.sh 1 2 3', exitcode=True)
        assert stdout == expstdout
        assert ret == 255
Пример #13
0
def test_func_to_cmd():
    with fslsub_mockFSLDIR(), tempdir():
        cmd = fslsub.func_to_cmd(myfunc, (), {})
        jid = fslsub.submit(cmd)

        stdout, stderr = fslsub.output(jid)

        assert stdout.strip() == 'standard output'
        assert stderr.strip() == 'standard error'
Пример #14
0
 def __screenshot(self, view=None):
     """Insert a screenshot of the given view panel into the notebook.
     If ``view`` is not specified, the first view is assumed.
     """
     if view is None:
         view = self.__frame.viewPanels[0]
     with tempdir.tempdir():
         screenshot.screenshot(view, 'screenshot.png')
         return display.Image('screenshot.png')
Пример #15
0
def _test_Image_orientation(imgtype, voxorient):
    """Test the Nifti.isNeurological and Nifti.getOrientation methods. """

    with tempdir() as testdir:
        imagefile = op.join(testdir, 'image')

        # an image with RAS voxel storage order
        # (affine has a positive determinant)
        # is said to be "neurological", whereas
        # an image with LAS voxel storage order
        # (negative determinant - x axis must
        # be flipped to bring it into RAS nifti
        # world coordinates)) is said to be
        # "radiological".  The make_image function
        # forms the affine from these pixdims.
        if voxorient == 'neuro': pixdims = (1, 1, 1)
        elif voxorient == 'radio': pixdims = (-1, 1, 1)

        make_image(imagefile, imgtype, (10, 10, 10), pixdims, np.float32)

        image = fslimage.Image(imagefile, mmap=False)

        # analyze images are always assumed to be
        # stored in radiological (LAS) orientation
        if imgtype == 0:
            expectNeuroTest = False
            expectvox0Orientation = constants.ORIENT_R2L
            expectvox1Orientation = constants.ORIENT_P2A
            expectvox2Orientation = constants.ORIENT_I2S

        elif voxorient == 'neuro':
            expectNeuroTest = True
            expectvox0Orientation = constants.ORIENT_L2R
            expectvox1Orientation = constants.ORIENT_P2A
            expectvox2Orientation = constants.ORIENT_I2S
        else:
            expectNeuroTest = False
            expectvox0Orientation = constants.ORIENT_R2L
            expectvox1Orientation = constants.ORIENT_P2A
            expectvox2Orientation = constants.ORIENT_I2S

        assert image.isNeurological() == expectNeuroTest

        # All images should have the
        # same orientation in the
        # world coordinate system
        assert image.getOrientation(0, np.eye(4)) == constants.ORIENT_L2R
        assert image.getOrientation(1, np.eye(4)) == constants.ORIENT_P2A
        assert image.getOrientation(2, np.eye(4)) == constants.ORIENT_I2S

        # But the voxel orientation
        # is dependent on the affine
        affine = image.voxToWorldMat
        assert image.getOrientation(0, affine) == expectvox0Orientation
        assert image.getOrientation(1, affine) == expectvox1Orientation
        assert image.getOrientation(2, affine) == expectvox2Orientation
        image = None
Пример #16
0
def mockdir(contents):
    with tempdir():
        for c in contents:
            dirname = op.dirname(c)
            if dirname != '' and not op.exists(dirname):
                os.makedirs(dirname)
            with open(c, 'wt') as f:
                pass
        yield
Пример #17
0
def test_tempdir_changeto():

    cwd = op.realpath(os.getcwd())

    # make sure cwd is not changed
    with tempdir.tempdir(changeto=False):
        assert op.realpath(os.getcwd()) == cwd

    assert op.realpath(os.getcwd()) == cwd
Пример #18
0
def mockSettings():
    with tempdir() as td:
        fakesettings = fslsettings.Settings('fsleyes',
                                            cfgdir=td,
                                            writeOnExit=False)
        os.makedirs(op.join(td, 'colourmaps'))
        os.makedirs(op.join(td, 'luts'))
        with fslsettings.use(fakesettings):
            yield td
Пример #19
0
def test_tempdir():

    # use ctx manager with or without arg
    with tempdir.tempdir():
        d = os.getcwd()

    # dir is removed after ctx manager exit
    assert not op.exists(d)

    with tempdir.tempdir() as td:

        d = td

        assert op.exists(d)

        # pwd is dir when in ctx manager
        assert op.realpath(os.getcwd()) == op.realpath(td)

    assert not op.exists(d)
Пример #20
0
def test_immv_badExt():
    with tempdir():

        with open('file.nii.gz', 'wt') as f:
            f.write('1')

        result = immv_script.main(['file.nii', 'dest'])

        assert result == 0
        assert op.exists('dest.nii.gz')
Пример #21
0
def test_addExt():
    """Test the addExt function. """

    default = fslimage.defaultExt()

    toCreate = [
        'compressed.nii.gz', 'uncompressed.nii', 'img_hdr_pair.img',
        'compressed_img_hdr_pair.img.gz', 'ambiguous.nii', 'ambiguous.nii.gz',
        'ambiguous.img', 'ambiguous.img.gz'
    ]

    # (file, mustExist, expected)
    tests = [('blah', False, 'blah{}'.format(default)),
             ('blah.nii', False, 'blah.nii'),
             ('blah.nii.gz', False, 'blah.nii.gz'),
             ('blah.img', False, 'blah.img'), ('blah.hdr', False, 'blah.hdr'),
             ('blah.img.gz', False, 'blah.img.gz'),
             ('blah.hdr.gz', False, 'blah.hdr.gz'),
             ('compressed', True, 'compressed.nii.gz'),
             ('compressed.nii.gz', True, 'compressed.nii.gz'),
             ('uncompressed', True, 'uncompressed.nii'),
             ('uncompressed.nii', True, 'uncompressed.nii'),
             ('img_hdr_pair', True, 'img_hdr_pair.hdr'),
             ('img_hdr_pair.hdr', True, 'img_hdr_pair.hdr'),
             ('img_hdr_pair.img', True, 'img_hdr_pair.img'),
             ('compressed_img_hdr_pair', True,
              'compressed_img_hdr_pair.hdr.gz'),
             ('compressed_img_hdr_pair.img.gz', True,
              'compressed_img_hdr_pair.img.gz'),
             ('compressed_img_hdr_pair.hdr.gz', True,
              'compressed_img_hdr_pair.hdr.gz'),
             ('ambiguous.nii', True, 'ambiguous.nii'),
             ('ambiguous.nii.gz', True, 'ambiguous.nii.gz'),
             ('ambiguous.img', True, 'ambiguous.img'),
             ('ambiguous.hdr', True, 'ambiguous.hdr'),
             ('ambiguous.img.gz', True, 'ambiguous.img.gz'),
             ('ambiguous.hdr.gz', True, 'ambiguous.hdr.gz')]

    with tempdir() as testdir:

        for path in toCreate:
            path = op.abspath(op.join(testdir, path))
            make_random_image(path)

        for path, mustExist, expected in tests:

            path = op.abspath(op.join(testdir, path))
            expected = op.abspath(op.join(testdir, expected))

            assert fslimage.addExt(path, mustExist) == expected

        # Make sure that an ambiguous path fails
        with pytest.raises(fslimage.PathError):
            path = op.join(testdir, 'ambiguous')
            fslimage.addExt(path, mustExist=True)
Пример #22
0
def test_io():
    directory = op.split(__file__)[0]
    tree = filetree.FileTree.read(op.join(directory, 'parent.tree'), partial_fill=True)
    with tempdir():
        tree.save_pickle('test.pck')
        new_tree = filetree.FileTree.load_pickle('test.pck')
        same_tree(tree, new_tree)

        tree.save_json('test.json')
        new_tree = filetree.FileTree.load_json('test.json')
        same_tree(tree, new_tree)
Пример #23
0
def test_VoxelwiseEVs():
    with tempdir():
        img = tests.make_random_image('image.nii.gz', (10, 10, 10, 10))

        ev1 = featdesign.VoxelwiseEV(0, 0, 'ev1', 'image.nii.gz')
        ev2 = featdesign.VoxelwiseConfoundEV(0, 0, 'ev2', 'image.nii.gz')

        for xyz in tests.random_voxels((10, 10, 10), 10):
            x, y, z = map(int, xyz)
            exp = img.dataobj[x, y, z, :]
            assert np.all(ev1.image[x, y, z, :] == exp)
            assert np.all(ev2.image[x, y, z, :] == exp)
Пример #24
0
def test_loadMeta_badJSON():
    with tempdir():
        make_image('image.nii.gz')

        # spurious comma after b:2
        with open('image.json', 'wt') as f:
            f.write('{"a" : 1, "b" : 2,}')

        # bad json should not cause failure
        img = fslimage.Image('image.nii.gz', loadMeta=True)

        assert list(img.metaKeys()) == []
Пример #25
0
def test_loadMeta():
    with tempdir():
        make_image('image.nii.gz')

        meta = {'a': 1, 'b': 2}
        with open('image.json', 'wt') as f:
            json.dump(meta, f)

        img = fslimage.Image('image.nii.gz', loadMeta=True)

        assert img.getMeta('a') == 1
        assert img.getMeta('b') == 2
Пример #26
0
def test_run_tee():
    test_script = textwrap.dedent("""
    #!/bin/bash

    echo "standard output - arguments: $@"
    echo "standard error" >&2
    exit 0
    """).strip()

    with tempdir.tempdir():
        mkexec('script.sh', test_script)

        expstdout = "standard output - arguments: 1 2 3\n"
        expstderr = "standard error\n"

        capture = CaptureStdout()

        with capture:
            stdout = run.run('./script.sh 1 2 3', log={'tee': True})

        assert stdout == expstdout
        assert capture.stdout == expstdout

        with capture.reset():
            stdout, stderr = run.run('./script.sh 1 2 3',
                                     stderr=True,
                                     log={'tee': True})

        assert stdout == expstdout
        assert stderr == expstderr
        assert capture.stdout == expstdout
        assert capture.stderr == expstderr

        with capture.reset():
            stdout, stderr, ret = run.run('./script.sh 1 2 3',
                                          stderr=True,
                                          exitcode=True,
                                          log={'tee': True})

        assert ret == 0
        assert stdout == expstdout
        assert stderr == expstderr
        assert capture.stdout == expstdout
        assert capture.stderr == expstderr

        with capture.reset():
            stdout, ret = run.run('./script.sh 1 2 3',
                                  exitcode=True,
                                  log={'tee': True})

        assert ret == 0
        assert stdout == expstdout
        assert capture.stdout == expstdout
Пример #27
0
def test_resample_image_ref():
    with tempdir():
        img = Image(make_random_image('image.nii.gz', dims=(10, 10, 10)))
        ref = Image(
            make_random_image('ref.nii.gz',
                              dims=(20, 20, 20),
                              pixdims=(0.5, 0.5, 0.5)))

        resample_image.main('image resampled -r ref'.split())

        res = Image('resampled')
        expv2w = ref.voxToWorldMat

        assert np.all(np.isclose(res.shape, (20, 20, 20)))
        assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5)))
        assert np.all(np.isclose(res.voxToWorldMat, expv2w))

        # 3D / 4D
        img = Image(make_random_image('image.nii.gz', dims=(10, 10, 10)))
        ref = Image(
            make_random_image('ref.nii.gz',
                              dims=(20, 20, 20, 20),
                              pixdims=(0.5, 0.5, 0.5, 1)))

        resample_image.main('image resampled -r ref'.split())
        res = Image('resampled')
        assert np.all(np.isclose(res.shape, (20, 20, 20)))
        assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5)))

        # 4D / 3D
        img = Image(make_random_image('image.nii.gz', dims=(10, 10, 10, 10)))
        ref = Image(
            make_random_image('ref.nii.gz',
                              dims=(20, 20, 20),
                              pixdims=(0.5, 0.5, 0.5)))

        resample_image.main('image resampled -r ref'.split())
        res = Image('resampled')
        assert np.all(np.isclose(res.shape, (20, 20, 20, 10)))
        assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5, 1)))

        # 4D / 4D - no resampling along fourth dim
        img = Image(make_random_image('image.nii.gz', dims=(10, 10, 10, 10)))
        ref = Image(
            make_random_image('ref.nii.gz',
                              dims=(20, 20, 20, 20),
                              pixdims=(0.5, 0.5, 0.5, 1)))

        resample_image.main('image resampled -r ref'.split())
        res = Image('resampled')
        assert np.all(np.isclose(res.shape, (20, 20, 20, 10)))
        assert np.all(np.isclose(res.pixdim, (0.5, 0.5, 0.5, 1)))
Пример #28
0
def test_run_streams():
    """
    """

    test_script = textwrap.dedent("""
    #!/usr/bin/env bash
    echo standard output
    echo standard error >&2
    exit 0
    """).strip()

    expstdout = 'standard output\n'
    expstderr = 'standard error\n'

    with tempdir.tempdir():
        mkexec('./script.sh', test_script)

        with open('my_stdout', 'wt') as stdout, \
             open('my_stderr', 'wt') as stderr:

            stdout, stderr = run.run('./script.sh',
                                     stderr=True,
                                     log={
                                         'stdout': stdout,
                                         'stderr': stderr
                                     })

        assert stdout == expstdout
        assert stderr == expstderr
        assert open('my_stdout', 'rt').read() == expstdout
        assert open('my_stderr', 'rt').read() == expstderr

        capture = CaptureStdout()

        with open('my_stdout', 'wt') as stdout, \
             open('my_stderr', 'wt') as stderr, \
             capture.reset():

            stdout, stderr = run.run('./script.sh',
                                     stderr=True,
                                     log={
                                         'tee': True,
                                         'stdout': stdout,
                                         'stderr': stderr
                                     })

        assert stdout == expstdout
        assert stderr == expstderr
        assert capture.stdout == expstdout
        assert capture.stderr == expstderr
        assert open('my_stdout', 'rt').read() == expstdout
        assert open('my_stderr', 'rt').read() == expstderr
Пример #29
0
def loadSeries(series):
    """Takes a DICOM series meta data dictionary, as returned by
    :func:`scanDir`, and loads the associated data as one or more NIFTI
    images.

    :arg series: Dictionary as returned by :func:`scanDir`, containing
                 meta data about one DICOM data series.

    :returns:    List containing one or more :class:`.DicomImage` objects.
    """

    if not enabled():
        raise RuntimeError('dcm2niix is not available or is too old')

    dcmdir = series['DicomDir']
    snum = series['SeriesNumber']
    desc = series['SeriesDescription']
    version = installedVersion()

    # Newer versions of dcm2niix
    # require a CRC to identify
    # series
    if compareVersions(version, CRC_DCM2NIIX_VERSION) >= 0:
        ident = seriesCRC(series)

    # Older versions require
    # the series number
    else:
        ident = snum

    cmd = 'dcm2niix -b n -f %s -z n -o . -n "{}" "{}"'.format(ident, dcmdir)

    with tempdir.tempdir() as td:

        with open(os.devnull, 'wb') as devnull:
            sp.call(shlex.split(cmd), stdout=devnull, stderr=devnull)

        files = glob.glob(op.join(td, '{}*.nii'.format(snum)))
        images = [nib.load(f, mmap=False) for f in files]

        # copy images so nibabel no longer
        # refs to the files (as they will
        # be deleted), and force-load the
        # the image data into memory (to
        # avoid any disk accesses due to
        # e.g. memmap)
        images = [
            nib.Nifti1Image(np.asanyarray(i.dataobj), None, i.header)
            for i in images
        ]

        return [DicomImage(i, series, dcmdir, name=desc) for i in images]
Пример #30
0
def test_compressed_voxelwise_ev():

    testcases = [((1, 1, 10, 10), (0, 0, 5)), ((1, 10, 1, 10), (0, 5, 0)),
                 ((10, 1, 1, 10), (5, 0, 0))]

    with tempdir():

        for shape, vox in testcases:
            img = tests.make_random_image('vev.nii.gz', shape)
            vev = featdesign.VoxelwiseEV(0, 0, 'ev1', 'vev.nii.gz')
            x, y, z = vox

            assert np.all(vev.getData(5, 5, 5) == img.dataobj[x, y, z, :])