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(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 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 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 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()
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) # ---------------- Time-series ---------------- ts_data = 100. * np.random.rand(10, 100) ts_select = np.ones((10,), dtype=bool) ts_select[[3, 4, 7]] = False ts_obj1 = TimeSeries3DObj('TS1', ts_data, xyz_1, select=ts_select) ts_obj2 = TimeSeries3DObj('TS2', ts_data, xyz_2, select=ts_select) # ---------------- Pictures ---------------- pic_data = 100. * np.random.rand(10, 20, 17) p_obj1 = Picture3DObj('P1', pic_data, xyz_1) p_obj2 = Picture3DObj('P2', 2 * pic_data, xyz_2)
""") pic = np.random.rand(xyz.shape[0], 20, 20) pic_obj = Picture3DObj('PIC', pic, xyz, select=select, pic_width=21., pic_height=21., cmap='viridis') sc.add_to_subplot(pic_obj, row=1, col=2, title='3D pictures') sc.add_to_subplot(BrainObj('B2'), use_this_cam=True, row=1, col=2) print(""" # ============================================================================= # Connectivity # ============================================================================= """) arch = np.load(download_file('phase_sync_delta.npz')) nodes, edges = arch['nodes'], arch['edges'] c_count = ConnectObj('default', nodes, edges, select=edges > .7, color_by='count', antialias=True, line_width=2., dynamic=(.1, 1.)) s_obj_c = SourceObj('sources', nodes, color='#ab4642', radius_min=5.) sc.add_to_subplot(c_count, row=2, col=0, row_span=2, title='3D connectivity') sc.add_to_subplot(s_obj_c, row=2, col=0) sc.add_to_subplot(BrainObj('B3'), use_this_cam=True, row=2, col=0) print(""" ============================================================================= Cross-sections ============================================================================= """) cs_brod = CrossSecObj('brodmann', interpolation='nearest', coords=(70, 80, 90), cmap='viridis') cs_brod.localize_source((-10., -15., 20.))
""" umin, umax = 30, 31 # 1 - Using select (0: hide, 1: display): select = np.zeros_like(connect) select[(connect > umin) & (connect < umax)] = 1 # 2 - Using masking (True: hide, 1: display): connect = np.ma.masked_array(connect, mask=True) connect.mask[np.where((connect > umin) & (connect < umax))] = False print('1 and 2 equivalent :', np.array_equal(select, ~connect.mask + 0)) """Create the connectivity object : """ c_obj = ConnectObj('ConnectObj1', xyz, connect, color_by='strength', dynamic=(.1, 1.), cmap='gnuplot', vmin=umin + .2, vmax=umax - .1, under='red', over='green', clim=(umin, umax), antialias=True) """Finally, pass source and connectivity objects to Brain : """ vb = Brain(source_obj=s_obj, connect_obj=c_obj) vb.show()
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
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
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)
def visu_graph_modules(net_file, lol_file, coords_file, labels_file, inter_modules=True, modality_type="", s_textcolor="white", c_colval=c_colval_modules, umin=0, umax=50): # coords coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000 * coords # 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) # 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 # Colormap properties (for connectivity) : # c_cmap = 'inferno' # Matplotlib colormap corres_coords = coords[node_corres, :] newLabels = npLabels[node_corres] if inter_modules: c_colval[-1] = "grey" # new to visbrain 0.3.7 from visbrain.objects import SourceObj, ConnectObj s_obj = SourceObj('SourceObj1', corres_coords, text=newLabels, text_color=s_textcolor, 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_modules(net_file, lol_file, coords_file, labels_file,inter_modules = True, modality_type = "",s_textcolor="white", c_colval = {0:"red",1:"orange",2:"blue",3:"green",4:"yellow",5:"darksalmon"}): ########## coords #coord_file = os.path.abspath("data/MEG/label_coords.txt") coords = np.loadtxt(coords_file) if modality_type == "MEG": coords = 1000*coords print("coords: ", end=' ') print(coords) ########## labels #label_file = os.path.abspath("data/MEG/label_names.txt") labels = [line.strip() for line in open(labels_file)] npLabels = np.array(labels) print(npLabels) ########## net file node_corres,sparse_matrix = read_Pajek_corres_nodes_and_sparse_matrix(net_file) print(sparse_matrix) print(node_corres) print(node_corres.shape) ############# lol file community_vect = read_lol_file(lol_file) print(community_vect) c_connect = np.array(compute_modular_network(sparse_matrix,community_vect),dtype = 'float64') print(c_connect.shape) #data = np.load('RealDataExample.npz') #s_data = data['beta'] #s_xyz = data['xyz'] umin = 0.0 umax = 50.0 c_connect = np.ma.masked_array(c_connect, mask=True) c_connect.mask[c_connect > -1.0] = False print(c_connect) # Colormap properties (for connectivity) : c_cmap = 'inferno' # Matplotlib colormap corres_coords = coords[node_corres,:] newLabels = npLabels[node_corres] #c_colval = {-1:"grey",0:"red",1:"orange",2:"blue",3:"green",4:"yellow",5:"purple"} if inter_modules: c_colval[-1] = "grey" #vb = Brain(s_xyz=corres_coords, s_text=newLabels, s_textsize = 2,s_textcolor=s_textcolor, c_map=c_cmap, c_connect = c_connect, c_colval = c_colval) #vb.show() #################### new to visbrain 0.3.7 from visbrain.objects import SourceObj, ConnectObj s_obj = SourceObj('SourceObj1', corres_coords, text=newLabels, text_color=s_textcolor, color='crimson', alpha=.5, edge_width=2., radius_min=2., radius_max=10.) #umin, umax = 30, 31 ## 1 - Using select (0: hide, 1: display): #select = np.zeros_like(connect) #select[(connect > umin) & (connect < umax)] = 1 ## 2 - Using masking (True: hide, 1: display): #connect = np.ma.masked_array(connect, mask=True) #connect.mask[np.where((connect > umin) & (connect < umax))] = False #print('1 and 2 equivalent :', np.array_equal(select, ~connect.mask + 0)) """Create the connectivity object : """ c_obj = ConnectObj('ConnectObj1', corres_coords, c_connect, color_by='strength', cmap=c_cmap) # , antialias=True vb = Brain(source_obj=s_obj, connect_obj=c_obj) #vb = Brain(s_xyz=corres_coords, s_text=newLabels, s_textsize = 2,s_textcolor=s_textcolor, c_map=c_cmap, c_connect = c_connect, c_colval = c_colval) vb.show()
connect = np.ma.masked_array(connect, False) # Hide lower triangle : connect.mask[np.tril_indices_from(connect.mask)] = True # Hide connexions that are not between min and max : connect.mask[np.logical_or(connect.data < min, connect.data > max)] = True return connect """Create two connectivity objects. """ connect_l = create_connect(s_xyz_l, -.5, .2) c_obl_l = ConnectObj('C_left', s_xyz_l, connect_l, color_by='strength', dynamic=(.1, 1.), cmap='viridis', vmin=0., vmax=.1, under='gray', over='red') connect_rb = create_connect(s_xyz_rb, -.5, .2) c_obj_rb = ConnectObj('C_right_back', s_xyz_rb, connect_rb, color_by='count', alpha=.7, cmap='plasma') """Finally, open _Brain_ with those list of objects """ vb = Brain(source_obj=[s_obj_l, s_obj_rb, s_obj_rf],
############################################################################### # 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
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.""" VisbrainCanvas() # without axis VisbrainCanvas(axis=True) # with axis
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()
# Here we need two threshold where above large is the big weight # and small weight we below is the small weights # 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 #print('1 and 2 equivalent :', np.array_equal(select, ~connect.mask + 0)) """Create the connectivity object : """ 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) """Finally, pass source and connectivity objects to Brain : """ vb = Brain(source_obj=s_obj, connect_obj=c_obj) vb.brain_control(alpha=0.1, hemisphere='both') rotation = 'axial_0' vb.rotate('axial_0') # top #vb.rotate('axial_1') #bottom #vb.rotate('sagittal_0') # left #vb.rotate('sagittal_1') # right #vb.rotate('coronal_0') # front
select1 = edges > 10 select11 = edges <20 select_1 = select1 == select11 select2 = edges > 20 select22 = edges <30 select_2 = select2 == select22 select3 = edges > 30 select33 = edges <40 select_3 = select3 == select33 select_4 = edges > 40 ################Different colors for diff strengths # Define the connectivity object c_default = ConnectObj('default', nodes, edges, select=select_0, line_width=1.5, antialias =True, custom_colors = {None: "#686868"},color_by = color_by, cmap = "inferno") # c_default1 = ConnectObj('default', nodes, edges, select=select_1, line_width=1.6, antialias =True, custom_colors = {None: "black"},color_by = color_by, cmap = "inferno") # c_default2 = ConnectObj('default', nodes, edges, select=select_2, line_width=1.7, antialias =True, custom_colors = {None: "rebeccapurple"},color_by = color_by, cmap = "inferno") # c_default3 = ConnectObj('default', nodes, edges, select=select_3, line_width=1.8, antialias =True, custom_colors = {None: "mediumvioletred"},color_by = color_by, cmap = "inferno") # c_default4 = ConnectObj('default', nodes, edges, select=select_4, line_width=2.5, antialias =True, custom_colors = {None: "darkorange"},color_by = color_by, cmap = "inferno") #if you want all connec to be same color use - custom_colors = {None: "green"} # Then, we define the sourcess #node size and color # s_obj = SourceObj('sources', nodes, radius_min=5., color="red") # black color nodes = color='#000000' #title # sc.add_to_subplot(c_default, row=0, col=0, zoom=0.1) # sc.add_to_subplot(c_default1, row=0, col=0, zoom=0.1) # sc.add_to_subplot(c_default2, row=0, col=0, zoom=0.1)
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) ###############################################################################
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
# Load files : xyz = np.genfromtxt(channel_coo_file, dtype=float) names = np.genfromtxt(channel_name_file, dtype=str) connect = np.load(connect_file) connect += connect.T connect = np.ma.masked_array(connect, mask=connect < thresh) names = names if with_text else None radius = connect.sum(1) clim = (thresh, connect.max()) # 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,
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
from visbrain.objects import ConnectObj, SceneObj, SourceObj, BrainObj from visbrain.io import download_file arch = np.load(download_file('phase_sync_delta.npz')) nodes, edges = arch['nodes'], arch['edges'] sc = SceneObj(bgcolor=(.1, .1, .1)) print(""" # ============================================================================= # Color by connectivity strength # ============================================================================= """) c_default = ConnectObj('default', nodes, edges, select=edges > .7, cmap='Spectral_r', line_width=2.) s_obj = SourceObj('sources', nodes, color='#ab4642', radius_min=15.) sc.add_to_subplot(c_default, title='Color by connectivity strength') sc.add_to_subplot(s_obj) sc.add_to_subplot(BrainObj('B1'), use_this_cam=True) print(""" # ============================================================================= # Color by number of connections per node # ============================================================================= """) c_count = ConnectObj('default', nodes, edges,