def test_brain_timeviewer_traces(renderer_interactive, hemi): """Test _TimeViewer traces.""" if renderer_interactive._get_3d_backend() != 'pyvista': pytest.skip() brain_data = _create_testing_brain(hemi=hemi) time_viewer = _TimeViewer(brain_data, show_traces=True) assert hasattr(time_viewer, "picked_points") assert hasattr(time_viewer, "_spheres") # test points picked by default picked_points = brain_data.get_picked_points() spheres = time_viewer._spheres hemi_str = [hemi] if hemi in ('lh', 'rh') else ['lh', 'rh'] for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 assert len(spheres) == len(hemi_str) # test removing points time_viewer.clear_points() assert len(picked_points['lh']) == 0 assert len(picked_points['rh']) == 0 # test picking a cell at random for idx, current_hemi in enumerate(hemi_str): current_mesh = brain_data._hemi_meshes[current_hemi] cell_id = np.random.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(current_mesh, cell_id) assert cell_id == test_picker.cell_id assert test_picker.point_id is None time_viewer.on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id sphere = spheres[idx] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = 'L' if current_hemi == 'lh' else 'R' hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni(vertices=vertex_id, hemis=hemi_int, subject=brain_data._subject_id, subjects_dir=brain_data._subjects_dir) label = "{}:{} MNI: {}".format(hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label assert len(spheres) == len(hemi_str)
def test_brain_traces(renderer_interactive, hemi, src, tmpdir, brain_gc): """Test brain traces.""" if renderer_interactive._get_3d_backend() != 'pyvista': pytest.skip('Only PyVista supports traces') hemi_str = list() if src in ('surface', 'vector', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) # label traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces='label', volume_options=None, # for speed, don't upsample n_time=5, initial_time=0, ) if src == 'surface': brain._data['src'] = None # test src=None if src in ('surface', 'vector', 'mixed'): assert brain.show_traces assert brain.traces_mode == 'label' brain.widgets["extract_mode"].set_value('max') # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): if current_hemi == 'vol': continue current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(current_mesh, cell_id, current_hemi, brain) assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) assert len(brain.picked_patches[current_hemi]) == 1 for label_id in list(brain.picked_patches[current_hemi]): label = brain._annotation_labels[current_hemi][label_id] assert isinstance(label._line, Line2D) brain.widgets["extract_mode"].set_value('mean') brain.clear_glyphs() assert len(brain.picked_patches[current_hemi]) == 0 brain._on_pick(test_picker, None) # picked and added assert len(brain.picked_patches[current_hemi]) == 1 brain._on_pick(test_picker, None) # picked again so removed assert len(brain.picked_patches[current_hemi]) == 0 # test switching from 'label' to 'vertex' brain.widgets["annotation"].set_value('None') brain.widgets["extract_mode"].set_value('max') else: # volume assert "annotation" not in brain.widgets assert "extract_mode" not in brain.widgets brain.close() # test colormap if src != 'vector': brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, diverging=True, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) # mne_analyze should be chosen ctab = brain._data['ctable'] assert_array_equal(ctab[0], [0, 255, 255, 255]) # opaque cyan assert_array_equal(ctab[-1], [255, 255, 0, 255]) # opaque yellow assert_allclose(ctab[len(ctab) // 2], [128, 128, 128, 0], atol=3) brain.close() # vertex traces brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, add_data_kwargs=dict(colorbar_kwargs=dict(n_labels=3)), ) assert brain.show_traces assert brain.traces_mode == 'vertex' assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") assert brain.plotter.scalar_bar.GetNumberOfLabels() == 3 # add foci should work for volumes brain.add_foci([[0, 0, 0]], hemi='lh' if src == 'surface' else 'vol') # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test switching from 'vertex' to 'label' if src == 'surface': brain.widgets["annotation"].set_value('aparc') brain.widgets["annotation"].set_value('None') # test removing points brain.clear_glyphs() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._layered_meshes[current_hemi]._polydata cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker(current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni(vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir) label = "{}:{} MNI: {}".format(hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2]
def test_brain_timeviewer_traces(renderer_interactive, hemi, src, tmpdir): """Test _TimeViewer traces.""" if renderer_interactive._get_3d_backend() != 'pyvista': pytest.skip('Only PyVista supports traces') brain_data = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample ) with pytest.raises(RuntimeError, match='already'): _TimeViewer(brain_data) time_viewer = brain_data.time_viewer assert time_viewer.show_traces assert hasattr(time_viewer, "picked_points") assert hasattr(time_viewer, "_spheres") # test points picked by default picked_points = brain_data.get_picked_points() spheres = time_viewer._spheres hemi_str = list() if src in ('surface', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test removing points time_viewer.clear_points() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain_data._data['vol']['grid'] vertices = brain_data._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain_data._hemi_meshes[current_hemi] cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain_data) assert time_viewer.on_pick(test_picker, None) is None test_picker = TstVTKPicker(current_mesh, cell_id, current_hemi, brain_data) assert cell_id == test_picker.cell_id assert test_picker.point_id is None time_viewer.on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni(vertices=vertex_id, hemis=hemi_int, subject=brain_data._subject_id, subjects_dir=brain_data._subjects_dir) label = "{}:{} MNI: {}".format(hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) time_viewer.on_pick(test_picker, None) assert len(spheres) < old_len # and the scraper for it (will close the instance) if not check_version('sphinx_gallery'): return screenshot = brain_data.screenshot() fnames = [str(tmpdir.join('temp.png'))] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain_data)) gallery_conf = dict(src_dir=str(tmpdir)) scraper = _BrainScraper() rst = scraper(None, block_vars, gallery_conf) assert 'temp.png' in rst assert path.isfile(fnames[0]) img = image.imread(fnames[0]) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height
def test_brain_timeviewer_traces(renderer_interactive, hemi, tmpdir): """Test _TimeViewer traces.""" if renderer_interactive._get_3d_backend() != 'pyvista': pytest.skip('Only PyVista supports traces') brain_data = _create_testing_brain(hemi=hemi) time_viewer = _TimeViewer(brain_data, show_traces=True) assert hasattr(time_viewer, "picked_points") assert hasattr(time_viewer, "_spheres") # test points picked by default picked_points = brain_data.get_picked_points() spheres = time_viewer._spheres hemi_str = [hemi] if hemi in ('lh', 'rh') else ['lh', 'rh'] for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 assert len(spheres) == len(hemi_str) # test removing points time_viewer.clear_points() assert len(picked_points['lh']) == 0 assert len(picked_points['rh']) == 0 # test picking a cell at random for idx, current_hemi in enumerate(hemi_str): current_mesh = brain_data._hemi_meshes[current_hemi] cell_id = np.random.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(current_mesh, cell_id) assert cell_id == test_picker.cell_id assert test_picker.point_id is None time_viewer.on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id sphere = spheres[idx] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = 'L' if current_hemi == 'lh' else 'R' hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni(vertices=vertex_id, hemis=hemi_int, subject=brain_data._subject_id, subjects_dir=brain_data._subjects_dir) label = "{}:{} MNI: {}".format(hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label assert len(spheres) == len(hemi_str) # and the scraper for it (will close the instance) if not check_version('sphinx_gallery'): return screenshot = brain_data.screenshot() fnames = [str(tmpdir.join('temp.png'))] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain_data)) gallery_conf = dict(src_dir=str(tmpdir)) scraper = _BrainScraper() rst = scraper(None, block_vars, gallery_conf) assert 'temp.png' in rst assert path.isfile(fnames[0]) img = image.imread(fnames[0]) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height
if op.isdir(op.join(subjects_dir, subject)): d = nib.load(op.join(subjects_dir, subject, 'mri', 'orig.mgz')) subject_orig_header = d.get_header() else: raise Exception( 'subject_orig_header is None and subjects_dir/subject is not a dir' ) return subject_orig_header if __name__ == '__main__': from src.utils import preproc_utils as pu SUBJECTS_DIR, MMVT_DIR, FREESURFER_HOME = pu.get_links() subject = 'mg78' points = [[-17.85, -52.18, 42.08]] true_ras = [[-16.92, -44.43, 29.06]] true_vox = [[146, 86, 76]] # point = [-13.1962, -66.5584, 33.3018] h = get_subject_orig_header(subject, SUBJECTS_DIR) vox = tkras_to_vox(points, h) print('vox: {}'.format(vox)) ras = vox_to_ras(vox, h) print('ras: {}'.format(ras)) import mne from mne.source_space import vertex_to_mni, combine_transforms, Transform, apply_trans mni2 = vertex_to_mni(23633, 0, 'mg78', SUBJECTS_DIR) print('mni2: {}'.format(mni2))
def test_brain_traces(renderer_interactive, hemi, src, tmpdir, brain_gc): """Test brain traces.""" if renderer_interactive._get_3d_backend() != 'pyvista': pytest.skip('Only PyVista supports traces') brain = _create_testing_brain( hemi=hemi, surf='white', src=src, show_traces=0.5, initial_time=0, volume_options=None, # for speed, don't upsample n_time=1 if src == 'mixed' else 5, ) assert brain.show_traces assert hasattr(brain, "picked_points") assert hasattr(brain, "_spheres") # test points picked by default picked_points = brain.get_picked_points() spheres = brain._spheres hemi_str = list() if src in ('surface', 'mixed'): hemi_str.extend([hemi] if hemi in ('lh', 'rh') else ['lh', 'rh']) if src in ('mixed', 'volume'): hemi_str.extend(['vol']) for current_hemi in hemi_str: assert len(picked_points[current_hemi]) == 1 n_spheres = len(hemi_str) if hemi == 'split' and src in ('mixed', 'volume'): n_spheres += 1 assert len(spheres) == n_spheres # test removing points brain.clear_points() assert len(spheres) == 0 for key in ('lh', 'rh', 'vol'): assert len(picked_points[key]) == 0 # test picking a cell at random rng = np.random.RandomState(0) for idx, current_hemi in enumerate(hemi_str): assert len(spheres) == 0 if current_hemi == 'vol': current_mesh = brain._data['vol']['grid'] vertices = brain._data['vol']['vertices'] values = current_mesh.cell_arrays['values'][vertices] cell_id = vertices[np.argmax(np.abs(values))] else: current_mesh = brain._hemi_meshes[current_hemi] cell_id = rng.randint(0, current_mesh.n_cells) test_picker = TstVTKPicker(None, None, current_hemi, brain) assert brain._on_pick(test_picker, None) is None test_picker = TstVTKPicker( current_mesh, cell_id, current_hemi, brain) assert cell_id == test_picker.cell_id assert test_picker.point_id is None brain._on_pick(test_picker, None) assert test_picker.point_id is not None assert len(picked_points[current_hemi]) == 1 assert picked_points[current_hemi][0] == test_picker.point_id assert len(spheres) > 0 sphere = spheres[-1] vertex_id = sphere._vertex_id assert vertex_id == test_picker.point_id line = sphere._line hemi_prefix = current_hemi[0].upper() if current_hemi == 'vol': assert hemi_prefix + ':' in line.get_label() assert 'MNI' in line.get_label() continue # the MNI conversion is more complex hemi_int = 0 if current_hemi == 'lh' else 1 mni = vertex_to_mni( vertices=vertex_id, hemis=hemi_int, subject=brain._subject_id, subjects_dir=brain._subjects_dir ) label = "{}:{} MNI: {}".format( hemi_prefix, str(vertex_id).ljust(6), ', '.join('%5.1f' % m for m in mni)) assert line.get_label() == label # remove the sphere by clicking in its vicinity old_len = len(spheres) test_picker._actors = sum((s._actors for s in spheres), []) brain._on_pick(test_picker, None) assert len(spheres) < old_len screenshot = brain.screenshot() screenshot_all = brain.screenshot(time_viewer=True) assert screenshot.shape[0] < screenshot_all.shape[0] # and the scraper for it (will close the instance) # only test one condition to save time if not (hemi == 'rh' and src == 'surface' and check_version('sphinx_gallery')): brain.close() return fnames = [str(tmpdir.join(f'temp_{ii}.png')) for ii in range(2)] block_vars = dict(image_path_iterator=iter(fnames), example_globals=dict(brain=brain)) block = ('code', """ something # brain.save_movie(time_dilation=1, framerate=1, # interpolation='linear', time_viewer=True) # """, 1) gallery_conf = dict(src_dir=str(tmpdir), compress_images=[]) scraper = _BrainScraper() rst = scraper(block, block_vars, gallery_conf) assert brain.plotter is None # closed gif_0 = fnames[0][:-3] + 'gif' for fname in (gif_0, fnames[1]): assert path.basename(fname) in rst assert path.isfile(fname) img = image.imread(fname) assert img.shape[1] == screenshot.shape[1] # same width assert img.shape[0] > screenshot.shape[0] # larger height assert img.shape[:2] == screenshot_all.shape[:2]