def _plt_src(name, kw_brain_obj, active_data, active_vert, sources, kw_source_obj, kw_activation, show): # Define a brain object and a source object : logger.info('Define a Brain and Source objects') from visbrain.objects import BrainObj, SourceObj, SceneObj brain_obj, source_obj = name + '_brain', name + '_sources' b_obj = BrainObj(brain_obj, **kw_brain_obj) s_obj = SourceObj(source_obj, sources, **kw_source_obj) s_obj.visible_obj = False # Add data to the BrainObj if needed : if isinstance(active_data, np.ndarray): logger.info("Add active data between " "[%2f, %2f]" % (active_data.min(), active_data.max())) b_obj.add_activation(data=active_data, vertices=active_vert, **kw_activation) # Return either a scene or a BrainObj and SourceObj : if show is True: # Display inside the Brain GUI # Define a Brain instance : from visbrain import Brain brain = Brain(brain_obj=b_obj, source_obj=s_obj) # By default, display colorbar if activation : if isinstance(active_data, np.ndarray): brain.menuDispCbar.setChecked(True) brain._fcn_menu_disp_cbar() brain.show() elif show is 'scene': # return a SceneObj logger.info('Define a unique scene for the Brain and Source objects') sc = SceneObj() sc.add_to_subplot(s_obj) sc.add_to_subplot(b_obj, use_this_cam=True) return sc else: # return the BrainObj and SourceObj s_obj.visible_obj = True return b_obj, s_obj
def visbrain_plot(mesh, tex=None, caption=None, cblabel=None, visb_sc=None, cmap='jet'): """ Visualize a trimesh object using visbrain core plotting tool :param mesh: trimesh object :param tex: numpy array of a texture to be visualized on the mesh :return: """ from visbrain.objects import BrainObj, ColorbarObj, SceneObj b_obj = BrainObj('gui', vertices=np.array(mesh.vertices), faces=np.array(mesh.faces), translucent=False) if not isinstance(visb_sc, SceneObj): visb_sc = SceneObj(bgcolor='black', size=(1000, 1000)) # identify (row, col) row, _ = get_visb_sc_shape(visb_sc) visb_sc.add_to_subplot(b_obj, row=row, col=0, title=caption) if tex is not None: b_obj.add_activation(data=tex, cmap=cmap, clim=(np.min(tex), np.max(tex))) CBAR_STATE = dict(cbtxtsz=20, txtsz=20., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.), cblabel=cblabel) cbar = ColorbarObj(b_obj, **CBAR_STATE) visb_sc.add_to_subplot(cbar, row=row, col=1, width_max=200) return visb_sc
def test_overlay_from_file(self): """Test add_activation method.""" # Prepare the brain : b_obj = BrainObj('inflated') file_1 = self.need_file(NEEDED_FILES['OVERLAY_1']) file_2 = self.need_file(NEEDED_FILES['OVERLAY_2']) # NIFTI Overlay : b_obj.add_activation(file=file_1, clim=(4., 30.), hide_under=4, cmap='Reds_r', hemisphere='left') b_obj.add_activation(file=file_2, clim=(4., 30.), hide_under=4, cmap='Blues_r', hemisphere='left', n_contours=10) # Meg inverse : file_3 = read_stc(self.need_file(NEEDED_FILES['MEG_INVERSE'])) data = file_3['data'][:, 2] vertices = file_3['vertices'] b_obj.add_activation(data=data, vertices=vertices, smoothing_steps=3) b_obj.add_activation(data=data, vertices=vertices, smoothing_steps=5, clim=(13., 22.), hide_under=13., cmap='plasma') # GII overlays : gii = self.need_file(NEEDED_FILES['GII_FILE']) gii_overlay = self.need_file(NEEDED_FILES['GII_OVERLAY']) b_gii = BrainObj(gii) b_gii.add_activation(file=gii_overlay)
def texture_plot(mesh, tex=None, caption=None, cblabel=None, visb_sc=None, cmap='gnuplot'): """ Projecting Texture onto trimesh object using visbrain core plotting tool :param mesh: trimesh object :param tex: numpy array of a texture to be visualized :return: 0 """ b_obj = BrainObj('gui', vertices=np.array(mesh.vertices), faces=np.array(mesh.faces), translucent=False) if visb_sc is None: visb_sc = SceneObj(bgcolor='black', size=(1400, 1000)) visb_sc.add_to_subplot(b_obj, title=caption) visb_sc_shape = (1, 1) else: visb_sc_shape = get_visb_sc_shape(visb_sc) visb_sc.add_to_subplot(b_obj, row=visb_sc_shape[0] - 1, col=visb_sc_shape[1], title=caption) if tex is not None: b_obj.add_activation(data=tex, cmap=cmap, clim=(np.min(tex), np.max(tex))) CBAR_STATE = dict(cbtxtsz=20, txtsz=20., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.), cblabel=cblabel) cbar = ColorbarObj(b_obj, **CBAR_STATE) visb_sc.add_to_subplot(cbar, row=visb_sc_shape[0] - 1, col=visb_sc_shape[1] + 1, width_max=200) return visb_sc
def visbrain_plot(mesh, tex=None): """ Visualize a trimesh object using visbrain core plotting tool :param mesh: trimesh object :param tex: numpy array of a texture to be visualized on the mesh :return: """ from visbrain.objects import BrainObj # invert_normals = True -> Light outside # invert_normals = False -> Light inside b_obj = BrainObj('gui', vertices=mesh.vertices, faces=mesh.faces, translucent=False, invert_normals=True) if tex is not None: b_obj.add_activation(data=tex, cmap='viridis') b_obj.preview(bgcolor='white')
def _plt_src(name, kw_brain_obj, active_data, active_vert, sources, kw_source_obj, kw_activation, show): # Define a brain object and a source object : logger.info(' Define a Brain and Source objects') from visbrain.objects import BrainObj, SourceObj, SceneObj brain_obj, source_obj = name + '_brain', name + '_sources' b_obj = BrainObj(brain_obj, **kw_brain_obj) s_obj = SourceObj(source_obj, sources, **kw_source_obj) s_obj.visible_obj = False # Add data to the BrainObj if needed : if isinstance(active_data, np.ndarray): logger.info(" Add active data between " "[%2f, %2f]" % (active_data.min(), active_data.max())) b_obj.add_activation(data=active_data, vertices=active_vert, **kw_activation) # Return either a scene or a BrainObj and SourceObj : if show is True: # Display inside the Brain GUI # Define a Brain instance : from visbrain.gui import Brain brain = Brain(brain_obj=b_obj, source_obj=s_obj) brain._brain_template.setEnabled(False) # By default, display colorbar if activation : if isinstance(active_data, np.ndarray): brain.menuDispCbar.setChecked(True) brain._fcn_menu_disp_cbar() brain.show() elif show is 'scene': # return a SceneObj logger.info(" Define a unique scene for the Brain and Source " "objects") sc = SceneObj() sc.add_to_subplot(s_obj) sc.add_to_subplot(b_obj, use_this_cam=True) return sc else: # return the BrainObj and SourceObj s_obj.visible_obj = True return b_obj, s_obj
""" file_name = 'meg_source_estimate-lh.stc' download_file(file_name) # Read the *.stc file : file = read_stc(path_to_visbrain_data(file=file_name)) # Get the data and vertices from the file : data = file['data'][:, 2] vertices = file['vertices'] # Define a brain object and add the data to the mesh : b_obj = BrainObj('white', translucent=True, hemisphere='left') b_obj.add_activation(data=data, vertices=vertices, smoothing_steps=5, clim=(7., 21.), hide_under=7., cmap='viridis') # Build arrows : dt = np.dtype([('vertices', float, 3), ('normals', float, 3)]) arrows = np.zeros(len(data), dtype=dt) arrows['vertices'] = b_obj.vertices[vertices, :] arrows['normals'] = b_obj.normals[vertices, :] select = data >= 7. # Define the vector object : v_obj = VectorObj('vector', arrows, data=data, inferred_data=True,
""" from visbrain import Brain from visbrain.objects import BrainObj from visbrain.io import path_to_visbrain_data, download_file, read_stc """Download file if needed : """ file = 'meg_source_estimate-lh.stc' download_file(file) # Read the *.stc file : file = read_stc(path_to_visbrain_data(file=file)) # Get the data and vertices from the file : data = file['data'][:, 2] vertices = file['vertices'] # Define a brain object and add the data to the mesh : b_obj = BrainObj('inflated', translucent=False, hemisphere='left') b_obj.add_activation(data=data, vertices=vertices, smoothing_steps=5, clim=(13., 22.), hide_under=13., cmap='plasma', hemisphere='left') # Finally, pass the brain object to the Brain module : vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
""" Display conjunction map ======================= Display a conjunction map from a nii.gz file (NiBabel required). See the original PySurfer example : https://pysurfer.github.io/auto_examples/plot_fmri_conjunction.html#sphx-glr-auto-examples-plot-fmri-conjunction-py .. image:: ../../_static/examples/ex_eegmeg_conjunction_map.png """ from visbrain.gui import Brain from visbrain.objects import BrainObj from visbrain.io import download_file """Download files if needed """ file_1 = download_file('lh.sig.nii.gz', astype='example_data') file_2 = download_file('lh.alt_sig.nii.gz', astype='example_data') b_obj = BrainObj('inflated', translucent=False, sulcus=True) b_obj.add_activation(file=file_1, clim=(4., 30.), hide_under=4, cmap='Reds_r', hemisphere='left') b_obj.add_activation(file=file_2, clim=(4., 30.), hide_under=4, cmap='Blues_r', hemisphere='left') vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
# be convenient to reload your template later. ############################################################################### # fMRI activation ############################################################################### # Add fMRI activations (included in a nii.gz file) to the surface. The provided # file comes from MNE-python # Download the lh.sig.nii.gz file file = download_file('lh.sig.nii.gz', astype='example_data') # Define the [...] you know b_obj_fmri = BrainObj('inflated', translucent=False, sulcus=True) # Add fMRI activation and hide every activation that is under 5. b_obj_fmri.add_activation(file=file, clim=(5., 20.), hide_under=5, cmap='viridis', hemisphere='left') sc.add_to_subplot(b_obj_fmri, row=2, col=1, title='Add fMRI activation', rotate='left', **KW) ############################################################################### # MEG inverse solution ############################################################################### # Finally, plot MEG inverse solution. The provided file comes from MNE-python # Dowload meg_source_estimate-rh.stc file and load the data
############################################################################### CAM_STATE = dict(azimuth=0, # azimuth angle elevation=90, # elevation angle ) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) sc = SceneObj(camera_state=CAM_STATE, size=(1400, 1000)) ############################################################################### # fMRI activation ############################################################################### file = download_file('lh.sig.nii.gz', astype='example_data') b_obj_fmri = BrainObj('inflated', translucent=False, sulcus=True) b_obj_fmri.add_activation(file=file, clim=(5., 20.), hide_under=5, cmap='viridis', hemisphere='left') sc.add_to_subplot(b_obj_fmri, row=0, col=0, row_span=2, title='fMRI activation', rotate='top') ############################################################################### # Region Of Interest (ROI) ############################################################################### roi_aal = RoiObj('aal') roi_aal.select_roi(select=[29, 30], unique_color=True, smooth=11) sc.add_to_subplot(roi_aal, row=0, col=1, title='Region Of Interest (ROI)') sc.add_to_subplot(BrainObj('B1'), use_this_cam=True, row=0, col=1) ############################################################################### # Sources ###############################################################################
See the original PySurfer example : https://pysurfer.github.io/auto_examples/plot_fmri_conjunction.html#sphx-glr-auto-examples-plot-fmri-conjunction-py .. image:: ../../_static/examples/ex_eegmeg_conjunction_map.png """ from visbrain.gui import Brain from visbrain.objects import BrainObj from visbrain.io import download_file """Download files if needed """ file_1 = download_file('lh.sig.nii.gz', astype='example_data') file_2 = download_file('lh.alt_sig.nii.gz', astype='example_data') b_obj = BrainObj('inflated', translucent=False, sulcus=True) b_obj.add_activation(file=file_1, clim=(4., 30.), hide_under=4, cmap='Reds_r', hemisphere='left') b_obj.add_activation(file=file_2, clim=(4., 30.), hide_under=4, cmap='Blues_r', hemisphere='left') vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
""" Display fMRI activation ======================= Display fMRI activations from a nii.gz file (NiBabel required). See the original example : https://pysurfer.github.io/auto_examples/plot_fmri_activation.html#sphx-glr-auto-examples-plot-fmri-activation-py .. image:: ../../_static/examples/ex_eegmeg_fmri_activations.png """ from visbrain.gui import Brain from visbrain.objects import BrainObj from visbrain.io import download_file """Download file if needed """ file = download_file('lh.sig.nii.gz', astype='example_data') b_obj = BrainObj('inflated', translucent=False, sulcus=True) b_obj.add_activation(file=file, clim=(5., 20.), hide_under=5, cmap='viridis', hemisphere='left') vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
meshrr = [b_obj_proj_rr.vertices, b_obj_proj_rr.faces] meshrl = [b_obj_proj_rl.vertices, b_obj_proj_rl.faces] texturell = surface.vol_to_surf(stat_img2, meshll) texturelr = surface.vol_to_surf(stat_img2, meshlr) texturerr = surface.vol_to_surf(stat_img2, meshrr) texturerl = surface.vol_to_surf(stat_img2, meshrl) texturell = texturell.ravel() texturelr = texturelr.ravel() texturerr = texturerr.ravel() texturerl = texturerl.ravel() b_obj_proj_ll.add_activation(texturell, hemisphere='left', cmap='hot_r', vmin=0, vmax=1, clim=(0, 1)) b_obj_proj_lr.add_activation(texturelr, hemisphere='left', cmap='hot_r', vmin=0, vmax=1, clim=(0, 1)) b_obj_proj_rr.add_activation(texturerr, hemisphere='right', cmap='hot_r', vmin=0, vmax=1,
# normals are provided, normals are going to be computed but it's a bit # slower. Then, you can save your template using `BrainObj.save`. This can # be convenient to reload your template later. ############################################################################### # fMRI activation ############################################################################### # Add fMRI activations (included in a nii.gz file) to the surface. The provided # file comes from MNE-python # Download the lh.sig.nii.gz file file = download_file('lh.sig.nii.gz', astype='example_data') # Define the [...] you know b_obj_fmri = BrainObj('inflated', translucent=False, sulcus=True) # Add fMRI activation and hide every activation that is under 5. b_obj_fmri.add_activation(file=file, clim=(5., 20.), hide_under=5, cmap='viridis', hemisphere='left') sc.add_to_subplot(b_obj_fmri, row=2, col=1, title='Add fMRI activation', rotate='left', **KW) ############################################################################### # MEG inverse solution ############################################################################### # Finally, plot MEG inverse solution. The provided file comes from MNE-python # Dowload meg_source_estimate-rh.stc file and load the data file = read_stc(download_file('meg_source_estimate-rh.stc', astype='example_data')) # Get the data of index 2 and the vertices data = file['data'][:, 2] vertices = file['vertices'] # You know...
from visbrain.io import read_stc, download_file """Download file if needed """ stc_file = download_file('meg_source_estimate-lh.stc', astype='example_data') # Read the *.stc file : file = read_stc(stc_file) # Get the data and vertices from the file : data = file['data'][:, 2] vertices = file['vertices'] # Define a brain object and add the data to the mesh : b_obj = BrainObj('white', translucent=True, hemisphere='left') b_obj.add_activation(data=data, vertices=vertices, smoothing_steps=5, clim=(7., 21.), hide_under=7., cmap='viridis') # Build arrows : dt = np.dtype([('vertices', float, 3), ('normals', float, 3)]) arrows = np.zeros(len(data), dtype=dt) arrows['vertices'] = b_obj.vertices[vertices, :] arrows['normals'] = b_obj.normals[vertices, :] select = data >= 7. # Define the vector object : v_obj = VectorObj('vector', arrows, data=data, inferred_data=True, clim=(7., 21.), antialias=True, cmap='viridis', select=select, line_width=2., arrow_coef=1.2, dynamic=(.2, 1.)) # Finally, pass the brain and vector object to the Brain module :
https://pysurfer.github.io/auto_examples/plot_meg_inverse_solution.html#sphx-glr-auto-examples-plot-meg-inverse-solution-py .. image:: ../../_static/examples/ex_eegmeg_meg_inverse.png """ from visbrain.gui import Brain from visbrain.objects import BrainObj from visbrain.io import download_file, read_stc """Download file if needed : """ stc_file = download_file('meg_source_estimate-lh.stc', astype='example_data') # Read the *.stc file : file = read_stc(stc_file) # Get the data and vertices from the file : data = file['data'][:, 2] vertices = file['vertices'] # Define a brain object and add the data to the mesh : b_obj = BrainObj('inflated', translucent=False, hemisphere='left') b_obj.add_activation(data=data, vertices=vertices, smoothing_steps=15, clim=(13., 22.), hide_under=13., cmap='plasma', hemisphere='left') # Finally, pass the brain object to the Brain module : vb = Brain(brain_obj=b_obj) vb.rotate('left') vb.show()
def mne_plot_source_estimation(sbj, sbj_dir, fwd_file, stc_file=None, hemisphere='both', parc='aparc', active_data=0, kw_brain_obj={}, kw_source_obj={}, kw_activation={}, show=True): """Plot source estimation. Parameters ---------- sbj : string The subject name. sbj_dir : string Path to the subject directory. fwd_file : string The file name of the forward solution, which should end with -fwd.fif or -fwd.fif.gz. stc_file : string | None Path to the *.stc inverse solution file. hemisphere : {'left', 'both', 'right'} The hemisphere to plot. parc : string | 'aparc' The parcellation to use, e.g., ‘aparc’ or ‘aparc.a2009s’. active_data : array_like, int | 0 The data to set to vertices. If an stc file is provided and if `active_data` is an integer, it describes the time instant in which you want to see the activation. Otherwise, `active_data` must be an array with the same same shape as the number of active vertices. kw_brain_obj : dict | {} Additional inputs to pass to the `BrainObj` class. kw_source_obj : dict | {} Additional inputs to pass to the `SourceObj` class. kw_activation : dict | {} Additional inputs to pass to the `BrainObj.add_activation` method. show : bool | False If True, the window of the `Brain` module is automatically displayed. If False, a BrainObj and a SourceObj are returned. Finally, if 'scene' a SceneObj is returned. Returns ------- b_obj : BrainObj A predefined `BrainObj` (if `show=False`) s_obj : SourceObj A predefined `SourceObj`, hide by default (if `show=False`) """ # Test that mne is installed and import : is_mne_installed(raise_error=True) import mne from mne.source_space import head_to_mni hemi_idx = {'left': [0], 'right': [1], 'both': [0, 1]}[hemisphere] # Read the forward solution : fwd = mne.read_forward_solution(fwd_file) logger.debug('Read the forward solution') # Get source space : fwd_src = fwd['src'] # Get the MRI (surface RAS)-> head matrix mri_head_t = fwd['mri_head_t'] # Head to MNI conversion logger.info("Head to MNI conversion") mesh, sources = [], [] for hemi in hemi_idx: vert_ = fwd_src[hemi]['rr'] sources_ = fwd_src[hemi]['rr'][fwd_src[hemi]['vertno']] m_ = head_to_mni(vert_, sbj, mri_head_t, subjects_dir=sbj_dir) s_ = head_to_mni(sources_, sbj, mri_head_t, subjects_dir=sbj_dir) mesh.append(m_) sources.append(s_) # Get active vertices : # fwd_src contains the source spaces, the first 2 are the cortex # (left and right hemi, the others are related to the substructures) if len(hemi_idx) == 1: active_vert = fwd_src[hemi_idx[0]]['vertno'] else: active_left = fwd_src[0]['vertno'] active_right = fwd_src[1]['vertno'] + mesh[0].shape[0] active_vert = np.r_[active_left, active_right] logger.info('%i active vertices detected ' % len(active_vert)) # Add data to the mesh : if isinstance(active_data, np.ndarray): if len(active_data) != len(active_vert): logger.error("The length of `active data` (%i) must be the same " "the length of the number of active vertices " "(%i)" % (len(active_data), len(active_vert))) active_data = active_vert = None else: logger.info("Array of active data used.") elif isinstance(stc_file, str) and isinstance(active_data, int): # Get active data : assert os.path.isfile(stc_file) n_tp = active_data data = mne.read_source_estimate(stc_file).data active_data = np.abs(data[:, n_tp] / data[:, n_tp].max()) logger.info("Time instant %i used for activation" % n_tp) else: logger.info("No active data detected.") active_data = active_vert = None # Concatenate vertices, faces and sources : vertices = np.concatenate(mesh) lr_index = np.r_[np.ones((len(mesh[0]), )), np.zeros((len(mesh[1]), ))] sources = np.concatenate(sources) # Get faces : if len(hemi_idx) == 1: faces = fwd_src[hemi_idx[0]]['tris'] else: _faces_l = fwd_src[0]['tris'] _faces_r = fwd_src[1]['tris'] + _faces_l.max() + 1 faces = np.r_[_faces_l, _faces_r].astype(int) # Define a brain object and a source object : logger.info('Define a Brain and Source objects') from visbrain.objects import BrainObj, SourceObj, SceneObj b_obj = BrainObj(sbj + '_brain', vertices=vertices, faces=faces, lr_index=lr_index.astype(bool), **kw_brain_obj) s_obj = SourceObj(sbj + '_src', sources, visible=False, **kw_source_obj) # Add data to the BrainObj if needed : if isinstance(active_data, np.ndarray): logger.info("Add active data between " "[%2f, %2f]" % (active_data.min(), active_data.max())) b_obj.add_activation(data=active_data, vertices=active_vert, **kw_activation) # Return either a scene or a BrainObj and SourceObj : if show: # Display inside the Brain GUI # Define a Brain instance : from visbrain import Brain brain = Brain(brain_obj=b_obj, source_obj=s_obj) # Remove all brain templates except the one of the subject : brain._brain_template.setEnabled(False) # By default, display colorbar if activation : if isinstance(active_data, np.ndarray): brain.menuDispCbar.setChecked(True) brain._fcn_menu_disp_cbar() brain.show() elif show is 'scene': # return a SceneObj logger.info('Define a unique scene for the Brain and Source objects') sc = SceneObj() sc.add_to_subplot(s_obj) sc.add_to_subplot(b_obj, use_this_cam=True) return sc else: # return the BrainObj and SourceObj return b_obj, s_obj