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 plot_meg_connectome(): ''' Plot the MEG brain connectome for the master figure in MEG paper ''' megdata = sio.loadmat('MEG_data_info/total_connecivtiy_coord_label.mat') total_con = megdata['connectivity'] xyz = megdata['ROI_coords'] normal_con = total_con[:53] smci_con = total_con[53:-28] pmci_con = total_con[-28:] edges = smci_con[8, :, :] sc = SceneObj(bgcolor='black') c_obj = ConnectObj('default', xyz, edges, select=edges > .026, line_width=3., dynamic=(0., 1.), dynamic_orientation='center', cmap='bwr', color_by='strength') s_obj = SourceObj('sources', xyz, color='red', radius_min=15.) cb_obj = ColorbarObj(c_obj, cblabel='Edge strength') sc.add_to_subplot(c_obj, title='MEG brain network') sc.add_to_subplot(s_obj) sc.add_to_subplot(BrainObj('B3'), use_this_cam=True) sc.add_to_subplot(cb_obj, col=1, width_max=200) sc.preview()
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
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
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)) print(""" ============================================================================= fMRI activation ============================================================================= """) file = download_file('lh.sig.nii.gz') 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') print(""" =============================================================================== 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) print(""" ============================================================================= Sources
# Generate random data and random connectivity data = np.random.uniform(low=-1., high=1., size=(n_sources, )) conn = np.triu(np.random.uniform(-1., 1., (n_sources, n_sources))) conn_select = (-.005 < conn) & (conn < .005) # Scene creation sc = SceneObj() ############################################################################### # Animate a single brain object ############################################################################### # Here we set an animation for a single brain object. b_obj_1 = BrainObj('inflated', translucent=False) b_obj_1.animate() sc.add_to_subplot(b_obj_1, rotate='left', title='Animate a single object') ############################################################################### # Animate multiple objects ############################################################################### # Here we animate multiple objects inside a subplot s_obj_1 = SourceObj('s1', xyz, data=data) b_obj_2 = BrainObj('white') b_obj_2.animate() sc.add_to_subplot(s_obj_1, row=1, title='Animate multiple objects') sc.add_to_subplot(b_obj_2, row=1, rotate='right', use_this_cam=True) ############################################################################### # Animate sources
antialias=True, cmap='bwr', line_width=4.) s_obj = SourceObj('s', xyz, data=radius, radius_min=5, radius_max=15, text=names, text_size=10, text_color='white', text_translate=(0., 0., 0.)) s_obj.color_sources(data=radius, cmap='inferno') cbar = ColorbarObj(c_obj, txtcolor='white', txtsz=15, cblabel='Connectivity', cbtxtsz=20) band = _parse_string(connect_file, freq_band_names) title = 'Connectivity on {} band'.format(band) sc.add_to_subplot(c_obj, title=title, title_size=14, title_bold=True, title_color='white', row=nf) sc.add_to_subplot(s_obj, rotate='top', zoom=.5, use_this_cam=True, row=nf) sc.add_to_subplot(cbar, col=1, width_max=200, row=nf) sc.preview()
sc = SceneObj(size=(1500, 800)) ############################################################################### # Ferret brain ############################################################################### # Hutchinson EB, Schwerin SC, Radomski KL, Sadeghi N, Jenkins J, Komlosh ME, # Irfanoglu MO, Juliano SL, Pierpaoli C (2017) "Population based MRI and DTI # templates of the adult ferret brain and tools for voxelwise analysis" # Neuroimage 152:575–589. [doi 10.1016/j.neuroimage.2017.03.009] ferret_file = download_file('ferret.x3d', astype='example_data') b_ferret_obj = BrainObj(ferret_file, translucent=False) sc.add_to_subplot(b_ferret_obj, title='Ferret brain (Hutchinson et al. 2017)') ############################################################################### # Macaque brain (1) ############################################################################### # Markov NT, Ercsey-Ravasz MM, Ribeiro Gomes AR, Lamy C, Magrou L, Vezoli J, # Misery P, Falchier A, Quilodran R, Gariel MA, Sallet J, Gamanut R, # Huissoud C, Clavagnier S, Giroud P, Sappey-Marinier D, Barone P, Dehay C, # Toroczkai Z, Knoblauch K, Van Essen DC, Kennedy H (2014) "A weighted and # directed interareal connectivity matrix for macaque cerebral cortex." Cereb # Cortex 24(1):17-36. [doi 10.1093/cercor/bhs270] macaque_file_1 = download_file('macaque_1.x3d', astype='example_data') b_macaque_obj_1 = BrainObj(macaque_file_1, translucent=False) sc.add_to_subplot(b_macaque_obj_1, col=1,
s_1 = pac_signals_wavelet(sf=sf, f_pha=10., f_amp=80., n_epochs=1, n_times=5000)[0] s_2 = pac_signals_wavelet(sf=sf, f_pha=5., f_amp=100., n_epochs=1, n_times=5000)[0] sig = np.c_[s_1, s_2] sc = SceneObj(size=(1200, 600)) print(""" # ============================================================================= # Comodulogram # ============================================================================= """) pac_obj_como = PacmapObj('como', sig, sf=sf, f_pha=(2, 30, 1, .5), f_amp=(60, 150, 10, 1), interpolation='bicubic') sc.add_to_subplot(pac_obj_como, row=0, col=0, zoom=.9, title='Comodulogram') print(""" # ============================================================================= # Optimal phase frequency # ============================================================================= """) pac_pha_como = PacmapObj('como', sig, sf=sf, f_pha=(2, 30, 1, .5), f_amp=[70., 110.], n_window=500, cmap='plasma') sc.add_to_subplot(pac_pha_como, row=0, col=1, zoom=.9, title='Optimal phase frequency') print(""" # ============================================================================= # Optimal amplitude frequency # =============================================================================
""" sf = 1024. s_1 = pac_signals_wavelet(sf=sf, fpha=10., famp=80., ntrials=1, npts=5000)[0] s_2 = pac_signals_wavelet(sf=sf, fpha=5., famp=100., ntrials=1, npts=5000)[0] sig = np.c_[s_1, s_2] sc = SceneObj(size=(1200, 600)) print(""" # ============================================================================= # Comodulogram # ============================================================================= """) pac_obj_como = PacmapObj('como', sig, sf=sf, f_pha=(2, 30, 1, .5), f_amp=(60, 150, 10, 1), interpolation='bicubic') sc.add_to_subplot(pac_obj_como, row=0, col=0, zoom=.9, title='Comodulogram') print(""" # ============================================================================= # Optimal phase frequency # ============================================================================= """) pac_pha_como = PacmapObj('como', sig, sf=sf, f_pha=(2, 30, 1, .5), f_amp=[70., 110.], n_window=500, cmap='plasma') sc.add_to_subplot(pac_pha_como, row=0, col=1, zoom=.9, title='Optimal phase frequency') print(""" # ============================================================================= # Optimal amplitude frequency # =============================================================================
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 ############################################################################### s_obj = SourceObj('FirstSources', xyz, data=data)
clim = (psds.min(), psds.max()) # Find indices of frequencies : idx_fplt = np.abs( (freqs.reshape(1, 1, -1) - freq_bands[..., np.newaxis])).argmin(2) psdf = np.array([psds[:, k[0]:k[1]].mean(1) for k in idx_fplt]) radius = normalize(np.c_[psdf.min(1), psdf.max(1)], 5, 25).astype(float) for num, (fb, fbn, psd, rx) in enumerate(zip(freq_bands, freq_band_names, psdf, radius)): s_obj = SourceObj('s', xyz, data=psd, radius_min=rx[0], radius_max=rx[1]) # noqa s_obj.color_sources(data=psd, cmap='cool', clim=clim) sc.add_to_subplot(s_obj, col=num, title=str(fb) + ' - ' + fbn, title_color='white', rotate='top', zoom=.6) cbar = ColorbarObj(s_obj, txtcolor='white', cblabel='PSD', txtsz=15, cbtxtsz=20) sc.add_to_subplot(cbar, col=len(freq_bands), width_max=200) sc.preview()
sc = SceneObj(bgcolor="black", size=(500, 500)) nodes = np.array(coords) edges = correlation_matrix[:len(nodes), :len(nodes)] # nodes # Coloring method color_by = 'strength' # Because we don't want to plot every connections, we only keep connections # above .7 select = edges > .5 # Define the connectivity object c_default = ConnectObj('default', nodes, edges, select=select, line_width=2., cmap='Spectral_r', color_by=color_by) # Then, we define the sources s_obj = SourceObj('sources', nodes, color='#ab4642', radius_min=15.) sc.add_to_subplot(c_default, title='Color by connectivity strength') # And add connect, source and brain objects to the scene brain_obj = BrainObj('B1', sulcus=True, verbose=True) sc.add_to_subplot(brain_obj, use_this_cam=True, rotate='right') sc.preview()
"_session_rest_subject_id_01") lol_file = op.join(res_path, "community_rada", "Z_List.lol") net_file = op.join(res_path, "prep_rada", "Z_List.net") roles_file = op.join(res_path, "node_roles", "node_roles.txt") views = ["left", 'top'] for i_v, view in enumerate(views): b_obj = BrainObj("B1", translucent=True) sc.add_to_subplot(b_obj, row=0, col=i_v, use_this_cam=True, rotate=view, title=("Modules"), title_size=14, title_bold=True, title_color='black') c_obj, s_obj = visu_graph_modules(lol_file=lol_file, net_file=net_file, coords_file=ROI_MNI_coords_file, inter_modules=False) sc.add_to_subplot(c_obj, row=0, col=i_v) sc.add_to_subplot(s_obj, row=0, col=i_v) b_obj = BrainObj('B1', translucent=True) sc.add_to_subplot(b_obj,
vmin=0, vmax=.1, clim=(0, .1)) b_obj_proj_rl.add_activation(texturerl, hemisphere='right', cmap='hot_r', vmin=0, vmax=.1, clim=(0, .1), hide_under=0) cb_proj = ColorbarObj(b_obj_proj_rl, cblabel='Correlation', cmap='hot_r', vmin=0, vmax=.1, **CBAR_STATE) sc.add_to_subplot(b_obj_proj_ll, row=0, col=0, rotate='left') sc.add_to_subplot(b_obj_proj_lr, row=0, col=1, rotate='right') sc.add_to_subplot(b_obj_proj_rl, row=0, col=2, rotate='left') sc.add_to_subplot(b_obj_proj_rr, row=0, col=3, rotate='right') #sc.add_to_subplot(cb_proj, row=0, col=4, width_max=100) #sc.preview() sc.screenshot(os.path.join(fig_dir, fname + '.png'), transparent=True)
from visbrain.objects import BrainObj, SceneObj from visbrain.io import download_file sc = SceneObj(size=(1500, 800)) ############################################################################### # Ferret brain ############################################################################### # Hutchinson EB, Schwerin SC, Radomski KL, Sadeghi N, Jenkins J, Komlosh ME, # Irfanoglu MO, Juliano SL, Pierpaoli C (2017) "Population based MRI and DTI # templates of the adult ferret brain and tools for voxelwise analysis" # Neuroimage 152:575–589. [doi 10.1016/j.neuroimage.2017.03.009] ferret_file = download_file('ferret.x3d', astype='example_data') b_ferret_obj = BrainObj(ferret_file, translucent=False) sc.add_to_subplot(b_ferret_obj, title='Ferret brain (Hutchinson et al. 2017)') ############################################################################### # Macaque brain (1) ############################################################################### # Markov NT, Ercsey-Ravasz MM, Ribeiro Gomes AR, Lamy C, Magrou L, Vezoli J, # Misery P, Falchier A, Quilodran R, Gariel MA, Sallet J, Gamanut R, # Huissoud C, Clavagnier S, Giroud P, Sappey-Marinier D, Barone P, Dehay C, # Toroczkai Z, Knoblauch K, Van Essen DC, Kennedy H (2014) "A weighted and # directed interareal connectivity matrix for macaque cerebral cortex." Cereb # Cortex 24(1):17-36. [doi 10.1093/cercor/bhs270] macaque_file_1 = download_file('macaque_1.x3d', astype='example_data') b_macaque_obj_1 = BrainObj(macaque_file_1, translucent=False) sc.add_to_subplot(b_macaque_obj_1, col=1,
brain_obj = BrainObj('Custom', vertices=verts, faces=faces, normals=normals, translucent=False) source_object = SourceObj('iEEG', xyz, data=data[:, 0], cmap=colormap) # Project source's activity source_object.project_sources(brain_obj) source_object.color_sources(data=data[:, 0]) # Finally, add the source and brain objects to the subplot scene.add_to_subplot(source_object, row=0, col=0, title='Project iEEG data', **KW) scene.add_to_subplot(brain_obj, row=0, col=0, rotate='left', use_this_cam=True) # Finally, add the colorbar : colorbar = ColorbarObj(source_object, cblabel='Projection of niEEG data', **CBAR_STATE) scene.add_to_subplot(colorbar, row=0, col=1, width_max=200, rotate='up') # Animation app_timer = Timer(app=CONFIG['VISPY_APP'], interval='auto', iterations=-1)
data = np.random.uniform(low=-1., high=1., size=(n_sources,)) conn = np.triu(np.random.uniform(-1., 1., (n_sources, n_sources))) conn_select = (-.005 < conn) & (conn < .005) # Scene creation sc = SceneObj() ############################################################################### # Animate a single brain object ############################################################################### # Here we set an animation for a single brain object. b_obj_1 = BrainObj('inflated', translucent=False) b_obj_1.animate() sc.add_to_subplot(b_obj_1, rotate='left', title='Animate a single object') ############################################################################### # Animate multiple objects ############################################################################### # Here we animate multiple objects inside a subplot s_obj_1 = SourceObj('s1', xyz, data=data) b_obj_2 = BrainObj('white') b_obj_2.animate() sc.add_to_subplot(s_obj_1, row=1, title='Animate multiple objects') sc.add_to_subplot(b_obj_2, row=1, rotate='right', use_this_cam=True) ###############################################################################
pic_data = np.asarray(pic_data) clim = (.01 * pic_data.min(), .01 * pic_data.max()) # Scene definition sc = SceneObj() ############################################################################### # Basic plot ############################################################################### # Basic plot without further customizations # Define time-series and picture objects ts_0 = TimeSeries3DObj('t0', ts_data, xyz, antialias=True) pic_0 = Picture3DObj('p0', pic_data, xyz, clim=clim) # Add those objects to the scene sc.add_to_subplot(ts_0, row=0, col=0, zoom=.2, title='Basic 3D TS plot') sc.add_to_subplot(pic_0, row=0, col=1, zoom=.5, title='Basic 3D pictures plot') ############################################################################### # Subset selection ############################################################################### # Select a subset of time-series and pictures using either a list of intergers # or booleans # Define a select variables using either intergers or boolean values s_ts = [0, 2, 4] s_pic = [True, False, True, False, True] # Define time-series and picture objects ts_1 = TimeSeries3DObj('t1', ts_data, xyz, antialias=True, select=s_ts) pic_1 = Picture3DObj('p1', pic_data, xyz, clim=clim, select=s_pic, cmap='bwr') # Add those objects to the scene
sf = 512. # sampling frequency n_pts = 1000 # number of time points n_channels = 5 # number of channels n_trials = 4 # number of trials data_3d = generate_eeg(n_pts=n_pts, n_channels=n_channels, n_trials=n_trials, f_max=20., smooth=200, noise=1000)[0] channels = ['Channel %i' % (k + 1) for k in range(n_channels)] trials = ['Trial %i' % k for k in range(n_trials)] # Generate the titles of each signal title = ['%s - %s' % (k, i) for k, i in product(channels, trials)] # Plot the data as a grid and add it to the scene g_obj_grid = GridSignalsObj('3d', data_3d, title=title, plt_as='grid') sc.add_to_subplot(g_obj_grid, title='Grid of 3D data') ############################################################################### # Plot MNE-Python data ############################################################################### # The GridSignalsObj is also compatible with several MNE-Python instance (i.e # mne.io.Raw, mne.io.RawArray and mne.Epochs). Here we illustrate how to plot # epochs in a grid. # Create MNE data data_mne = generate_eeg(n_pts=n_pts, n_channels=n_channels, f_max=20., smooth=200, noise=1000)[0] # Create info required for the definition of the RawArray info = mne.create_info(channels, sf) # Create a RawArray MNE instance
# First, we download a connectivity dataset consisting of the location of each # node (iEEG site) and the connectivity strength between those nodes. The first # coloring method illustrated bellow consist in coloring connections based on # a colormap # Coloring method color_by = 'strength' # Because we don't want to plot every connections, we only keep connections # above .7 select = edges > .7 # Define the connectivity object c_default = ConnectObj('default', nodes, edges, select=select, line_width=2., cmap='Spectral_r', color_by=color_by) # Then, we define the sources s_obj = SourceObj('sources', nodes, color='#ab4642', radius_min=15.) sc.add_to_subplot(c_default, title='Color by connectivity strength') # And add connect, source and brain objects to the scene sc.add_to_subplot(s_obj) sc.add_to_subplot(BrainObj('B3'), use_this_cam=True) ############################################################################### # Color by number of connections per node ############################################################################### # The next coloring method consist in set a color according to the number of # connections per node. Here, we also illustrate that colors can also by # `dynamic` (i.e stronger connections are opaque and weak connections are more # translucent) # Coloring method color_by = 'count' # Weak connections -> alpha = .1 // strong connections -> alpha = 1.
* Load an MRI (nii.gz) file """ from visbrain.objects import VolumeObj, SceneObj from visbrain.io import download_file # Define the scene sc = SceneObj(size=(1000, 600)) ############################################################################### # MIP rendering ############################################################################### # MIP rendering with an opaque fire colormap v_obj_mip = VolumeObj('brodmann', method='mip', cmap='OpaqueFire') sc.add_to_subplot(v_obj_mip, row=0, col=0, title='MIP rendering', zoom=.7) ############################################################################### # Translucent rendering ############################################################################### # Translucent rendering with a translucent fire colormap v_obj_trans = VolumeObj('aal', method='translucent', cmap='TransFire') sc.add_to_subplot(v_obj_trans, row=0, col=1, title='Translucent rendering', zoom=.7) ############################################################################### # Additive rendering ############################################################################### # Additive rendering with a translucent grays colormap
mat = np.load(download_file('xyz_sample.npz', astype='example_data')) xyz, subjects = mat['xyz'], mat['subjects'] data = np.random.rand(xyz.shape[0]) ############################################################################### # Basic brain using MNI template ############################################################################### # By default, Visbrain include several MNI brain templates (B1, B3, B3, # inflated, white and shere). # Translucent inflated BrainObj with both hemispheres displayed b_obj_fs = BrainObj('inflated', translucent=True, hemisphere='both') # Add the brain to the scene. Note that `row_span` means that the plot will # occupy two rows (row 0 and 1) sc.add_to_subplot(b_obj_fs, row=0, col=0, row_span=2, title='Translucent inflated brain template', **KW) ############################################################################### # Select the left or the right hemisphere ############################################################################### # You can use the `hemisphere` input to select either the 'left', 'right' or # 'both' hemispheres. # Opaque left hemispehre of the white matter b_obj_lw = BrainObj('white', hemisphere='left', translucent=False) sc.add_to_subplot(b_obj_lw, row=0, col=1, rotate='right', title='Left hemisphere', **KW) ############################################################################### # Projection iEEG data on the surface of the brain ###############################################################################
roi_to_find1('brodmann') # Switch to Brodmann idx_ba6 = roi_to_find1.where_is('BA6') # Find only BA6 print(ref_brod.loc[idx_ba6]) roi_to_find1('aal') # Switch to AAL idx_sma = roi_to_find1.where_is(['Supp Motor Area', '(L)'], union=False) # ============================================================================= # BRAIN + BA6 # ============================================================================= print('\n-> Plot brodmann area 6') b_obj = BrainObj('B1') roi_brod = RoiObj('brodmann') idx_ba6 = roi_brod.where_is('BA6') roi_brod.select_roi(select=idx_ba6) roi_brod.get_labels(save_to_path=vb_path) # print available brodmann labels sc.add_to_subplot(roi_brod, row=0, col=0, title='Brodmann area 6') sc.add_to_subplot(b_obj, row=0, col=0, use_this_cam=True) # ============================================================================= # MULTIPLE ROI + UNIQUE COLORS # ============================================================================= print('\n-> Select and plot multiple ROI with random unique colors') roi_aal = RoiObj('aal') roi_aal.select_roi(select=[29, 30, 77, 78], unique_color=True, smooth=11) roi_aal.get_labels(save_to_path=vb_path) # save available AAL labels sc.add_to_subplot(roi_aal, row=0, col=1, title='Select and plot multiple ROI with unique colors') # =============================================================================
cmap='hot_r', vmin=0, vmax=1, clim=(0, 1)) b_obj_proj_rl.add_activation(texturerl, hemisphere='right', cmap='hot_r', vmin=0, vmax=1, clim=(0, 1), hide_under=0) cb_proj = ColorbarObj(b_obj_proj_rl, cblabel='Correlation', cmap='hot_r', vmin=0, vmax=1, **CBAR_STATE) sc2.add_to_subplot(b_obj_proj_ll, row=0, col=0, rotate='left') sc2.add_to_subplot(b_obj_proj_lr, row=0, col=1, rotate='right') sc2.add_to_subplot(b_obj_proj_rl, row=0, col=2, rotate='left') sc2.add_to_subplot(b_obj_proj_rr, row=0, col=3, rotate='right') sc2.add_to_subplot(cb_proj, row=0, col=4, width_max=100) sc2.preview()
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
) S_KW = dict(camera_state=CAM_STATE) # Create the scene sc = SceneObj(size=(1600, 1000)) CBAR_STATE = dict(cbtxtsz=12, txtsz=10., width=.5, cbtxtsh=3., rect=(1., -2., 1., 4.)) ############################################################################### # Basic source object ############################################################################### # The first example consist of only plotting the source, without any # modifications of the inputs # Create the source objects and add this object to the scene s_obj_basic = SourceObj('Basic', xyz) sc.add_to_subplot(s_obj_basic, row=0, col=0, title='Default configuration', **S_KW) ############################################################################### # Text, symbol and color control ############################################################################### # Now, we attach text to each source (bold and yellow) and use a gray squares # symbol # The color definition could either be uniform (e.g 'green', 'blue'...), a list # of colors or an array of RGB(A) colors # s_color = 'blue' # uniform definition s_color = ["#D72638"] * 100 + ["#3772FF"] * 100 + ["#008148"] * 200 + \ ["#C17D11"] * 183 # list definition # Define the source object and add this object to the scene s_obj_col = SourceObj('S2', xyz, text=text, text_size=4., text_color='yellow', text_bold=True, color=s_color, symbol='square')
with open(label_file, 'rb') as f: ar = pickle.load(f) names, xyz, colors = ar['ROI_names'], ar['ROI_coords'], ar[ 'ROI_colors'] # noqa ts = np.squeeze(np.load(inverse_file)) cen = np.array([k.mean(0) for k in xyz]) # Get the data of the left / right hemisphere : lh_data, rh_data = ts[::2, time_pts], ts[1::2, time_pts] clim = (ts[:, time_pts].min(), ts[:, time_pts].max()) roi_names = [k[0:-3] for k in np.array(names)[::2]] # Left hemisphere outside : b_obj_li = BrainObj('white', translucent=False, hemisphere='left') b_obj_li.parcellize(lh_file, select=roi_names, data=lh_data, cmap=cmap) sc.add_to_subplot(b_obj_li, rotate='left') # Left hemisphere inside : b_obj_lo = BrainObj('white', translucent=False, hemisphere='left') b_obj_lo.parcellize(lh_file, select=roi_names, data=lh_data, cmap=cmap) sc.add_to_subplot(b_obj_lo, col=1, rotate='right') # Right hemisphere outside : b_obj_ro = BrainObj('white', translucent=False, hemisphere='right') b_obj_ro.parcellize(rh_file, select=roi_names, data=rh_data, cmap=cmap) sc.add_to_subplot(b_obj_ro, row=1, rotate='right') # Right hemisphere inside : b_obj_ri = BrainObj('white', translucent=False, hemisphere='right') b_obj_ri.parcellize(rh_file, select=roi_names, data=rh_data, cmap=cmap) sc.add_to_subplot(b_obj_ri, row=1, col=1, rotate='left')
############################################################################### # Extract the mesh of an ROI ############################################################################### # Once you have the index of the ROI that you want to plot, use the # :class:`visbrain.objects.RoiObj.select_roi` method to extract the mesh (i.e # vertices and faces) of the ROI. Here, we illustrate this question with the # brodmann 6 ROI # Load the brodmann 6 atlas, get the index of BA6 and extract the mesh roi_brod = RoiObj('brodmann') idx_ba6 = roi_brod.where_is('BA6') roi_brod.select_roi(select=idx_ba6) # Define a brain object and add this brain and ROI objects to the scene b_obj = BrainObj('B1') sc.add_to_subplot(b_obj, row=0, col=0, use_this_cam=True, title='Brodmann area 6 mesh') sc.add_to_subplot(roi_brod, row=0, col=0) ############################################################################### # Set a unique color per ROI mesh ############################################################################### # If you need, you can set a unique color per plotted ROI mesh. Here, we plot # the left and right insula and thalamus and set a unique color to each # Load the AAL atlas roi_aal = RoiObj('aal') # Select indicies 29, 30, 77 and 78 (respectively insula left, right and # thalamus left and right) roi_aal.select_roi(select=[29, 30, 77, 78], unique_color=True, smooth=11) # Add the ROI to the scene sc.add_to_subplot(roi_aal, row=0, col=1, rotate='top', zoom=.4,
sc = SceneObj(bgcolor='white', size=(1600, 900)) ############################################################################### # Topoplot based on channel names ############################################################################### # First definition using channel names only # Define some EEG channels and set one data value per channel ch_names = ['C3', 'C4', 'Cz', 'Fz', 'Pz'] data_names = [10, 20, 30, 10, 10] # Create the topoplot and the associated colorbar t_obj = TopoObj('topo', data_names, channels=ch_names, **kw_top) cb_obj = ColorbarObj(t_obj, cblabel='Colorbar label', **kw_cbar) # Add both objects to the scene # Add the topoplot and the colorbar to the scene : sc.add_to_subplot(t_obj, row=0, col=0, title='Definition using channel names', title_color='black', width_max=400) sc.add_to_subplot(cb_obj, row=0, col=1, width_max=100) ############################################################################### # Topoplot based on channel (x, y) coordinates ############################################################################### # Second definition using channel (x, y) coordinates # Create the topoplot and the object : t_obj_1 = TopoObj('topo', data, channels=channels, xyz=xy, cmap='bwr', clim=(2., 3.), **kw_top) cb_obj_1 = ColorbarObj(t_obj_1, cblabel='Beta power', **kw_cbar) # Add the topoplot and the colorbar to the scene : sc.add_to_subplot(t_obj_1, row=0, col=2, title_color='black', width_max=400, title='Definition using channel coordinates') sc.add_to_subplot(cb_obj_1, row=0, col=3, width_max=100)