Esempio n. 1
0
def test_brain_init(renderer, tmpdir, pixel_ratio, brain_gc):
    """Test initialization of the Brain instance."""
    if renderer._get_3d_backend() != 'pyvista':
        pytest.skip('TimeViewer tests only supported on PyVista')
    from mne.source_estimate import _BaseSourceEstimate

    class FakeSTC(_BaseSourceEstimate):
        def __init__(self):
            pass

    hemi = 'lh'
    surf = 'inflated'
    cortex = 'low_contrast'
    title = 'test'
    size = (300, 300)

    kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='"size" parameter must be'):
        Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs)
    with pytest.raises(KeyError):
        Brain(hemi='foo', surf=surf, **kwargs)
    with pytest.raises(TypeError, match='figure'):
        Brain(hemi=hemi, surf=surf, figure='foo', **kwargs)
    with pytest.raises(TypeError, match='interaction'):
        Brain(hemi=hemi, surf=surf, interaction=0, **kwargs)
    with pytest.raises(ValueError, match='interaction'):
        Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs)
    renderer.backend._close_all()

    brain = Brain(hemi=hemi,
                  surf=surf,
                  size=size,
                  title=title,
                  cortex=cortex,
                  units='m',
                  silhouette=dict(decimate=0.95),
                  **kwargs)
    with pytest.raises(TypeError, match='not supported'):
        brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None)
    with pytest.raises(ValueError, match='add_data'):
        brain.setup_time_viewer(time_viewer=True)
    brain._hemi = 'foo'  # for testing: hemis
    with pytest.raises(ValueError, match='not be None'):
        brain._check_hemi(hemi=None)
    with pytest.raises(ValueError, match='either "lh" or "rh"'):
        brain._check_hemi(hemi='foo')
    with pytest.raises(ValueError, match='either "lh" or "rh"'):
        brain._check_hemis(hemi='foo')
    brain._hemi = hemi  # end testing: hemis
    with pytest.raises(ValueError, match='bool or positive'):
        brain._to_borders(None, None, 'foo')
    assert brain.interaction == 'trackball'
    # add_data
    stc = read_source_estimate(fname_stc)
    fmin = stc.data.min()
    fmax = stc.data.max()
    for h in brain._hemis:
        if h == 'lh':
            hi = 0
        else:
            hi = 1
        hemi_data = stc.data[:len(stc.vertices[hi]), 10]
        hemi_vertices = stc.vertices[hi]

        with pytest.raises(TypeError, match='scale_factor'):
            brain.add_data(hemi_data, hemi=h, scale_factor='foo')
        with pytest.raises(TypeError, match='vector_alpha'):
            brain.add_data(hemi_data, hemi=h, vector_alpha='foo')
        with pytest.raises(ValueError, match='thresh'):
            brain.add_data(hemi_data, hemi=h, thresh=-1)
        with pytest.raises(ValueError, match='remove_existing'):
            brain.add_data(hemi_data, hemi=h, remove_existing=-1)
        with pytest.raises(ValueError, match='time_label_size'):
            brain.add_data(hemi_data,
                           hemi=h,
                           time_label_size=-1,
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='is positive'):
            brain.add_data(hemi_data,
                           hemi=h,
                           smoothing_steps=-1,
                           vertices=hemi_vertices)
        with pytest.raises(TypeError, match='int or NoneType'):
            brain.add_data(hemi_data, hemi=h, smoothing_steps='foo')
        with pytest.raises(ValueError, match='dimension mismatch'):
            brain.add_data(array=np.array([0, 1, 2]),
                           hemi=h,
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='vertices parameter must not be'):
            brain.add_data(hemi_data,
                           fmin=fmin,
                           hemi=hemi,
                           fmax=fmax,
                           vertices=None)
        with pytest.raises(ValueError, match='has shape'):
            brain.add_data(hemi_data[:, np.newaxis],
                           fmin=fmin,
                           hemi=hemi,
                           fmax=fmax,
                           vertices=None,
                           time=[0, 1])

        brain.add_data(hemi_data,
                       fmin=fmin,
                       hemi=h,
                       fmax=fmax,
                       colormap='hot',
                       vertices=hemi_vertices,
                       smoothing_steps='nearest',
                       colorbar=(0, 0),
                       time=None)
        with pytest.raises(ValueError, match='brain has no defined times'):
            brain.set_time(0.)
        assert brain.data['lh']['array'] is hemi_data
        assert brain.views == ['lateral']
        assert brain.hemis == ('lh', )
        brain.add_data(hemi_data[:, np.newaxis],
                       fmin=fmin,
                       hemi=h,
                       fmax=fmax,
                       colormap='hot',
                       vertices=hemi_vertices,
                       smoothing_steps=1,
                       initial_time=0.,
                       colorbar=False,
                       time=[0])
        with pytest.raises(ValueError, match='the range of available times'):
            brain.set_time(7.)
        brain.set_time(0.)
        brain.set_time_point(0)  # should hit _safe_interp1d

        with pytest.raises(ValueError, match='consistent with'):
            brain.add_data(hemi_data[:, np.newaxis],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices,
                           smoothing_steps='nearest',
                           colorbar=False,
                           time=[1])
        with pytest.raises(ValueError, match='different from'):
            brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='need shape'):
            brain.add_data(hemi_data[:, np.newaxis],
                           time=[0, 1],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='If array has 3'):
            brain.add_data(hemi_data[:, np.newaxis, np.newaxis],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices)
    # add label
    label = read_label(fname_label)
    with pytest.raises(ValueError, match="not a filename"):
        brain.add_label(0)
    with pytest.raises(ValueError, match="does not exist"):
        brain.add_label('foo', subdir='bar')
    label.name = None  # test unnamed label
    brain.add_label(label, scalar_thresh=0., color="green")
    assert isinstance(brain.labels[label.hemi], list)
    overlays = brain._layered_meshes[label.hemi]._overlays
    assert 'unnamed0' in overlays
    assert np.allclose(overlays['unnamed0']._colormap[0],
                       [0, 0, 0, 0])  # first component is transparent
    assert np.allclose(overlays['unnamed0']._colormap[1],
                       [0, 128, 0, 255])  # second is green
    brain.remove_labels()
    assert 'unnamed0' not in overlays
    brain.add_label(fname_label)
    brain.add_label('V1', borders=True)
    brain.remove_labels()
    brain.remove_labels()

    # add foci
    brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue')

    # add text
    brain.add_text(x=0, y=0, text='foo')
    brain.close()

    # add annotation
    annots = [
        'aparc',
        path.join(subjects_dir, 'fsaverage', 'label',
                  'lh.PALS_B12_Lobes.annot')
    ]
    borders = [True, 2]
    alphas = [1, 0.5]
    colors = [None, 'r']
    brain = Brain(subject_id='fsaverage',
                  hemi='both',
                  size=size,
                  surf='inflated',
                  subjects_dir=subjects_dir)
    with pytest.raises(RuntimeError, match="both hemispheres"):
        brain.add_annotation(annots[-1])
    with pytest.raises(ValueError, match="does not exist"):
        brain.add_annotation('foo')
    brain.close()
    brain = Brain(subject_id='fsaverage',
                  hemi=hemi,
                  size=size,
                  surf='inflated',
                  subjects_dir=subjects_dir)
    for a, b, p, color in zip(annots, borders, alphas, colors):
        brain.add_annotation(a, b, p, color=color)

    brain.show_view(dict(focalpoint=(1e-5, 1e-5, 1e-5)), roll=1, distance=500)

    # image and screenshot
    fname = path.join(str(tmpdir), 'test.png')
    assert not path.isfile(fname)
    brain.save_image(fname)
    assert path.isfile(fname)
    brain.show_view(view=dict(azimuth=180., elevation=90.))
    img = brain.screenshot(mode='rgb')
    if renderer._get_3d_backend() == 'mayavi':
        pixel_ratio = 1.  # no HiDPI when using the testing backend
    want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 3])
    assert_allclose(img.shape, want_size)
    brain.close()
Esempio n. 2
0
def test_brain_init(renderer_pyvistaqt, tmpdir, pixel_ratio, brain_gc):
    """Test initialization of the Brain instance."""
    from mne.source_estimate import _BaseSourceEstimate

    class FakeSTC(_BaseSourceEstimate):
        def __init__(self):
            pass

    hemi = 'lh'
    surf = 'inflated'
    cortex = 'low_contrast'
    title = 'test'
    size = (300, 300)

    kwargs = dict(subject_id=subject_id, subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='"size" parameter must be'):
        Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs)
    with pytest.raises(ValueError, match='.*hemi.*Allowed values.*'):
        Brain(hemi='foo', surf=surf, **kwargs)
    with pytest.raises(ValueError, match='.*view.*Allowed values.*'):
        Brain(hemi='lh', surf=surf, views='foo', **kwargs)
    with pytest.raises(TypeError, match='figure'):
        Brain(hemi=hemi, surf=surf, figure='foo', **kwargs)
    with pytest.raises(TypeError, match='interaction'):
        Brain(hemi=hemi, surf=surf, interaction=0, **kwargs)
    with pytest.raises(ValueError, match='interaction'):
        Brain(hemi=hemi, surf=surf, interaction='foo', **kwargs)
    with pytest.raises(FileNotFoundError, match=r'lh\.whatever'):
        Brain(subject_id, 'lh', 'whatever')
    with pytest.raises(ValueError, match='`surf` cannot be seghead'):
        Brain(hemi='lh', surf='seghead', **kwargs)
    Brain(subject_id, hemi=None, surf=None)  # test no surfaces
    renderer_pyvistaqt.backend._close_all()

    brain = Brain(hemi=hemi,
                  surf=surf,
                  size=size,
                  title=title,
                  cortex=cortex,
                  units='m',
                  silhouette=dict(decimate=0.95),
                  **kwargs)
    with pytest.raises(TypeError, match='not supported'):
        brain._check_stc(hemi='lh', array=FakeSTC(), vertices=None)
    with pytest.raises(ValueError, match='add_data'):
        brain.setup_time_viewer(time_viewer=True)
    brain._hemi = 'foo'  # for testing: hemis
    with pytest.raises(ValueError, match='not be None'):
        brain._check_hemi(hemi=None)
    with pytest.raises(ValueError, match='Invalid.*hemi.*Allowed'):
        brain._check_hemi(hemi='foo')
    brain._hemi = hemi  # end testing: hemis
    with pytest.raises(ValueError, match='bool or positive'):
        brain._to_borders(None, None, 'foo')
    assert brain.interaction == 'trackball'
    # add_data
    stc = read_source_estimate(fname_stc)
    fmin = stc.data.min()
    fmax = stc.data.max()
    for h in brain._hemis:
        if h == 'lh':
            hi = 0
        else:
            hi = 1
        hemi_data = stc.data[:len(stc.vertices[hi]), 10]
        hemi_vertices = stc.vertices[hi]

        with pytest.raises(TypeError, match='scale_factor'):
            brain.add_data(hemi_data, hemi=h, scale_factor='foo')
        with pytest.raises(TypeError, match='vector_alpha'):
            brain.add_data(hemi_data, hemi=h, vector_alpha='foo')
        with pytest.raises(ValueError, match='thresh'):
            brain.add_data(hemi_data, hemi=h, thresh=-1)
        with pytest.raises(ValueError, match='remove_existing'):
            brain.add_data(hemi_data, hemi=h, remove_existing=-1)
        with pytest.raises(ValueError, match='time_label_size'):
            brain.add_data(hemi_data,
                           hemi=h,
                           time_label_size=-1,
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='is positive'):
            brain.add_data(hemi_data,
                           hemi=h,
                           smoothing_steps=-1,
                           vertices=hemi_vertices)
        with pytest.raises(TypeError, match='int or NoneType'):
            brain.add_data(hemi_data, hemi=h, smoothing_steps='foo')
        with pytest.raises(ValueError, match='dimension mismatch'):
            brain.add_data(array=np.array([0, 1, 2]),
                           hemi=h,
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='vertices parameter must not be'):
            brain.add_data(hemi_data,
                           fmin=fmin,
                           hemi=hemi,
                           fmax=fmax,
                           vertices=None)
        with pytest.raises(ValueError, match='has shape'):
            brain.add_data(hemi_data[:, np.newaxis],
                           fmin=fmin,
                           hemi=hemi,
                           fmax=fmax,
                           vertices=None,
                           time=[0, 1])

        brain.add_data(hemi_data,
                       fmin=fmin,
                       hemi=h,
                       fmax=fmax,
                       colormap='hot',
                       vertices=hemi_vertices,
                       smoothing_steps='nearest',
                       colorbar=(0, 0),
                       time=None)
        with pytest.raises(ValueError, match='brain has no defined times'):
            brain.set_time(0.)
        assert brain.data['lh']['array'] is hemi_data
        assert brain.views == ['lateral']
        assert brain.hemis == ('lh', )
        brain.add_data(hemi_data[:, np.newaxis],
                       fmin=fmin,
                       hemi=h,
                       fmax=fmax,
                       colormap='hot',
                       vertices=hemi_vertices,
                       smoothing_steps=1,
                       initial_time=0.,
                       colorbar=False,
                       time=[0])
        with pytest.raises(ValueError, match='the range of available times'):
            brain.set_time(7.)
        brain.set_time(0.)
        brain.set_time_point(0)  # should hit _safe_interp1d

        with pytest.raises(ValueError, match='consistent with'):
            brain.add_data(hemi_data[:, np.newaxis],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices,
                           smoothing_steps='nearest',
                           colorbar=False,
                           time=[1])
        with pytest.raises(ValueError, match='different from'):
            brain.add_data(hemi_data[:, np.newaxis][:, [0, 0]],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='need shape'):
            brain.add_data(hemi_data[:, np.newaxis],
                           time=[0, 1],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices)
        with pytest.raises(ValueError, match='If array has 3'):
            brain.add_data(hemi_data[:, np.newaxis, np.newaxis],
                           fmin=fmin,
                           hemi=h,
                           fmax=fmax,
                           colormap='hot',
                           vertices=hemi_vertices)
    # add label
    label = read_label(fname_label)
    with pytest.raises(ValueError, match="not a filename"):
        brain.add_label(0)
    with pytest.raises(ValueError, match="does not exist"):
        brain.add_label('foo', subdir='bar')
    label.name = None  # test unnamed label
    brain.add_label(label, scalar_thresh=0., color="green")
    assert isinstance(brain.labels[label.hemi], list)
    overlays = brain._layered_meshes[label.hemi]._overlays
    assert 'unnamed0' in overlays
    assert np.allclose(overlays['unnamed0']._colormap[0],
                       [0, 0, 0, 0])  # first component is transparent
    assert np.allclose(overlays['unnamed0']._colormap[1],
                       [0, 128, 0, 255])  # second is green
    brain.remove_labels()
    assert 'unnamed0' not in overlays
    brain.add_label(fname_label)
    brain.add_label('V1', borders=True)
    brain.remove_labels()
    brain.remove_labels()

    # add foci
    brain.add_foci([0], coords_as_verts=True, hemi=hemi, color='blue')

    # add head and skull
    brain.add_head(color='red', alpha=0.1)
    brain.add_skull(outer=True, color='green', alpha=0.1)

    # add volume labels
    brain.add_volume_labels(aseg='aseg',
                            labels=('Brain-Stem', 'Left-Hippocampus',
                                    'Left-Amygdala'))
    # add sensors
    info = read_info(fname_raw_testing)
    brain.add_sensors(info, trans=fname_trans)

    info['chs'][0]['coord_frame'] = 99
    with pytest.raises(RuntimeError, match='must be "meg", "head" or "mri"'):
        brain.add_sensors(info, trans=fname_trans)

    # add text
    brain.add_text(x=0, y=0, text='foo')
    brain.close()

    # add annotation
    annots = [
        'aparc',
        op.join(subjects_dir, 'fsaverage', 'label', 'lh.PALS_B12_Lobes.annot')
    ]
    borders = [True, 2]
    alphas = [1, 0.5]
    colors = [None, 'r']
    brain = Brain(subject_id='fsaverage',
                  hemi='both',
                  size=size,
                  surf='inflated',
                  subjects_dir=subjects_dir)
    with pytest.raises(RuntimeError, match="both hemispheres"):
        brain.add_annotation(annots[-1])
    with pytest.raises(ValueError, match="does not exist"):
        brain.add_annotation('foo')
    brain.close()
    brain = Brain(subject_id='fsaverage',
                  hemi=hemi,
                  size=size,
                  surf='inflated',
                  subjects_dir=subjects_dir)
    for a, b, p, color in zip(annots, borders, alphas, colors):
        brain.add_annotation(a, b, p, color=color)

    view_args = dict(roll=1, distance=500, focalpoint=(1e-5, 1e-5, 1e-5))
    cam = brain._renderer.figure.plotter.camera
    previous_roll = cam.GetRoll()
    brain.show_view(**view_args)
    assert_allclose(cam.GetFocalPoint(), view_args["focalpoint"])
    assert_allclose(cam.GetDistance(), view_args["distance"])
    assert_allclose(cam.GetRoll(), previous_roll + view_args["roll"])
    del view_args

    with pytest.warns(DeprecationWarning, match='`view` is a dict'):
        brain.show_view(view=dict(azimuth=180., elevation=90.))

    # image and screenshot
    fname = op.join(str(tmpdir), 'test.png')
    assert not op.isfile(fname)
    brain.save_image(fname)
    assert op.isfile(fname)
    fp = np.array(
        brain._renderer.figure.plotter.renderer.ComputeVisiblePropBounds())
    fp = (fp[1::2] + fp[::2]) * 0.5
    azimuth, elevation = 180., 90.
    for view_args in (dict(azimuth=azimuth,
                           elevation=elevation,
                           focalpoint='auto'), dict(view='lateral',
                                                    hemi='lh')):
        brain.show_view(**view_args)
        assert_allclose(brain._renderer.figure._azimuth, azimuth)
        assert_allclose(brain._renderer.figure._elevation, elevation)
        assert_allclose(cam.GetFocalPoint(), fp)
    del view_args
    img = brain.screenshot(mode='rgba')
    want_size = np.array([size[0] * pixel_ratio, size[1] * pixel_ratio, 4])
    assert_allclose(img.shape, want_size)
    brain.close()