Exemplo n.º 1
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    view = get_view(brain)

    brain.add_label("BA1")
    check_view(brain, view)
    brain.add_label("BA1", color="blue", scalar_thresh=.5)
    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, subject_id,
                       "label", "%s.MT.label" % hemi)
    brain.add_label(label_file)
    brain.add_label("BA44", borders=True)
    brain.add_label("BA6", alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1", color="steelblue", alpha=.6)
    brain.add_label("V2", color="#FF6347", alpha=.6)
    brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')
    brain.show_view(dict(elevation=40, distance=430), distance=430)
    with pytest.raises(ValueError, match='!='):
        brain.show_view(dict(elevation=40, distance=430), distance=431)

    # remove labels
    brain.remove_labels('V1')
    assert 'V2' in brain.labels_dict
    assert 'V1' not in brain.labels_dict
    brain.remove_labels()
    assert 'V2' not in brain.labels_dict

    brain.close()
Exemplo n.º 2
0
    def __init__(self,
                 subject_id,
                 hemi,
                 surf,
                 subjects_dir=None,
                 offset=None,
                 units='mm'):
        from surfer.utils import _check_units, _get_subjects_dir

        hemis = ('lh', 'rh')

        if hemi not in hemis:
            raise ValueError('hemi should be either "lh" or "rh",' +
                             'given value {0}'.format(hemi))

        if offset is not None and ((not isinstance(offset, float)) and
                                   (not isinstance(offset, int))):
            raise ValueError('offset should either float or int, given ' +
                             'type {0}'.format(type(offset).__name__))

        self.subject_id = subject_id
        self.hemi = hemi
        self.surf = surf
        self.offset = offset
        self.units = _check_units(units)
        self.bin_curv = None
        self.coords = None
        self.curv = None
        self.faces = None
        self.grey_curv = None
        self.nn = None
        self.labels = dict()

        subjects_dir = _get_subjects_dir(subjects_dir)
        self.data_path = path.join(subjects_dir, subject_id)
Exemplo n.º 3
0
def test_surface():
    """Test IO for Surface class"""
    subj_dir = utils._get_subjects_dir()
    for subjects_dir in [None, subj_dir]:
        surface = utils.Surface('fsaverage', 'lh', 'inflated',
                                subjects_dir=subjects_dir)
        surface.load_geometry()
        surface.load_label('BA1')
        surface.load_curvature()
        xfm = np.eye(4)
        xfm[:3, -1] += 2  # translation
        x = surface.x
        surface.apply_xfm(xfm)
        x_ = surface.x
        assert_array_almost_equal(x + 2, x_)

        # normals
        nn = _slow_compute_normals(surface.coords, surface.faces[:10000])
        nn_fast = utils._compute_normals(surface.coords, surface.faces[:10000])
        assert_array_almost_equal(nn, nn_fast)
        assert 50 < np.linalg.norm(surface.coords, axis=-1).mean() < 100  # mm
    surface = utils.Surface('fsaverage', 'lh', 'inflated',
                            subjects_dir=subj_dir, units='m')
    surface.load_geometry()
    assert 0.05 < np.linalg.norm(surface.coords, axis=-1).mean() < 0.1  # m
Exemplo n.º 4
0
def test_surface():
    """Test IO for Surface class"""
    subj_dir = utils._get_subjects_dir()
    for subjects_dir in [None, subj_dir]:
        surface = utils.Surface('fsaverage',
                                'lh',
                                'inflated',
                                subjects_dir=subjects_dir)
        surface.load_geometry()
        surface.load_label('BA1')
        surface.load_curvature()
        xfm = np.eye(4)
        xfm[:3, -1] += 2  # translation
        x = surface.x
        surface.apply_xfm(xfm)
        x_ = surface.x
        assert_array_almost_equal(x + 2, x_)

        # normals
        nn = _slow_compute_normals(surface.coords, surface.faces[:10000])
        nn_fast = utils._compute_normals(surface.coords, surface.faces[:10000])
        assert_array_almost_equal(nn, nn_fast)
        assert 50 < np.linalg.norm(surface.coords, axis=-1).mean() < 100  # mm
    surface = utils.Surface('fsaverage',
                            'lh',
                            'inflated',
                            subjects_dir=subj_dir,
                            units='m')
    surface.load_geometry()
    assert 0.05 < np.linalg.norm(surface.coords, axis=-1).mean() < 0.1  # m
Exemplo n.º 5
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    brain.add_label("BA1")
    brain.add_label("BA1", color="blue", scalar_thresh=.5)
    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi)
    brain.add_label(label_file)
    brain.add_label("BA44", borders=True)
    brain.add_label("BA6", alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1", color="steelblue", alpha=.6)
    brain.add_label("V2", color="#FF6347", alpha=.6)
    brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')

    # remove labels
    brain.remove_labels('V1')
    assert_in('V2', brain.labels_dict)
    assert_not_in('V1', brain.labels_dict)
    brain.remove_labels()
    assert_not_in('V2', brain.labels_dict)

    brain.close()
Exemplo n.º 6
0
def test_foci():
    """Test plotting of foci."""
    _set_backend('test')
    brain = Brain(*std_args)
    coords = [[-36, 18, -3], [-43, 25, 24], [-48, 26, -2]]
    brain.add_foci(coords,
                   map_surface="white",
                   color="gold",
                   name='test1',
                   resolution=25)

    subj_dir = utils._get_subjects_dir()
    annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
    ids, ctab, names = nib.freesurfer.read_annot(annot_path)
    verts = np.arange(0, len(ids))
    coords = np.random.permutation(verts[ids == 74])[:10]
    scale_factor = 0.7
    brain.add_foci(coords,
                   coords_as_verts=True,
                   scale_factor=scale_factor,
                   color="#A52A2A",
                   name='test2')
    with pytest.raises(ValueError):
        brain.remove_foci(['test4'])
    brain.remove_foci('test1')
    brain.remove_foci()
    assert len(brain.foci_dict) == 0
    brain.close()
Exemplo n.º 7
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    brain.add_label("BA1")
    brain.add_label("BA1", color="blue", scalar_thresh=.5)
    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, subject_id,
                       "label", "%s.MT.label" % hemi)
    brain.add_label(label_file)
    brain.add_label("BA44", borders=True)
    brain.add_label("BA6", alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1", color="steelblue", alpha=.6)
    brain.add_label("V2", color="#FF6347", alpha=.6)
    brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')

    # remove labels
    brain.remove_labels('V1')
    assert_in('V2', brain.labels_dict)
    assert_not_in('V1', brain.labels_dict)
    brain.remove_labels()
    assert_not_in('V2', brain.labels_dict)

    brain.close()
Exemplo n.º 8
0
def test_annot():
    """Test plotting of annot."""
    _set_backend()
    annots = ['aparc', 'aparc.a2005s']
    borders = [True, False, 2]
    alphas = [1, 0.5]
    brain = Brain(*std_args)
    view = get_view(brain)

    for a, b, p in zip(annots, borders, alphas):
        brain.add_annotation(a, b, p, opacity=0.8)
    check_view(brain, view)

    brain.set_surf('white')
    with pytest.raises(ValueError):
        brain.add_annotation('aparc', borders=-1)

    subj_dir = utils._get_subjects_dir()
    annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
    labels, ctab, names = nib.freesurfer.read_annot(annot_path)
    brain.add_annotation((labels, ctab))

    brain.add_annotation('aparc', color="red", remove_existing=True)
    surf = brain.annot["surface"]
    ctab = surf.module_manager.scalar_lut_manager.lut.table
    for color in ctab:
        assert color[:3] == (255, 0, 0)

    brain.close()
Exemplo n.º 9
0
def test_annot():
    """Test plotting of annot."""
    _set_backend()
    annots = ['aparc', 'aparc.a2005s']
    borders = [True, False, 2]
    alphas = [1, 0.5]
    brain = Brain(*std_args)
    for a, b, p in zip(annots, borders, alphas):
        brain.add_annotation(a, b, p)
    brain.set_surf('white')
    assert_raises(ValueError, brain.add_annotation, 'aparc', borders=-1)

    subj_dir = utils._get_subjects_dir()
    annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
    labels, ctab, names = nib.freesurfer.read_annot(annot_path)
    brain.add_annotation((labels, ctab))

    brain.close()
Exemplo n.º 10
0
def test_foci():
    """Test plotting of foci."""
    _set_backend('test')
    brain = Brain(*std_args)
    coords = [[-36, 18, -3],
              [-43, 25, 24],
              [-48, 26, -2]]
    brain.add_foci(coords, map_surface="white", color="gold")

    subj_dir = utils._get_subjects_dir()
    annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
    ids, ctab, names = nib.freesurfer.read_annot(annot_path)
    verts = np.arange(0, len(ids))
    coords = np.random.permutation(verts[ids == 74])[:10]
    scale_factor = 0.7
    brain.add_foci(coords, coords_as_verts=True,
                   scale_factor=scale_factor, color="#A52A2A")
    brain.close()
Exemplo n.º 11
0
def test_annot():
    """Test plotting of annot."""
    _set_backend()
    annots = ['aparc', 'aparc.a2005s']
    borders = [True, False, 2]
    alphas = [1, 0.5]
    brain = Brain(*std_args)
    for a, b, p in zip(annots, borders, alphas):
        brain.add_annotation(a, b, p)
    brain.set_surf('white')
    assert_raises(ValueError, brain.add_annotation, 'aparc', borders=-1)

    subj_dir = utils._get_subjects_dir()
    annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
    labels, ctab, names = nib.freesurfer.read_annot(annot_path)
    brain.add_annotation((labels, ctab))

    brain.close()
Exemplo n.º 12
0
def test_brains():
    """Test plotting of Brain with different arguments."""
    # testing backend breaks when passing in a figure, so we use 'auto' here
    # (shouldn't affect usability, but it makes testing more annoying)
    _set_backend('auto')
    with warnings.catch_warnings(record=True):  # traits for mlab.figure()
        mlab.figure(101)
    surfs = ['inflated', 'white', 'white', 'white', 'white', 'white', 'white']
    hemis = ['lh', 'rh', 'both', 'both', 'rh', 'both', 'both']
    titles = [None, 'Hello', 'Good bye!', 'lut test',
              'dict test', 'None test', 'RGB test']
    cortices = ["low_contrast", ("Reds", 0, 1, False), 'hotpink',
                ['yellow', 'blue'], dict(colormap='Greys'),
                None, (0.5, 0.5, 0.5)]
    sizes = [500, (400, 300), (300, 300), (300, 400), 500, 400, 300]
    backgrounds = ["white", "blue", "black", "0.75",
                   (0.2, 0.2, 0.2), "black", "0.75"]
    foregrounds = ["black", "white", "0.75", "red",
                   (0.2, 0.2, 0.2), "blue", "black"]
    with warnings.catch_warnings(record=True):  # traits for mlab.figure()
        figs = [101, mlab.figure(), None, None, mlab.figure(), None, None]
    subj_dir = utils._get_subjects_dir()
    subj_dirs = [None, subj_dir, subj_dir, subj_dir,
                 subj_dir, subj_dir, subj_dir]
    alphas = [1.0, 0.5, 0.25, 0.7, 0.5, 0.25, 0.7]
    for surf, hemi, title, cort, s, bg, fg, fig, sd, alpha \
            in zip(surfs, hemis, titles, cortices, sizes,
                   backgrounds, foregrounds, figs, subj_dirs, alphas):
        brain = Brain(subject_id, hemi, surf, title=title, cortex=cort,
                      alpha=alpha, size=s, background=bg, foreground=fg,
                      figure=fig, subjects_dir=sd)
        with np.errstate(invalid='ignore'):  # encountered in double_scalars
            brain.set_distance()
        brain.close()
    brain = Brain(subject_id, hemi, surf, subjects_dir=sd,
                  interaction='terrain')
    brain.close()
    pytest.raises(ValueError, Brain, subject_id, 'lh', 'inflated',
                  subjects_dir='')
    pytest.raises(ValueError, Brain, subject_id, 'lh', 'inflated',
                  interaction='foo', subjects_dir=sd)
Exemplo n.º 13
0
def test_brains():
    """Test plotting of Brain with different arguments."""
    # testing backend breaks when passing in a figure, so we use 'auto' here
    # (shouldn't affect usability, but it makes testing more annoying)
    _set_backend('auto')
    with warnings.catch_warnings(record=True):  # traits for mlab.figure()
        mlab.figure(101)
    surfs = ['inflated', 'white', 'white', 'white', 'white', 'white', 'white']
    hemis = ['lh', 'rh', 'both', 'both', 'rh', 'both', 'both']
    titles = [None, 'Hello', 'Good bye!', 'lut test',
              'dict test', 'None test', 'RGB test']
    cortices = ["low_contrast", ("Reds", 0, 1, False), 'hotpink',
                ['yellow', 'blue'], dict(colormap='Greys'),
                None, (0.5, 0.5, 0.5)]
    sizes = [500, (400, 300), (300, 300), (300, 400), 500, 400, 300]
    backgrounds = ["white", "blue", "black", "0.75",
                   (0.2, 0.2, 0.2), "black", "0.75"]
    foregrounds = ["black", "white", "0.75", "red",
                   (0.2, 0.2, 0.2), "blue", "black"]
    with warnings.catch_warnings(record=True):  # traits for mlab.figure()
        figs = [101, mlab.figure(), None, None, mlab.figure(), None, None]
    subj_dir = utils._get_subjects_dir()
    subj_dirs = [None, subj_dir, subj_dir, subj_dir,
                 subj_dir, subj_dir, subj_dir]
    alphas = [1.0, 0.5, 0.25, 0.7, 0.5, 0.25, 0.7]
    for surf, hemi, title, cort, s, bg, fg, fig, sd, alpha \
            in zip(surfs, hemis, titles, cortices, sizes,
                   backgrounds, foregrounds, figs, subj_dirs, alphas):
        brain = Brain(subject_id, hemi, surf, title=title, cortex=cort,
                      alpha=alpha, size=s, background=bg, foreground=fg,
                      figure=fig, subjects_dir=sd)
        with np.errstate(invalid='ignore'):  # encountered in double_scalars
            brain.set_distance()
        brain.close()
    brain = Brain(subject_id, hemi, surf, subjects_dir=sd,
                  interaction='terrain')
    brain.close()
    pytest.raises(ValueError, Brain, subject_id, 'lh', 'inflated',
                  subjects_dir='')
    pytest.raises(ValueError, Brain, subject_id, 'lh', 'inflated',
                  interaction='foo', subjects_dir=sd)
Exemplo n.º 14
0
def test_probabilistic_labels():
    """Test plotting of probabilistic labels."""
    _set_backend()
    brain = Brain("fsaverage", "lh", "inflated", cortex="low_contrast")

    brain.add_label("BA1", color="darkblue")

    brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5)

    brain.add_label("BA45", color="firebrick", borders=True)
    brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5)

    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label")
    prob_field = np.zeros_like(brain.geo['lh'].x)
    ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True)
    prob_field[ids] = probs
    brain.add_data(prob_field, thresh=1e-5)

    with warnings.catch_warnings(record=True):
        brain.data["colorbar"].number_of_colors = 10
        brain.data["colorbar"].number_of_labels = 11
    brain.close()
Exemplo n.º 15
0
def test_probabilistic_labels():
    """Test plotting of probabilistic labels."""
    _set_backend()
    brain = Brain("fsaverage", "lh", "inflated",
                  cortex="low_contrast")

    brain.add_label("BA1", color="darkblue")

    brain.add_label("BA1", color="dodgerblue", scalar_thresh=.5)

    brain.add_label("BA45", color="firebrick", borders=True)
    brain.add_label("BA45", color="salmon", borders=True, scalar_thresh=.5)

    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, "fsaverage", "label", "lh.BA6.label")
    prob_field = np.zeros_like(brain.geo['lh'].x)
    ids, probs = nib.freesurfer.read_label(label_file, read_scalars=True)
    prob_field[ids] = probs
    brain.add_data(prob_field, thresh=1e-5)

    with warnings.catch_warnings(record=True):
        brain.data["colorbar"].number_of_colors = 10
        brain.data["colorbar"].number_of_labels = 11
    brain.close()
Exemplo n.º 16
0
import numpy as np
import os
import os.path as op
from os.path import join as pjoin
from numpy.testing import assert_raises, assert_array_equal
from tempfile import mktemp
import nibabel as nib

from surfer import Brain, io, utils
from surfer.utils import requires_fsaverage
from mayavi import mlab

subj_dir = utils._get_subjects_dir()
subject_id = 'fsaverage'
std_args = [subject_id, 'lh', 'inflated']
data_dir = pjoin(op.dirname(__file__), '..', '..', 'examples', 'example_data')
small_brain = dict(size=100)

overlay_fname = pjoin(data_dir, 'lh.sig.nii.gz')


def has_freesurfer():
    if 'FREESURFER_HOME' not in os.environ:
        return False
    else:
        return True


requires_fs = np.testing.dec.skipif(not has_freesurfer(),
                                    'Requires FreeSurfer command line tools')
Exemplo n.º 17
0
from os.path import join as pjoin

import numpy as np
import nose.tools as nt
from numpy.testing import assert_array_almost_equal, assert_array_equal

from surfer import utils

subj_dir = utils._get_subjects_dir()
subject_id = 'fsaverage'
data_path = pjoin(subj_dir, subject_id)


def _slow_compute_normals(rr, tris):
    """Efficiently compute vertex normals for triangulated surface"""
    # first, compute triangle normals
    r1 = rr[tris[:, 0], :]
    r2 = rr[tris[:, 1], :]
    r3 = rr[tris[:, 2], :]
    tri_nn = np.cross((r2 - r1), (r3 - r1))

    #   Triangle normals and areas
    size = np.sqrt(np.sum(tri_nn * tri_nn, axis=1))
    zidx = np.where(size == 0)[0]
    size[zidx] = 1.0  # prevent ugly divide-by-zero
    tri_nn /= size[:, np.newaxis]

    # accumulate the normals
    nn = np.zeros((len(rr), 3))
    for p, verts in enumerate(tris):
        nn[verts] += tri_nn[p, :]