示例#1
0
def _test_query(tests):

    fslatlases.rescanAtlases()
    capture = CaptureStdout()
    print()

    for atlas, use_label, q_type, q_in, res, o_type in tests:

        with tempdir() as td:

            if q_type in ('voxel', 'coordinate'):
                genfunc = _gen_coord_voxel_query
                evalfunc = _eval_coord_voxel_query
            else:
                genfunc = _gen_mask_query
                evalfunc = _eval_mask_query

            print('Test: {} {}mm label={} type={} in={} type={}'.format(
                atlas, res, use_label, q_type, q_in, o_type))

            query = genfunc(atlas, use_label, q_type, q_in, res)
            cmd = _build_command_line(atlas, query, use_label, q_type, res,
                                      o_type)

            print('fslatlasq {}'.format(' '.join(cmd)))

            capture.reset()
            with capture:
                fslatlasq.main(cmd)

            evalfunc(capture.stdout, atlas, query, use_label, q_type, q_in,
                     res, o_type)
示例#2
0
def test_summary():

    fslatlases.rescanAtlases()

    adescs  = fslatlases.listAtlases()
    capture = CaptureStdout()

    for desc in adescs:

        tests = [desc.atlasID, desc.name]

        for test in tests:

            capture.reset()

            with capture:
                fslatlasq.main(['summary', test])

            stdout = capture.stdout

            assert desc.atlasID   in stdout
            assert desc.name      in stdout
            assert desc.specPath  in stdout
            assert desc.atlasType in stdout

            for image in it.chain(desc.images, desc.summaryImages):
                assert image in stdout

            for label in desc.labels:
                assert label.name in stdout
示例#3
0
def test_list():

    fslatlases.rescanAtlases()

    adescs  = fslatlases.listAtlases()
    capture = CaptureStdout()

    tests     = ['list', 'list --extended']
    extendeds = [False, True]

    for test, extended in zip(tests, extendeds):
        capture.reset()

        with capture:
            fslatlasq.main(test.split())

        stdout = capture.stdout

        for desc in adescs:
            assert desc.atlasID in stdout
            assert desc.name    in stdout

            assert (desc.specPath in stdout) == extended

            for image in it.chain(desc.images, desc.summaryImages):
                assert (image in stdout) == extended
                assert (image in stdout) == extended
示例#4
0
def test_dumpatlases():
    """Test the ohi --dumpatlases option. """

    capture = CaptureStdout()

    with capture:
        fslatlasq.main('ohi --dumpatlases'.split())

    atlases = fslatlases.listAtlases()
    atlases = [a.name for a in atlases]
    atlases = sorted(atlases)

    assert capture.stdout.strip() == '\n'.join(atlases)
示例#5
0
def test_bad_atlas():
    """Test the ohi -a "atlas" ..., with a non-existent atlas. """

    capture = CaptureStdout()

    atlases = fslatlases.listAtlases()
    atlases = sorted([a.name for a in atlases])

    expected = ['Invalid atlas name. Try one of:'] + atlases
    expected = '\n'.join(expected)

    cmds = ['ohi -a "non-existent atlas" -c "0,0,0"',
            'ohi -a "non-existent atlas" -m "nomask"']

    for cmd in cmds:
        capture.reset()
        with capture:
            fslatlasq.main(shlex.split(cmd))
            assert capture.stdout.strip() == expected
示例#6
0
def test_bad_mask(seed):

    fslatlases.rescanAtlases()
    capture = CaptureStdout()

    with tempdir() as td:

        for atlasID, use_label in it.product(atlases, use_labels):

            atlas = fslatlases.loadAtlas(atlasID,
                                         loadSummary=use_label,
                                         indexed=True,
                                         loadData=False,
                                         calcRange=False)
            ashape = list(atlas.shape[:3])

            wrongdims = fslimage.Image(
                np.array(np.random.random(list(ashape) + [2]),
                         dtype=np.float32))
            wrongspace = fslimage.Image(np.random.random((20, 20, 20)),
                                        xform=transform.concat(
                                            atlas.voxToWorldMat,
                                            np.diag([2, 2, 2, 1])))

            print(wrongdims.shape)
            print(wrongspace.shape)

            wrongdims.save('wrongdims.nii.gz')
            wrongspace.save('wrongspace.nii.gz')

            cmd = ['query', atlasID, '-m', 'wrongdims']
            expected = 'Mask has wrong number of dimensions'
            capture.reset()
            with capture:
                assert fslatlasq.main(cmd) != 0
            assert capture.stdout.strip() == expected

            cmd = ['query', atlasID, '-m', 'wrongspace']
            expected = 'Mask is not in the same space as atlas'
            capture.reset()
            with capture:
                assert fslatlasq.main(cmd) != 0
            assert capture.stdout.strip() == expected
示例#7
0
def test_coords(seed):
    """Test the ohi -a "atlas" -c "coords" mode. """
    def expectedProbOutput(atlas, coords):
        probs = atlas.values(coords)
        expected = '<b>{}</b><br>'.format(atlas.desc.name)
        nzprobs = []

        for i, p in enumerate(probs):
            if p > 0:
                label = atlas.desc.labels[i].name
                nzprobs.append((p, label))

        if len(nzprobs) > 0:
            nzprobs = reversed(sorted(nzprobs, key=lambda b: b[0]))
            nzprobs = [
                '{:d}% {}'.format(int(round(p)), l) for (p, l) in nzprobs
            ]
            expected += ', '.join(nzprobs)
        else:
            expected += 'No label found!'

        return expected

    def expectedLabelOutput(atlas, coords):
        label = atlas.label(coords)
        expected = '<b>{}</b><br>'.format(atlas.desc.name)

        if label is None:
            return expected + 'Unclassified'
        else:
            return expected + atlas.desc.find(value=int(label)).name

    capture = CaptureStdout()

    # random coordinates in MNI152 space,
    # with some coordinates out of bounds
    ncoords = 50
    xc = -100 + 190 * np.random.random(ncoords)
    yc = -130 + 220 * np.random.random(ncoords)
    zc = -80 + 120 * np.random.random(ncoords)
    coords = np.vstack((xc, yc, zc)).T

    fslatlases.rescanAtlases()
    atlases = fslatlases.listAtlases()

    for ad in atlases:

        # atlasquery/ohi always uses 2mm resolution
        atlas = fslatlases.loadAtlas(ad.atlasID, resolution=2)

        print(ad.name)

        for x, y, z in coords:

            cmd = 'ohi -a "{}" -c "{},{},{}"'.format(ad.name, x, y, z)

            capture.reset()
            with capture:
                fslatlasq.main(shlex.split(cmd))

            if isinstance(atlas, fslatlases.ProbabilisticAtlas):
                expected = expectedProbOutput(atlas, (x, y, z))

            # LabelAtlas
            else:
                expected = expectedLabelOutput(atlas, (x, y, z))

            assert capture.stdout.strip() == expected.strip()
示例#8
0
def test_mask(seed):
    """Test the ohi -a "atlas" -m "mask" mode, with label and probabilistic
    atlases.
    """
    def expectedLabelOutput(mask, atlas):

        labels, props = atlas.maskLabel(mask)
        exp = []

        for lbl, prop in zip(labels, props):
            name = desc.find(value=int(lbl)).name
            exp.append('{}:{:0.4f}'.format(name, prop))

        return '\n'.join(exp)

    def expectedProbOutput(mask, atlas):

        props = atlas.maskValues(mask)
        labels = [l.index for l in atlas.desc.labels]
        exp = []

        for lbl, prop in zip(labels, props):
            if prop > 0:
                exp.append('{}:{:0.4f}'.format(desc.labels[int(lbl)].name,
                                               prop))

        return '\n'.join(exp)

    fslatlases.rescanAtlases()

    capture = CaptureStdout()
    atlases = fslatlases.listAtlases()

    with tempdir() as td:

        maskfile = op.join(td, 'mask.nii')

        for desc in atlases:

            # atlasquery always uses 2mm
            # resolution versions of atlases
            atlas2mm = fslatlases.loadAtlas(desc.atlasID, resolution=2)

            # Test with 1mm and 2mm masks
            for res in [1, 2]:
                atlasimg = fslatlases.loadAtlas(desc.atlasID, resolution=res)
                maskimg = make_random_mask(maskfile, atlasimg.shape[:3],
                                           atlasimg.voxToWorldMat)

                cmd = 'ohi -a "{}" -m {}'.format(desc.name, maskfile)
                print(cmd)

                capture.reset()
                with capture:
                    fslatlasq.main(shlex.split(cmd))

                if isinstance(atlasimg, fslatlases.LabelAtlas):
                    expected = expectedLabelOutput(maskimg, atlas2mm)
                elif isinstance(atlasimg, fslatlases.ProbabilisticAtlas):
                    expected = expectedProbOutput(maskimg, atlas2mm)

                assert capture.stdout.strip() == expected