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 visu_graph(net_file, coords_file, labels_file, modality_type="fMRI", s_textcolor="black", c_colval={1: "orange"}): # coords coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000*coords coords = np.swapaxes(coords, 0, 1) # labels labels = [line.strip() for line in open(labels_file)] npLabels = np.array(labels) # net file node_corres, sparse_matrix = read_Pajek_corres_nodes_and_sparse_matrix( net_file) c_connect = np.array(sparse_matrix.todense()) c_connect[c_connect != 0] = 1 corres_coords = coords[node_corres, :] newLabels = npLabels[node_corres] # new to visbrain 0.3.7 s_obj = SourceObj('SourceObj1', corres_coords, text=newLabels, text_color="white", color='crimson', alpha=.5, edge_width=2., radius_min=2., radius_max=10.) """Create the connectivity object :""" c_obj = ConnectObj('ConnectObj1', corres_coords, c_connect, color_by='strength', custom_colors=c_colval) # ,antialias=True vb = Brain(source_obj=s_obj, connect_obj=c_obj) return vb
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 visu_graph_signif(indexed_mat_file, coords_file, labels_file, c_colval = {4:"darkred",3:"red",2:"orange",1:"yellow",-1:"cyan",-2:"cornflowerblue",-3:"blue",-4:"navy"}): ########### coords #coord_file = os.path.abspath("data/MEG/label_coords.txt") coords = np.loadtxt(coords_file) #print("coords: ", end=' ') print("coords: ") print(coords) ########## labels labels = [line.strip() for line in open(labels_file)] npLabels = np.array(labels) #print(npLabels) ########## net file ########## indexed_mat file if indexed_mat_file.endswith(".csv"): indexed_mat = pd.read_csv(indexed_mat_file,index_col = 0).values elif indexed_mat_file.endswith(".npy"): indexed_mat = np.load(indexed_mat_file) indexed_mat = np.load(indexed_mat_file) print (indexed_mat[indexed_mat != 0]) for i in range(indexed_mat.shape[0]): if np.sum(indexed_mat[i,:] == 0) == indexed_mat.shape[1]: npLabels[i] = "" c_connect = np.ma.masked_array(indexed_mat, mask = indexed_mat == 0) #################### new to visbrain 0.3.7 from visbrain.objects import SourceObj, ConnectObj s_obj = SourceObj('SourceObj1', coords, text=npLabels, text_color="white", color='crimson', alpha=.5, edge_width=2., radius_min=2., radius_max=10.) """Create the connectivity object : """ c_obj = ConnectObj('ConnectObj1', coords, c_connect, color_by='strength', custom_colors = c_colval) # , antialias=True vb = Brain(source_obj=s_obj, connect_obj=c_obj) vb.show()
def visu_graph_signif(indexed_mat_file, coords_file, labels_file, c_colval=c_colval_signif): # coords coords = np.loadtxt(coords_file) # labels labels = [line.strip() for line in open(labels_file)] npLabels = np.array(labels) # print(npLabels) # net file # indexed_mat file if indexed_mat_file.endswith(".csv"): indexed_mat = pd.read_csv(indexed_mat_file, index_col=0).values elif indexed_mat_file.endswith(".npy"): indexed_mat = np.load(indexed_mat_file) indexed_mat = np.load(indexed_mat_file) print(indexed_mat[indexed_mat != 0]) for i in range(indexed_mat.shape[0]): if np.sum(indexed_mat[i, :] == 0) == indexed_mat.shape[1]: npLabels[i] = "" c_connect = np.ma.masked_array(indexed_mat, mask=indexed_mat == 0) # new to visbrain 0.3.7 s_obj = SourceObj('SourceObj1', coords, text=npLabels, text_color="white", color='crimson', alpha=.5, edge_width=2., radius_min=2., radius_max=10.) """Create the connectivity object :""" c_obj = ConnectObj('ConnectObj1', coords, c_connect, color_by='strength', custom_colors=c_colval) # , antialias=True vb = Brain(source_obj=s_obj, connect_obj=c_obj) vb.show()
def test_update_cbar_from_obj(self): """Test function update_cbar_from_obj.""" xyz = np.random.rand(10, 3) edges = np.random.rand(10, 10) s_obj = SourceObj('S1', xyz) b_obj = BrainObj('B1') c_obj = ConnectObj('C1', xyz, edges) im_obj = ImageObj('IM1', np.random.rand(10, 10)) ColorbarObj(s_obj) ColorbarObj(c_obj) ColorbarObj(b_obj) ColorbarObj(im_obj)
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
# data15 = b15.get_data().values.ravel() # xyz15 = b15.locs.values template_brain = 'B3' sc = SceneObj(bgcolor='white', size=(1000, 1000)) CBAR_STATE = dict(cbtxtsz=12, clim=[0, 15], txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) KW = dict(title_size=14., zoom=1) s_obj_1 = SourceObj('iEEG', xyz1, data=data1, cmap=cmap) s_obj_1.color_sources(data=data1) s_obj_2 = SourceObj('iEEG', xyz2, data=data2, cmap=cmap) s_obj_2.color_sources(data=data2) s_obj_3 = SourceObj('iEEG', xyz3, data=data3, cmap=cmap) s_obj_3.color_sources(data=data3) s_obj_4 = SourceObj('iEEG', xyz4, data=data4, cmap=cmap) s_obj_4.color_sources(data=data4) s_obj_5 = SourceObj('iEEG', xyz5, data=data5, cmap=cmap) s_obj_5.color_sources(data=data5) s_obj_6 = SourceObj('iEEG', xyz6, data=data6, cmap=cmap) s_obj_6.color_sources(data=data6) s_obj_7 = SourceObj('iEEG', xyz7, data=data7, cmap=cmap) s_obj_7.color_sources(data=data7) s_obj_8 = SourceObj('iEEG', xyz8, data=data8, cmap=cmap) s_obj_8.color_sources(data=data8)
# 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
""" import numpy as np from visbrain import Brain from visbrain.objects import Picture3DObj, SourceObj from visbrain.io import download_file kwargs = {} # Load the xyz coordinates and corresponding subject name : s_xyz = np.load(download_file('xyz_sample.npz'))['xyz'] s_xyz = s_xyz[4::10, ...] n_sources = s_xyz.shape[0] """Define a source object """ s_obj = SourceObj('MySources', s_xyz, symbol='disc', color='green') """Define picture data """ sf = 1024. n = 50 x, y = np.ogrid[0:n / 2, 0:n / 2] x, y = np.append(x, np.flip(x, 0)), np.append(y, np.flip(y, 1)) time = (x.reshape(-1, 1) + y.reshape(1, -1)) / sf time = np.tile(time[np.newaxis, ...], (n_sources, 1, 1)) coef = s_xyz[:, 0].reshape(-1, 1, 1) / 2. data = np.sinc(coef * 2 * np.pi * 1. * time) data += .2 * np.random.rand(*data.shape) """If you want to remove some pictures, define a pic_select array of boolean values and specify if those pictures has to be hide or displayed : """ pic_select = np.ones((n_sources, ), dtype=bool)
############################################################################### # Project source's data onto the surface of ROI mesh ############################################################################### # Once you've extract the mesh of the ROI, you can explicitly specify to the # :class:`visbrain.object.SourceObj.project_sources` to project the activity # onto the surface of the ROI. Here, we extract the mesh of the default mode # network (DMN) and project source's activity on it # Define the roi object using the MIST at resolution 7 roi_dmn = RoiObj('mist_7') roi_dmn.get_labels(save_to_path=vb_path) # save the labels dmn_idx = roi_dmn.where_is('Default mode network') roi_dmn.select_roi(select=dmn_idx) # Define the source object and project source's data on the DMN s_dmn = SourceObj('SecondSources', xyz, data=data) s_dmn.project_sources(roi_dmn, cmap='plasma', clim=(-1., 1.), vmin=-.5, vmax=.7, under='gray', over='red') # Get the colorbar of the projection cb_dmn = ColorbarObj(s_dmn, cblabel='Source activity', **CBAR_STATE) # Add those objects to the scene sc.add_to_subplot(roi_dmn, row=0, col=2, rotate='top', zoom=.4,
############################################################################### # 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 ############################################################################### # Previous subplots are using the brain object. But every 3D objects in # Visbrain can also be animated. We illustrate this with a source object # Define connectivity links and sources c_obj_1 = ConnectObj('c1', xyz,
def visu_graph_modules(net_file, lol_file, coords_file, labels_file=0, inter_modules=True, modality_type="", s_textcolor="white", c_colval=c_colval_modules, umin=0, umax=50, x_offset=0, y_offset=0, z_offset=0): # coords coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000 * coords temp = np.copy(coords) coords[:, 1] = coords[:, 0] coords[:, 0] = temp[:, 1] coords[:, 2] += z_offset coords[:, 1] += y_offset coords[:, 0] += x_offset # labels if labels_file: labels = [line.strip() for line in open(labels_file)] np_labels = np.array(labels) # net file node_corres, sparse_matrix = read_Pajek_corres_nodes_and_sparse_matrix( net_file) # lol file community_vect = read_lol_file(lol_file) c_connect = np.array(compute_modular_matrix(sparse_matrix, community_vect), dtype='float64') c_connect = np.ma.masked_array(c_connect, mask=True) c_connect.mask[c_connect > -1.0] = False corres_coords = coords[node_corres, :] if inter_modules: c_colval[-1] = "grey" """Create the connectivity object :""" c_obj = ConnectObj('ConnectObj1', corres_coords, c_connect, color_by='strength', custom_colors=c_colval) # source object colors_nodes = [] for i in community_vect: if i in c_colval.keys(): colors_nodes.append(c_colval[i]) else: colors_nodes.append("black") if labels_file: corres_labels = np_labels[node_corres] s_obj = SourceObj('SourceObj1', corres_coords, text=corres_labels, text_color=s_textcolor, text_size=10, color=colors_nodes, alpha=.5, edge_width=2., radius_min=10., radius_max=10.) else: s_obj = SourceObj('SourceObj1', corres_coords, text_color=s_textcolor, text_size=10, color=colors_nodes, alpha=.5, edge_width=2., radius_min=10., radius_max=10.) return c_obj, s_obj
def visu_graph_kcore(net_file, coords_file, labels_file, node_size_file, modality_type="fMRI", s_textcolor="black", c_colval={1: "orange"}): # coords coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000 * coords coords = np.swapaxes(coords, 0, 1) # labels npLabels = np.array([line.strip() for line in open(labels_file)]) # net file c_connect = np.transpose(np.load(net_file)) c_connect_mask = np.ma.masked_array(c_connect, mask=True) c_connect_mask.mask[c_connect == 1] = False node_size = np.load(node_size_file) assert node_size.shape[0] == coords.shape[0], \ "Uncompatible size {} for node_size vect {}".format( node_size.shape[0], coords.shape[0]) # kcore in_kcore = node_size == np.max(node_size) kcore_mat = c_connect[in_kcore, :][:, in_kcore] kcore_mat_mask = np.ma.masked_array(kcore_mat, mask=True) kcore_mat_mask.mask[kcore_mat == 1] = False kcore_coords = coords[in_kcore, :] kcore_node_size = node_size[in_kcore] kcore_labels = npLabels[in_kcore] # new to visbrain 0.3.7 s_obj = SourceObj('SourceObj1', coords, text=npLabels, data=node_size, text_color=s_textcolor, color='blue', alpha=.5, edge_width=2., radius_min=1., radius_max=1.) """Create the connectivity object :""" c_obj = ConnectObj(name='ConnectObj1', nodes=coords, custom_colors={None: 'blue'}, edges=c_connect_mask, color_by='count') # Kcore graph s_obj2 = SourceObj('SourceKcore', kcore_coords, text=kcore_labels, data=kcore_node_size, text_color=s_textcolor, color='crimson', alpha=.5, edge_width=2., radius_min=20., radius_max=20.) """Create the connectivity object :""" if kcore_mat_mask.shape[0] != 1: c_obj2 = ConnectObj(name='ConnectKcore', nodes=kcore_coords, custom_colors={None: 'crimson'}, edges=kcore_mat_mask, color_by='count') else: c_obj2 = 0 return c_obj, s_obj, c_obj2, s_obj2
psds, freqs = arch['psds'], arch['freqs'] xyz = np.genfromtxt(channel_coo_file, dtype=float) freq_bands = np.asarray(freq_bands) 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)
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) s_obj.color_sources(data=data, cmap='Spectral_r') sc.add_to_subplot(s_obj, row=1, col=1, title='Sources') sc.add_to_subplot(BrainObj('B3'), use_this_cam=True, row=1, col=1) ############################################################################### # 3D Time-series ############################################################################### ts, _ = generate_eeg(n_pts=100, n_channels=xyz.shape[0]) select = np.zeros((xyz.shape[0],), dtype=bool) select[slice(0, 100, 10)] = True ts_obj = TimeSeries3DObj('TS3D', ts, xyz, select=select, color='pink', ts_amp=24.) sc.add_to_subplot(ts_obj, row=0, col=2, title='3D time series') sc.add_to_subplot(BrainObj('B2'), use_this_cam=True, row=0, col=2)
# Download intrcranial xyz : mat = np.load(download_file('xyz_sample.npz')) xyz_full = mat['xyz'] mat.close() xyz_1, xyz_2 = xyz_full[20:30, :], xyz_full[10:20, :] # ---------------- Sources ---------------- # Define some random sources : s_data = 100 * np.random.rand(10) s_color = ['blue'] * 3 + ['white'] * 3 + ['red'] * 4 s_mask = np.array([True] + [False] * 9) s_obj1 = SourceObj('S1', xyz_1, data=s_data, color=s_color, mask=s_mask) s_obj2 = SourceObj('S2', xyz_2, data=2 * s_data, color=s_color, mask=s_mask) # ---------------- Connectivity ---------------- # Connectivity array : c_connect = np.random.randint(-10, 10, (10, 10)).astype(float) c_connect[np.tril_indices_from(c_connect)] = 0 c_connect = np.ma.masked_array(c_connect, mask=True) nz = np.where((c_connect > -5) & (c_connect < 5)) c_connect.mask[nz] = False c_connect = c_connect c_obj = ConnectObj('C1', xyz_1, c_connect) c_obj2 = ConnectObj('C2', xyz_2, c_connect)
ylabel='ylab', name='Can1', add_cbar=True) # Scene : sc_obj_2d_1 = SceneObj(bgcolor=(0., 0., 0.)) sc_obj_3d_1 = SceneObj(bgcolor='#ab4642') sc_obj_3d_2 = SceneObj(bgcolor='olive') # Objects : n_sources = 10 s_1 = 20. * np.random.rand(n_sources, 3) s_2 = 20. * np.random.rand(n_sources, 3) b_obj_1 = BrainObj('B1') b_obj_2 = BrainObj('B2') s_obj_1 = SourceObj('S1', s_1) s_obj_2 = SourceObj('S1', s_2) c_obj_1 = ConnectObj('C1', s_1, np.random.rand(n_sources, n_sources)) c_obj_2 = ConnectObj('C2', s_2, np.random.rand(n_sources, n_sources)) im_obj_1 = ImageObj('IM1', np.random.rand(10, 20)) im_obj_2 = ImageObj('IM2', np.random.rand(10, 20)) im_obj_3 = ImageObj('IM3', np.random.rand(10, 20)) class TestVisbrainCanvas(_TestVisbrain): """Test the definition of a visbrain canvas.""" OBJ = vb_can def test_definition(self): """Test function definition."""
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 ============================================================================= """) s_obj = SourceObj('FirstSources', xyz, data=data) s_obj.color_sources(data=data, cmap='Spectral_r') sc.add_to_subplot(s_obj, row=1, col=1, title='Sources') sc.add_to_subplot(BrainObj('B3'), use_this_cam=True, row=1, col=1) print(""" # ============================================================================= # 3D Time-series # ============================================================================= """) ts, _ = generate_eeg(n_pts=100, n_channels=xyz.shape[0]) select = np.zeros((xyz.shape[0],), dtype=bool) select[slice(0, 100, 10)] = True ts_obj = TimeSeries3DObj('TS3D', ts, xyz, select=select, color='pink', ts_amp=24.)
#subjects = subjects * 3000 #print(xyz) subjects = subjects[0] print(xyz.shape) print(subjects.shape) #N = xyz.shape[0] # Number of electrodes N = 583 # Now, create some random data between [-50,50] data = np.random.uniform(-50, 50, len(subjects)) """Create the source object : """ s_obj = SourceObj('SourceObj1', xyz, data, color='crimson', alpha=.5, edge_width=2., radius_min=2., radius_max=10.) """ To connect sources between them, we create a (N, N) array. This array should be either upper or lower triangular to avoid redondant connections. """ connect = 1000 * np.random.rand(N, N) # Random array of connections connect[np.tril_indices_from(connect)] = 0 # Set to zero inferior triangle """ Because all connections are not necessary interesting, it's possible to select only certain either using a select array composed with ones and zeros, or by masking the connection matrix. We are giong to search vealues between umin and umax to limit the number of connections :
# With text : c_obj = ConnectObj('c', xyz, connect, color_by='count', clim=clim, dynamic=(0., 1.), dynamic_order=3, 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,
# them to get a path traveling across boundary vertices # The output is a list of potentially more than one boudaries # depending on the topology of the input mesh. # Here the mesh has a single boundary open_mesh_boundary = stop.mesh_boundary(open_mesh) print(open_mesh_boundary) ############################################################################### # show the result # WARNING : BrainObj should be added first before visb_sc = splt.visbrain_plot(mesh=open_mesh, caption='open mesh') # create points with vispy for bound in open_mesh_boundary: points = open_mesh.vertices[bound] s_rad = SourceObj('rad', points, color='red', symbol='square', radius_min=10) visb_sc.add_to_subplot(s_rad) lines = Line(pos=open_mesh.vertices[bound], width=10, color='b') # wrap the vispy object using visbrain l_obj = VispyObj('line', lines) visb_sc.add_to_subplot(l_obj) visb_sc.preview() ############################################################################### # here is how to get the vertices that define the boundary of # a texture on a mesh # Let us first load example data mesh = sio.load_mesh('../examples/data/example_mesh.gii') # rotate the mesh for better visualization transfo_flip = np.array([[-1, 0, 0, 0],[0, 1, 0, 0],[0, 0, -1, 0], [0, 0, 0, 1]]) mesh.apply_transform(transfo_flip)
data6 = b6.get_data().values.ravel() xyz6 = b6.locs.values template_brain = 'B3' sc = SceneObj(bgcolor='white', size=(1000, 1000)) CBAR_STATE = dict(cbtxtsz=12, clim=[0, 7], txtsz=10., width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) KW = dict(title_size=14., zoom=1) s_obj_1 = SourceObj('iEEG', xyz1, data=data1, cmap=cmap) s_obj_1.color_sources(data=data1) s_obj_2 = SourceObj('iEEG', xyz2, data=data2, cmap=cmap) s_obj_2.color_sources(data=data2) s_obj_3 = SourceObj('iEEG', xyz3, data=data3, cmap=cmap) s_obj_3.color_sources(data=data3) s_obj_4 = SourceObj('iEEG', xyz4, data=data4, cmap=cmap) s_obj_4.color_sources(data=data4) s_obj_5 = SourceObj('iEEG', xyz5, data=data5, cmap=cmap) s_obj_5.color_sources(data=data5) s_obj_6 = SourceObj('iEEG', xyz6, data=data6, cmap=cmap) s_obj_6.color_sources(data=data6) #s_obj_all = s_obj_1 + s_obj_2 + s_obj_3 + s_obj_4+ s_obj_5 + s_obj_6 + s_obj_7 s_obj_all = s_obj_6 + s_obj_5 + s_obj_4 + s_obj_3 + s_obj_2 + s_obj_1
def visu_graph(net_file, coords_file, labels_file, node_size_file=0, modality_type="fMRI", s_textcolor="black", c_colval={1: "orange"}): # coords coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000 * coords coords = np.swapaxes(coords, 0, 1) # labels labels = [line.strip() for line in open(labels_file)] npLabels = np.array(labels) # net file path, base, ext = split_f(net_file) print(ext) if ext == ".net": node_corres, sparse_matrix = read_Pajek_corres_nodes_and_sparse_matrix( net_file) c_connect = np.array(sparse_matrix.todense()) c_connect[c_connect != 0] = 1 corres_coords = coords[node_corres, :] newLabels = npLabels[node_corres] elif ext == ".npy": c_connect = np.transpose(np.load(net_file)) print(c_connect) c_connect_mask = np.ma.masked_array(c_connect, mask=True) c_connect_mask.mask[c_connect == 1] = False print(c_connect_mask) corres_coords = coords newLabels = npLabels print(c_connect.shape, corres_coords.shape, newLabels.shape) if node_size_file: node_size = np.load(node_size_file) assert node_size.shape[0] == corres_coords.shape[0], \ "Uncompatible size {} for node_size vect {}".format( node_size.shape[0], corres_coords.shape[0]) else: node_size = np.ones((corres_coords.shape[0])) print(node_size) # new to visbrain 0.3.7 s_obj = SourceObj('SourceObj1', corres_coords, text=newLabels, data=node_size, text_color=s_textcolor, color='crimson', alpha=.5, edge_width=2., radius_min=1., radius_max=20.) """Create the connectivity object :""" c_obj = ConnectObj(name='ConnectObj1', nodes=corres_coords, edges=c_connect_mask, color_by='count') return c_obj, s_obj
GII_FILE='lh.bert.inflated.gii', GII_OVERLAY='lh.bert.thickness.gii', OBJ_FILE='brain.obj') # BRAIN : b_obj = BrainObj('B1') n_vertices, n_faces = 100, 50 vertices_x3 = 20. * np.random.rand(n_vertices, 3, 3) vertices = 20. * np.random.rand(n_vertices, 3) normals = (vertices >= 0).astype(float) faces = np.random.randint(0, n_vertices, (n_faces, 3)) # SOURCES : xyz = np.random.uniform(-20, 20, (50, 3)) mask = xyz[:, 0] > 10 s_obj = SourceObj('xyz', xyz, mask=mask) class TestBrainObj(_TestObjects): """Test BrainObj.""" OBJ = b_obj def test_rotation(self): """Test function rotation.""" # Test fixed rotations : f_rot = [ 'sagittal_0', 'left', 'sagittal_1', 'right', 'coronal_0', 'front', 'coronal_1', 'back', 'axial_0', 'top', 'axial_1', 'bottom' ] for k in f_rot:
def visu_graph_modules_roles(net_file, lol_file, roles_file, coords_file, inter_modules=True, modality_type="", s_textcolor="white", c_colval=c_colval_modules, umin=0, umax=50, x_offset=0, y_offset=0, z_offset=0, default_size=10, hub_to_non_hub=3): # coords coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000 * coords temp = np.copy(coords) coords[:, 1] = coords[:, 0] coords[:, 0] = temp[:, 1] coords[:, 2] += z_offset coords[:, 1] += y_offset coords[:, 0] += x_offset # net file node_corres, sparse_matrix = read_Pajek_corres_nodes_and_sparse_matrix( net_file) corres_coords = coords[node_corres, :] corres_coords = coords[node_corres, :] # lol file community_vect = read_lol_file(lol_file) max_col = np.array([val for val in c_colval.keys()]).max() community_vect[community_vect > max_col] = max_col """Create the connectivity object :""" c_connect = np.array(compute_modular_matrix(sparse_matrix, community_vect), dtype='float64') c_connect = np.ma.masked_array(c_connect, mask=True) c_connect.mask[-1.0 <= c_connect] = False if inter_modules: c_colval[-1] = "grey" else: c_connect.mask[-1.0 == c_connect] = True c_obj = ConnectObj('ConnectObj1', corres_coords, c_connect, color_by='strength', custom_colors=c_colval) """Create the source object :""" node_roles = np.array(np.loadtxt(roles_file), dtype='int64') # prov_hubs prov_hubs = (node_roles[:, 0] == 2) & (node_roles[:, 1] == 1) coords_prov_hubs = corres_coords[prov_hubs] colors_prov_hubs = [c_colval[i] for i in community_vect[prov_hubs]] # prov_no_hubs prov_no_hubs = (node_roles[:, 0] == 1) & (node_roles[:, 1] == 1) coords_prov_no_hubs = corres_coords[prov_no_hubs] colors_prov_no_hubs = [c_colval[i] for i in community_vect[prov_no_hubs]] # connec_hubs connec_hubs = (node_roles[:, 0] == 2) & (node_roles[:, 1] == 2) coords_connec_hubs = corres_coords[connec_hubs] colors_connec_hubs = [c_colval[i] for i in community_vect[connec_hubs]] # connec_no_hubs connec_no_hubs = (node_roles[:, 0] == 1) & (node_roles[:, 1] == 2) coords_connec_no_hubs = corres_coords[connec_no_hubs] colors_connec_no_hubs = [ c_colval[i] for i in community_vect[connec_no_hubs] ] list_sources = [] if len(coords_prov_no_hubs != 0): s_obj1 = SourceObj('prov_no_hubs', coords_prov_no_hubs, color=colors_prov_no_hubs, alpha=.5, edge_width=2., radius_min=default_size, radius_max=default_size) list_sources.append(s_obj1) if len(coords_connec_no_hubs != 0): s_obj2 = SourceObj('connec_no_hubs', coords_connec_no_hubs, color=colors_connec_no_hubs, alpha=.5, edge_width=2., radius_min=default_size, radius_max=default_size, symbol='square') list_sources.append(s_obj2) if len(coords_prov_hubs != 0): s_obj3 = SourceObj('prov_hubs', coords_prov_hubs, color=colors_prov_hubs, alpha=.5, edge_width=2., radius_min=default_size * hub_to_non_hub, radius_max=default_size * hub_to_non_hub) list_sources.append(s_obj3) if len(coords_connec_hubs != 0): s_obj4 = SourceObj('connec_hubs', coords_connec_hubs, color=colors_connec_hubs, alpha=.5, edge_width=2., radius_min=default_size * hub_to_non_hub, radius_max=default_size * hub_to_non_hub, symbol='square') list_sources.append(s_obj4) return c_obj, list_sources
# 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 ############################################################################### # As explain above, we define a source object and project the source's activity # on the surface of the brain # First, define a brain object used for the projection b_obj_proj = BrainObj('B3', hemisphere='both', translucent=False) # Define the source object s_obj = SourceObj('iEEG', xyz, data=data, cmap='inferno') # Just for fun, color sources according to the data :) s_obj.color_sources(data=data) # Project source's activity s_obj.project_sources(b_obj_proj, cmap='plasma') # Finally, add the source and brain objects to the subplot sc.add_to_subplot(s_obj, row=0, col=2, title='Project iEEG data', **KW) sc.add_to_subplot(b_obj_proj, row=0, col=2, rotate='left', use_this_cam=True) # Finally, add the colorbar : cb_proj = ColorbarObj(s_obj, cblabel='Projection of niEEG data', **CBAR_STATE) sc.add_to_subplot(cb_proj, row=0, col=3, width_max=200) ############################################################################### # .. note:: # Here, we used s_obj.project_sources(b_obj) to project source's activity # on the surface. We could also have used to b_obj.project_sources(s_obj)
row=0, col=1, rotate='right', title='Left hemisphere', **KW) ############################################################################### # Projection iEEG data on the surface of the brain ############################################################################### # As explain above, we define a source object and project the source's activity # on the surface of the brain # First, define a brain object used for the projection b_obj_proj = BrainObj('B3', hemisphere='both', translucent=False) # Define the source object s_obj = SourceObj('iEEG', xyz, data=data, cmap='inferno') # Just for fun, color sources according to the data :) s_obj.color_sources(data=data) # Project source's activity s_obj.project_sources(b_obj_proj, cmap='plasma') # Finally, add the source and brain objects to the subplot sc.add_to_subplot(s_obj, row=0, col=2, title='Project iEEG data', **KW) sc.add_to_subplot(b_obj_proj, row=0, col=2, rotate='left', use_this_cam=True) # Finally, add the colorbar : cb_proj = ColorbarObj(s_obj, cblabel='Projection of niEEG data', **CBAR_STATE) sc.add_to_subplot(cb_proj, row=0, col=3, width_max=200) ############################################################################### # .. note:: # Here, we used s_obj.project_sources(b_obj) to project source's activity # on the surface. We could also have used to b_obj.project_sources(s_obj)
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 ############################################################################### # Previous subplots are using the brain object. But every 3D objects in # Visbrain can also be animated. We illustrate this with a source object # Define connectivity links and sources c_obj_1 = ConnectObj('c1', xyz, conn, select=conn_select, dynamic=(0., 1.), dynamic_orientation='center', dynamic_order=3, cmap='bwr', antialias=True) s_obj_2 = SourceObj('s2', xyz, data=data, radius_min=5., radius_max=20) s_obj_2.color_sources(data=data, cmap='inferno') # Animate sources s_obj_2.animate() # Add objects to the scene sc.add_to_subplot(c_obj_1, col=1, title='Animate a source object') sc.add_to_subplot(s_obj_2, col=1, rotate='front', use_this_cam=True, zoom=.7) ############################################################################### # Configure the animation rate ############################################################################### # Here, we configure animations so that there's a 60° rotation update every # second
s_obj_mask = SourceObj('S3', xyz, mask=mask, mask_color=mask_color, color=s_color, data=rnd_data, radius_min=radius_min, radius_max=radius_max) sc.add_to_subplot(s_obj_mask, row=0, col=3, title='Masked sources between [-20., 20.]\nare orange', **S_KW) ############################################################################### # Get anatomical informations of sources ############################################################################### # The region of interest object (RoiObj) is basically a volume where each voxel # is known to be part of an anatomical region. Hence, you can define the RoiObj # and use it to get the anatomical informations of each source # First, create a basic source object s_obj_ba = SourceObj('S4', xyz) # Then, we define a region of interest object (RoiObj). We use brodmann areas # but you should take a look to the complete tutorial on ROIs because visbrain # povides several templates (Brodmann, AAL, Talairach and MIST) roi_obj = RoiObj('brodmann') # If you want to see labels associated with the brodmann areas, uncomment the # following line # print(roi_obj.get_labels()) # Now, analyse sources using the RoiObj. The argument returned by the # `SourceObj.analyse_sources` method is a Pandas dataframe df_brod = s_obj_ba.analyse_sources(roi_obj=roi_obj) # The dataframe contains a column `brodmann` which is the name of the # associated brodmann area. Hence, we use it to color sources according to the # name of brodmann area s_obj_ba.color_sources(analysis=df_brod, color_by='brodmann') # Finally, add the object to the scene
finally right hemisphere back : """ s_xyz_l = s_xyz[s_xyz[:, 0] <= 0, :] s_xyz_rb = s_xyz[np.logical_and(s_xyz[:, 0] > 0, s_xyz[:, 1] <= 0), :] s_xyz_rf = s_xyz[np.logical_and(s_xyz[:, 0] > 0, s_xyz[:, 1] > 0), :] data_l = np.random.uniform(-10, 10, s_xyz_l.shape[0]) ############################################################################### # SOURCES ############################################################################### """Create a first source object with uniform red square markers """ s_obj_l = SourceObj('S_left', s_xyz_l, data=data_l, color='red', edge_color='white', symbol='disc', edge_width=2., radius_min=10., radius_max=20., alpha=.4) """Color the sources according to data """ s_obj_l.color_sources(data=data_l, cmap='plasma') """Create a second source object. Then, we analyse where are located the sources using the AAL region of interest and used color according to gyrus """ s_obj_rb = SourceObj('S_right_back', s_xyz_rb, symbol='arrow', radius_min=20., edge_width=0., text_color='white', text_size=1., text_bold=True) """Analyse where the source are located using the Brodmann area (BA) atlas. This method returns a pandas.DataFrame """
kwargs['mask'] = mask kwargs['mask_color'] = 'gray' """It's also possible to add text to each source. Here, we show the name of the subject in yellow. To avoid a superposition between the text and sources sphere, we introduce an offset to the text using the s_textshift input """ kwargs['text'] = subjects # Name of the subject kwargs['text_color'] = "#f39c12" # Set to yellow the text color kwargs['text_size'] = 1.5 # Size of the text kwargs['text_translate'] = (1.5, 1.5, 0) kwargs['text_bold'] = True """Create the source object. If you want to previsualize the result without opening Brain, use s_obj.preview() """ s_obj = SourceObj('SourceExample', xyz, **kwargs) # s_obj.preview() """Color sources according to the data """ # s_obj.color_sources(data=kwargs['data'], cmap='viridis') """Colorbar properties """ cb_kw = dict( cblabel="Project source activity", cbtxtsz=3., border=False, ) """Define a brain object with the B3 template and project source's activity onto the surface """ b_obj = BrainObj('B3', **cb_kw)
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()
"""Test RoiObj.""" import numpy as np from visbrain.objects.tests._testing_objects import _TestVolumeObject from visbrain.objects import SourceObj, RoiObj from visbrain.io import (download_file, path_to_visbrain_data, read_nifti, clean_tmp) roi_obj = RoiObj('brodmann') roi_obj.select_roi([4, 6]) rnd = np.random.RandomState(0) xyz = 100. * rnd.rand(50, 3) xyz[:, 0] -= 50. xyz[:, 1] -= 50. s_obj = SourceObj('S1', xyz) download_file('MIST_ROI.zip', unzip=True) nifti_file = path_to_visbrain_data('MIST_ROI.nii.gz') csv_file = path_to_visbrain_data('MIST_ROI.csv') # Read the .csv file : arr = np.genfromtxt(csv_file, delimiter=';', dtype=str) # Get column names, labels and index : column_names = arr[0, :] arr = np.delete(arr, 0, 0) n_roi = arr.shape[0] roi_index = arr[:, 0].astype(int) roi_labels = arr[:, [1, 2]].astype(object) # Build the struct array : label = np.zeros(n_roi, dtype=[('label', object), ('name', object)]) label['label'] = roi_labels[:, 0] label['name'] = roi_labels[:, 1]
nii_bo_dir = '../../../data/niis/best_locs' fig_dir = '../../../paper/figs/source/best_locs' # Colorbar default arguments CBAR_STATE = dict(cbtxtsz=20, txtsz=20., txtcolor='white', width=.1, cbtxtsh=3., rect=(-.3, -2., 1., 4.)) KW = dict(title_size=14., zoom=2) template_brain = 'B3' bo = se.load(os.path.join(nii_bo_dir, 'best_90th.bo')) data1 = bo.get_data().values.ravel() xyz1 = bo.locs.values s_obj_1 = SourceObj('iEEG', xyz1, data=data1, cmap=cmap) s_obj_1.color_sources(data=data1) sc = SceneObj(bgcolor='white', size=(1000, 500)) b_obj_proj_left = BrainObj(template_brain, hemisphere='left', translucent=False) b_obj_proj_left.project_sources(s_obj_1, clim=(0, 2), cmap='binary') sc.add_to_subplot(b_obj_proj_left, row=0, col=0, rotate='left', use_this_cam=True) b_obj_proj_left = BrainObj(template_brain, hemisphere='left', translucent=False) b_obj_proj_left.project_sources(s_obj_1, clim=(0, 2), cmap='binary') sc.add_to_subplot(b_obj_proj_left, row=0, col=1, rotate='right', use_this_cam=True) b_obj_proj_right = BrainObj(template_brain, hemisphere='right', translucent=False) b_obj_proj_right.project_sources(s_obj_1, clim=(0, 2), cmap='binary')
############################################################################### # Project source's data onto the surface of ROI mesh ############################################################################### # Once you've extract the mesh of the ROI, you can explicitly specify to the # :class:`visbrain.object.SourceObj.project_sources` to project the activity # onto the surface of the ROI. Here, we extract the mesh of the default mode # network (DMN) and project source's activity on it # Define the roi object using the MIST at resolution 7 roi_dmn = RoiObj('mist_7') roi_dmn.get_labels(save_to_path=vb_path) # save the labels dmn_idx = roi_dmn.where_is('Default mode network') roi_dmn.select_roi(select=dmn_idx) # Define the source object and project source's data on the DMN s_dmn = SourceObj('SecondSources', xyz, data=data) s_dmn.project_sources(roi_dmn, cmap='plasma', clim=(-1., 1.), vmin=-.5, vmax=.7, under='gray', over='red') # Get the colorbar of the projection cb_dmn = ColorbarObj(s_dmn, cblabel='Source activity', **CBAR_STATE) # Add those objects to the scene sc.add_to_subplot(roi_dmn, row=0, col=2, rotate='top', zoom=.4, title="Project source's activity onto the DMN") sc.add_to_subplot(cb_dmn, row=0, col=3, width_max=200) ############################################################################### # Get anatomical informations of sources ############################################################################### # If you defined sources (like intracranial recording sites, MEG source # reconstruction...) you can use the SourceObj to defined those sources and
def create_graph_picture(filename, xyz, hemisphere, rotation): ''' data is a .mat file containing the location and the 3D tensor containing N number of M*M matrices. Output path is where we will be saving the stuff hemisphere is 'left' 'right' or 'both' rotation is 'left', 'right', 'top', 'bottom' ''' num_electrodes = xyz.shape[0] # Number of electrodes # Get the connection matrix connect = 1 * np.random.rand(num_electrodes, num_electrodes) data = np.mean(connect, axis=1) # need a upper triangular matrix (fine for wPLI since we have symmetry) connect[np.tril_indices_from(connect)] = 0 # Set to zero inferior triangle small_weight_threshold = 0.001 large_weight_threshold = 0.999 # 2 - Using masking (True: hide, 1: display): connect = np.ma.masked_array(connect, mask=True) # This will show (set to hide = False) only the large and small connection connect.mask[np.where((connect >= large_weight_threshold) | (connect <= small_weight_threshold))] = False s_obj = SourceObj('SourceObj1', xyz, data, color='whitesmoke', alpha=.5, edge_width=2., radius_min=2., radius_max=30.) c_obj = ConnectObj('ConnectObj1', xyz, connect, color_by='strength', cmap='Greys', vmin=small_weight_threshold, vmax=large_weight_threshold, under='blue', over='red', antialias=True) CAM_STATE = dict( azimuth=0, elevation=90, ) 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)) sc.add_to_subplot(BrainObj('B1', hemisphere=hemisphere), row=0, col=0, rotate=rotation) sc.add_to_subplot(c_obj, row=0, col=0, rotate=rotation) sc.add_to_subplot(s_obj, row=0, col=0, rotate=rotation) sc.screenshot(filename, print_size=(10, 20), dpi=100)