def test_plot_connectivity_circle(): """Test plotting connectivity circle """ node_order = ['frontalpole-lh', 'parsorbitalis-lh', 'lateralorbitofrontal-lh', 'rostralmiddlefrontal-lh', 'medialorbitofrontal-lh', 'parstriangularis-lh', 'rostralanteriorcingulate-lh', 'temporalpole-lh', 'parsopercularis-lh', 'caudalanteriorcingulate-lh', 'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh', 'caudalmiddlefrontal-lh', 'superiortemporal-lh', 'parahippocampal-lh', 'middletemporal-lh', 'inferiortemporal-lh', 'precentral-lh', 'transversetemporal-lh', 'posteriorcingulate-lh', 'fusiform-lh', 'postcentral-lh', 'bankssts-lh', 'supramarginal-lh', 'isthmuscingulate-lh', 'paracentral-lh', 'lingual-lh', 'precuneus-lh', 'inferiorparietal-lh', 'superiorparietal-lh', 'pericalcarine-lh', 'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh', 'lateraloccipital-rh', 'pericalcarine-rh', 'superiorparietal-rh', 'inferiorparietal-rh', 'precuneus-rh', 'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh', 'supramarginal-rh', 'bankssts-rh', 'postcentral-rh', 'fusiform-rh', 'posteriorcingulate-rh', 'transversetemporal-rh', 'precentral-rh', 'inferiortemporal-rh', 'middletemporal-rh', 'parahippocampal-rh', 'superiortemporal-rh', 'caudalmiddlefrontal-rh', 'insula-rh', 'superiorfrontal-rh', 'entorhinal-rh', 'caudalanteriorcingulate-rh', 'parsopercularis-rh', 'temporalpole-rh', 'rostralanteriorcingulate-rh', 'parstriangularis-rh', 'medialorbitofrontal-rh', 'rostralmiddlefrontal-rh', 'lateralorbitofrontal-rh', 'parsorbitalis-rh', 'frontalpole-rh'] label_names = ['bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh', 'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh', 'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh', 'entorhinal-lh', 'entorhinal-rh', 'frontalpole-lh', 'frontalpole-rh', 'fusiform-lh', 'fusiform-rh', 'inferiorparietal-lh', 'inferiorparietal-rh', 'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh', 'insula-rh', 'isthmuscingulate-lh', 'isthmuscingulate-rh', 'lateraloccipital-lh', 'lateraloccipital-rh', 'lateralorbitofrontal-lh', 'lateralorbitofrontal-rh', 'lingual-lh', 'lingual-rh', 'medialorbitofrontal-lh', 'medialorbitofrontal-rh', 'middletemporal-lh', 'middletemporal-rh', 'paracentral-lh', 'paracentral-rh', 'parahippocampal-lh', 'parahippocampal-rh', 'parsopercularis-lh', 'parsopercularis-rh', 'parsorbitalis-lh', 'parsorbitalis-rh', 'parstriangularis-lh', 'parstriangularis-rh', 'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh', 'postcentral-rh', 'posteriorcingulate-lh', 'posteriorcingulate-rh', 'precentral-lh', 'precentral-rh', 'precuneus-lh', 'precuneus-rh', 'rostralanteriorcingulate-lh', 'rostralanteriorcingulate-rh', 'rostralmiddlefrontal-lh', 'rostralmiddlefrontal-rh', 'superiorfrontal-lh', 'superiorfrontal-rh', 'superiorparietal-lh', 'superiorparietal-rh', 'superiortemporal-lh', 'superiortemporal-rh', 'supramarginal-lh', 'supramarginal-rh', 'temporalpole-lh', 'temporalpole-rh', 'transversetemporal-lh', 'transversetemporal-rh'] node_angles = circular_layout(label_names, node_order, start_pos=90) con = np.random.randn(68, 68) plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, title='test')
def test_plot_connectivity_circle(): """Test plotting connectivity circle """ node_order = [ 'frontalpole-lh', 'parsorbitalis-lh', 'lateralorbitofrontal-lh', 'rostralmiddlefrontal-lh', 'medialorbitofrontal-lh', 'parstriangularis-lh', 'rostralanteriorcingulate-lh', 'temporalpole-lh', 'parsopercularis-lh', 'caudalanteriorcingulate-lh', 'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh', 'caudalmiddlefrontal-lh', 'superiortemporal-lh', 'parahippocampal-lh', 'middletemporal-lh', 'inferiortemporal-lh', 'precentral-lh', 'transversetemporal-lh', 'posteriorcingulate-lh', 'fusiform-lh', 'postcentral-lh', 'bankssts-lh', 'supramarginal-lh', 'isthmuscingulate-lh', 'paracentral-lh', 'lingual-lh', 'precuneus-lh', 'inferiorparietal-lh', 'superiorparietal-lh', 'pericalcarine-lh', 'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh', 'lateraloccipital-rh', 'pericalcarine-rh', 'superiorparietal-rh', 'inferiorparietal-rh', 'precuneus-rh', 'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh', 'supramarginal-rh', 'bankssts-rh', 'postcentral-rh', 'fusiform-rh', 'posteriorcingulate-rh', 'transversetemporal-rh', 'precentral-rh', 'inferiortemporal-rh', 'middletemporal-rh', 'parahippocampal-rh', 'superiortemporal-rh', 'caudalmiddlefrontal-rh', 'insula-rh', 'superiorfrontal-rh', 'entorhinal-rh', 'caudalanteriorcingulate-rh', 'parsopercularis-rh', 'temporalpole-rh', 'rostralanteriorcingulate-rh', 'parstriangularis-rh', 'medialorbitofrontal-rh', 'rostralmiddlefrontal-rh', 'lateralorbitofrontal-rh', 'parsorbitalis-rh', 'frontalpole-rh' ] label_names = [ 'bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh', 'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh', 'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh', 'entorhinal-lh', 'entorhinal-rh', 'frontalpole-lh', 'frontalpole-rh', 'fusiform-lh', 'fusiform-rh', 'inferiorparietal-lh', 'inferiorparietal-rh', 'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh', 'insula-rh', 'isthmuscingulate-lh', 'isthmuscingulate-rh', 'lateraloccipital-lh', 'lateraloccipital-rh', 'lateralorbitofrontal-lh', 'lateralorbitofrontal-rh', 'lingual-lh', 'lingual-rh', 'medialorbitofrontal-lh', 'medialorbitofrontal-rh', 'middletemporal-lh', 'middletemporal-rh', 'paracentral-lh', 'paracentral-rh', 'parahippocampal-lh', 'parahippocampal-rh', 'parsopercularis-lh', 'parsopercularis-rh', 'parsorbitalis-lh', 'parsorbitalis-rh', 'parstriangularis-lh', 'parstriangularis-rh', 'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh', 'postcentral-rh', 'posteriorcingulate-lh', 'posteriorcingulate-rh', 'precentral-lh', 'precentral-rh', 'precuneus-lh', 'precuneus-rh', 'rostralanteriorcingulate-lh', 'rostralanteriorcingulate-rh', 'rostralmiddlefrontal-lh', 'rostralmiddlefrontal-rh', 'superiorfrontal-lh', 'superiorfrontal-rh', 'superiorparietal-lh', 'superiorparietal-rh', 'superiortemporal-lh', 'superiortemporal-rh', 'supramarginal-lh', 'supramarginal-rh', 'temporalpole-lh', 'temporalpole-rh', 'transversetemporal-lh', 'transversetemporal-rh' ] node_angles = circular_layout(label_names, node_order, start_pos=90) con = np.random.randn(68, 68) plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, title='test')
def plot_circular_connectivity(conmat, label_names, node_colors, node_order, vmin = 0.3, vmax = 1.0, nb_lines = 200, fname = "_def"): import os import numpy as np from mne.viz import circular_layout, plot_connectivity_circle import matplotlib.pyplot as plt # Angles node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) / 2]) # Plot the graph using node colors from the FreeSurfer parcellation. We only # show the 300 strongest connections. fig,_ = plot_connectivity_circle(conmat, label_names, n_lines=nb_lines, node_angles=node_angles, node_colors = node_colors, fontsize_names = 12, title='All-to-All Connectivity' , show = False, vmin = vmin, vmax = vmax) #plot_conmat_file = os.path.abspath('circle.png') plot_conmat_file = os.path.abspath('circle_' + fname + '.eps') fig.savefig(plot_conmat_file, facecolor='black') plt.close(fig) #fig1.close() del fig return plot_conmat_file
def _plot_circular_connectivity(conmat, label_names, node_colors=None, node_order=[], vmin=0.3, vmax=1.0, nb_lines=200, fname="_def", save_dir=None): """Plot circular connectivity.""" import matplotlib.pyplot as plt assert len(conmat.shape) == 2, "Error, conmat should be 2D matrix" assert conmat.shape[0] == conmat.shape[1], "Error, conmat should squared" assert conmat.shape[0] == len(label_names), "Error, conmat and labels\ should have same length {} != {}".format(conmat.shape[0], len(label_names)) # if not defined, use label_names if len(node_order) == 0: node_order = label_names # Angles node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) / 2]) # necessary to have symetric matrix conmat = conmat + np.transpose(conmat) # Plot the graph fig, _ = plot_connectivity_circle(conmat, label_names, n_lines=nb_lines, node_angles=node_angles.astype(int), node_colors=None, fontsize_names=12, title='All-to-All Connectivity', show=False, vmin=vmin, vmax=vmax) # saving circle file if save_dir is not None: assert os.path.exists(save_dir), ("Error, do not use save_dir if it \ does not exists before") plot_conmat_file = os.path.join(save_dir, 'circle_' + fname + '.png') else: plot_conmat_file = os.path.abspath('circle_' + fname + '.png') fig.savefig(plot_conmat_file, facecolor='black') plt.close(fig) return plot_conmat_file
def plot_circular_connectivity(conmat, label_names, node_colors, node_order, vmin=0.3, vmax=1.0, nb_lines=200, fname="_def"): """Plot circular connectivity""" import os import numpy as np from mne.viz import circular_layout, plot_connectivity_circle import matplotlib.pyplot as plt # Angles node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) / 2]) print(conmat) print((node_angles.astype(int))) conmat = conmat + np.transpose(conmat) # Plot the graph using node colors from the FreeSurfer parcellation. # We only show the 300 strongest connections. fig, _ = plot_connectivity_circle(conmat, label_names, n_lines=nb_lines, node_angles=node_angles.astype(int), node_colors=None, fontsize_names=12, title='All-to-All Connectivity', show=False, vmin=vmin, vmax=vmax) # plt.show() # print fig # plot_conmat_file = os.path.abspath('circle.png') plot_conmat_file = os.path.abspath('circle_' + fname + '.eps') fig.savefig(plot_conmat_file, facecolor='black') # fig.savefig(plot_conmat_file) plt.close(fig) # fig1.close() del fig return plot_conmat_file
def plot_seaborn(features, node_names=None, node_idx=None, **kwargs): from mne.viz import circular_layout node_angles = circular_layout( node_names.tolist(), node_names[node_idx].tolist(), start_pos=90, group_boundaries=[0, len(node_names) / 2. + 1]) matrix = copy_matrix(array_to_matrix(features.values[0]), diagonal_filler=0.) return plot_connectivity_seaborn(matrix, node_names=node_names, con_thresh=400, node_angles=node_angles, node_colors=sns.dark_palette( kwargs['color']))
def test_plot_connectivity_circle(): """Test plotting connectivity circle.""" node_order = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff'] label_names = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff'] group_boundaries = [0, 2, 4] node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=group_boundaries) con = np.random.RandomState(0).randn(6, 6) con[con < 0.7] = 0 fig, ax = plot_connectivity_circle(con, label_names, n_lines=60, node_angles=node_angles, title='test', colormap='RdBu_r', vmin=0, vmax=2, linewidth=.5, facecolor='k') plt.show() pytest.raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[-1]) pytest.raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[20, 0])
def test_plot_connectivity_circle(): """Test plotting connectivity circle.""" node_order = ['frontalpole-lh', 'parsorbitalis-lh', 'lateralorbitofrontal-lh', 'rostralmiddlefrontal-lh', 'medialorbitofrontal-lh', 'parstriangularis-lh', 'rostralanteriorcingulate-lh', 'temporalpole-lh', 'parsopercularis-lh', 'caudalanteriorcingulate-lh', 'entorhinal-lh', 'superiorfrontal-lh', 'insula-lh', 'caudalmiddlefrontal-lh', 'superiortemporal-lh', 'parahippocampal-lh', 'middletemporal-lh', 'inferiortemporal-lh', 'precentral-lh', 'transversetemporal-lh', 'posteriorcingulate-lh', 'fusiform-lh', 'postcentral-lh', 'bankssts-lh', 'supramarginal-lh', 'isthmuscingulate-lh', 'paracentral-lh', 'lingual-lh', 'precuneus-lh', 'inferiorparietal-lh', 'superiorparietal-lh', 'pericalcarine-lh', 'lateraloccipital-lh', 'cuneus-lh', 'cuneus-rh', 'lateraloccipital-rh', 'pericalcarine-rh', 'superiorparietal-rh', 'inferiorparietal-rh', 'precuneus-rh', 'lingual-rh', 'paracentral-rh', 'isthmuscingulate-rh', 'supramarginal-rh', 'bankssts-rh', 'postcentral-rh', 'fusiform-rh', 'posteriorcingulate-rh', 'transversetemporal-rh', 'precentral-rh', 'inferiortemporal-rh', 'middletemporal-rh', 'parahippocampal-rh', 'superiortemporal-rh', 'caudalmiddlefrontal-rh', 'insula-rh', 'superiorfrontal-rh', 'entorhinal-rh', 'caudalanteriorcingulate-rh', 'parsopercularis-rh', 'temporalpole-rh', 'rostralanteriorcingulate-rh', 'parstriangularis-rh', 'medialorbitofrontal-rh', 'rostralmiddlefrontal-rh', 'lateralorbitofrontal-rh', 'parsorbitalis-rh', 'frontalpole-rh'] label_names = ['bankssts-lh', 'bankssts-rh', 'caudalanteriorcingulate-lh', 'caudalanteriorcingulate-rh', 'caudalmiddlefrontal-lh', 'caudalmiddlefrontal-rh', 'cuneus-lh', 'cuneus-rh', 'entorhinal-lh', 'entorhinal-rh', 'frontalpole-lh', 'frontalpole-rh', 'fusiform-lh', 'fusiform-rh', 'inferiorparietal-lh', 'inferiorparietal-rh', 'inferiortemporal-lh', 'inferiortemporal-rh', 'insula-lh', 'insula-rh', 'isthmuscingulate-lh', 'isthmuscingulate-rh', 'lateraloccipital-lh', 'lateraloccipital-rh', 'lateralorbitofrontal-lh', 'lateralorbitofrontal-rh', 'lingual-lh', 'lingual-rh', 'medialorbitofrontal-lh', 'medialorbitofrontal-rh', 'middletemporal-lh', 'middletemporal-rh', 'paracentral-lh', 'paracentral-rh', 'parahippocampal-lh', 'parahippocampal-rh', 'parsopercularis-lh', 'parsopercularis-rh', 'parsorbitalis-lh', 'parsorbitalis-rh', 'parstriangularis-lh', 'parstriangularis-rh', 'pericalcarine-lh', 'pericalcarine-rh', 'postcentral-lh', 'postcentral-rh', 'posteriorcingulate-lh', 'posteriorcingulate-rh', 'precentral-lh', 'precentral-rh', 'precuneus-lh', 'precuneus-rh', 'rostralanteriorcingulate-lh', 'rostralanteriorcingulate-rh', 'rostralmiddlefrontal-lh', 'rostralmiddlefrontal-rh', 'superiorfrontal-lh', 'superiorfrontal-rh', 'superiorparietal-lh', 'superiorparietal-rh', 'superiortemporal-lh', 'superiortemporal-rh', 'supramarginal-lh', 'supramarginal-rh', 'temporalpole-lh', 'temporalpole-rh', 'transversetemporal-lh', 'transversetemporal-rh'] group_boundaries = [0, len(label_names) / 2] node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=group_boundaries) con = np.random.RandomState(0).randn(68, 68) plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, title='test', ) pytest.raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[-1]) pytest.raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[20, 0]) plt.close('all')
def make_circle(threshmat, outpath, label_names, thr): ## GET VMIN AND MAX FROM MATRIX # maxval = threshmat.max() # minval = np.min(threshmat[np.nonzero(threshmat)]) - 1 maxval = None minval = None ## CHECK CIRCLE GRAPH COLOR TYPE ## if color_type == 'DARK': fc = 'black' elif color_type == 'LIGHT': fc = 'white' ## PREP FIGURE fig = plt.figure(num=None, figsize=(30, 30), facecolor=fc) ## MAKE NODES ANGLES ## node_angles = circular_layout(label_names, node_order, start_pos=sp, group_boundaries=split) ## REMOVE NAMES IF TRUE ## remove_names = True if remove_names == True: label_names = [''] * len(label_names) ## WRITE GRAPH TO FIG ## if color_type == 'DARK': plot_connectivity_circle( threshmat, label_names, node_angles=node_angles, node_colors=label_colors, title=title, fontsize_title=48, textcolor='white', facecolor='black', node_edgecolor='black', node_linewidth=.5, linewidth=1.5, fontsize_names=8, colormap='hot', vmin=minval, vmax=maxval, ### make vmin and max the values from the min/max of matrix colorbar_size=0.2, colorbar_pos=(-1, .5), fontsize_colorbar=28, colorbar=True, padding=6.0, fig=fig, subplot=111, interactive=False, show=False) # ADD Left/Right Labels plt.gcf().text(.22, .5, 'L', color='white', fontsize=48) plt.gcf().text(.633, .5, 'R', color='white', fontsize=48) elif color_type == 'LIGHT': plot_connectivity_circle( threshmat, label_names, node_angles=node_angles, node_colors=label_colors, title=title, fontsize_title=48, textcolor='black', facecolor='white', node_edgecolor='black', node_linewidth=.5, linewidth=1.5, fontsize_names=8, colormap='hot_r', vmin=minval, vmax=maxval, # colormap='YlGnBu' ### make vmin and max the values from the min/max of matrix colorbar_size=0.2, colorbar_pos=(-1, .5), fontsize_colorbar=28, colorbar=True, padding=6.0, fig=fig, subplot=111, interactive=False, show=False) # ADD Left/Right Labels plt.gcf().text(.22, .5, 'L', color='black', fontsize=48) plt.gcf().text(.633, .5, 'R', color='black', fontsize=48) ## SAVE FIGURE ## out_fig = os.path.abspath( os.path.join(out_path, file_name + '_THR' + str(thr))) # have to re-set the facecolor before saving # fig.savefig(out_fig, facecolor=fc)
# Reorder the labels based on their location lh_labels = [label for (yp, label) in sorted(zip(label_ypos_lh, lh_labels))] # For the right hemi rh_labels = [ label[:-2] + 'rh' for label in lh_labels if label != 'Brain-Stem' and label[:-2] + 'rh' in rh_labels ] # Save the plot order node_order = list() node_order = lh_labels[::-1] + rh_labels node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) // 2]) # Plot the graph using node colors from the FreeSurfer parcellation. We only # show the 300 strongest connections. conmat = con[:, :, 0] plot_connectivity_circle(conmat, label_names, n_lines=300, node_angles=node_angles, node_colors=node_colors, title='All-to-All Connectivity left-Auditory ' 'Condition (PLI)') # Uncomment the following line to save the figure '''
def plot_connectomics(matrix, node_size, save_path, prename, save=False, **kwargs): _plot_cfg = { 'threshold': 1.4, 'fontsize_title': 19, 'fontsize_colorbar': 13, 'fontsize_names': 13, 'colorbar_size': 0.3, 'colormap': 'hot', 'vmin': -3, 'vmax': 3, 'figure': plt.figure(figsize=(16, 16)), 'facecolor': 'black', 'dpi': 150, 'name': 'weights', 'title': 'Connectome', 'filetype': 'png', 'zscore': True } _plot_cfg.update(kwargs) directory_ = save_path[save_path.rfind('/') + 1:] #names_lr, colors_lr, index_, coords = get_plot_stuff(directory_) names_lr = kwargs['node_names'] colors_lr = kwargs['node_colors'] index_ = kwargs['node_order'] coords = kwargs['node_coords'] networks = kwargs['networks'] matrix = matrix[index_][:, index_] names_lr = names_lr[index_] node_colors = colors_lr[index_] node_size = node_size[index_] f, _ = plot_connectivity_circle_edited( matrix, names_lr, node_colors=node_colors, node_size=node_size, con_thresh=_plot_cfg['threshold'], title=_plot_cfg['title'], node_angles=circular_layout( names_lr, list(names_lr), ), fontsize_title=_plot_cfg['fontsize_title'], fontsize_names=_plot_cfg['fontsize_names'], fontsize_colorbar=_plot_cfg['fontsize_colorbar'], colorbar_size=_plot_cfg['colorbar_size'], colormap=_plot_cfg['colormap'], vmin=_plot_cfg['vmin'], vmax=_plot_cfg['vmax'], fig=_plot_cfg['figure'], ) if save == True: fname = "%s_features_%s.%s" % (prename, _plot_cfg['name'], _plot_cfg['filetype']) f.savefig(os.path.join(save_path, fname), facecolor=_plot_cfg['facecolor'], dpi=_plot_cfg['dpi']) for d_ in ['x', 'y', 'z']: fname = None if save == True: fname = "%s_connectome_feature_%s_%s.%s" % ( prename, _plot_cfg['name'], d_, _plot_cfg['filetype']) fname = os.path.join(save_path, fname) plot_connectome(matrix, coords, colors_lr, node_size, _plot_cfg['threshold'], fname, cmap=_plot_cfg['colormap'], title=None, display_=d_, max_=_plot_cfg['vmax'], min_=_plot_cfg['vmin']) f = plot_matrix(matrix, _, networks, threshold=_plot_cfg['threshold'], zscore=_plot_cfg['zscore']) if save == True: fname = "%s_matrix_%s.%s" % (prename, _plot_cfg['name'], _plot_cfg['filetype']) f.savefig(os.path.join(save_path, fname), facecolor=_plot_cfg['facecolor'], dpi=_plot_cfg['dpi'])
except ValueError: pass # Reorder the labels based on their location lh_labels = [label for (yp, label) in sorted(zip(label_ypos_lh, lh_labels))] # For the right hemi rh_labels = [label[:-2] + 'rh' for label in lh_labels if label != 'Brain-Stem' and label[:-2] + 'rh' in rh_labels] # Save the plot order node_order = list() node_order = lh_labels[::-1] + rh_labels node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) // 2]) # Plot the graph using node colors from the FreeSurfer parcellation. We only # show the 300 strongest connections. conmat = con[:, :, 0] plot_connectivity_circle(conmat, label_names, n_lines=300, node_angles=node_angles, node_colors=node_colors, title='All-to-All Connectivity left-Auditory ' 'Condition (PLI)') # Uncomment the following line to save the figure ''' import matplotlib.pyplot as plt plt.savefig('circle.png', facecolor='black') '''
def circular_brain_plot(forward, solution_support, stcs, obj_fun, label_name=False, plot_circular=True, plot_labels=True, n_burnin=0, vmin=0., vmax=10., plot_hist=False, subplot=111, title='', fig=None, colorbar=True): indices = list() vertices_lh = list() vertices_rh = list() support = np.unique(np.where(solution_support)[1]) indices.append(support) for stc in stcs: vertices_lh.append(stc.vertices[0]) vertices_rh.append(stc.vertices[1]) indices = np.unique(np.concatenate(np.array(indices))) vertices_lh = np.unique(np.concatenate(np.array(vertices_lh))) vertices_rh = np.unique(np.concatenate(np.array(vertices_rh))) n_sources = solution_support.shape[1] # Get n_used of the left hemi n_used = forward['src'][0]['nuse'] n_rh = forward['src'][1]['nuse'] # indices_lh = indices[np.where(indices < n_used)[0]] indices_rh = indices[np.where(indices >= n_used)[0]] indices_sym = np.sort( np.concatenate( np.array([indices, indices_lh + n_used, indices_rh - n_rh]))) # n_support = len(indices_sym) iindices = [list(indices_sym).index(ii) for ii in indices] # Remove burnin solution_support = solution_support[n_burnin:, :] stcs = stcs[n_burnin:] # Plot histogram of the different objective function values # obtained with the MCMC init after burnin. if plot_hist: out = plt.hist(obj_fun) ymin, ymax = 0, out[0].max() plt.vlines(obj_fun[0], ymin=ymin, ymax=ymax) plt.ylim([ymin, ymax]) plt.yticks(fontsize=16) plt.xticks(fontsize=16) plt.xlabel('Objective function values', fontsize=16) plt.legend(['MM solution', 'MCMC initializations'], fontsize=16) plt.show() # #### ind = np.unique(np.where(solution_support)[1]) # #### # Take the results for all indices data_support_res = solution_support[:, indices] # Construct cooeccurrence matrix cooecc = np.zeros((n_sources, n_sources)) ixgrid = np.ix_(indices, indices) cooecc[ixgrid] = np.dot(data_support_res.T, data_support_res) ixgrid = np.ix_(indices_sym, indices_sym) cooecc = cooecc[ixgrid] # Read labels # data_path = sample.data_path() subjects_dir = sample.data_path() + '/subjects' labels = mne.read_labels_from_annot('sample', parc='aparc.split-125', subjects_dir=subjects_dir) # First, we reorder the labels based on their location in the left hemi label_names = [label.name for label in labels] lh_labels = [name for name in label_names if name.endswith('lh')] # Get the y-location of the label label_ypos = list() for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1]) label_ypos.append(ypos) # Reorder the labels based on their location lh_labels = [label for (yp, label) in sorted(zip(label_ypos, lh_labels))] # Find the corresponding label name to the vertices lh_names = list() length = 0 for vertex in vertices_lh: for label in labels[::2]: if vertex in label.vertices: lh_names.append(label.name) if len(lh_names) != length + 1: lh_names.append(labels[56].name) length += 1 rh_names = list() length = 0 for vertex in vertices_rh: for label in labels[1::2]: if vertex in label.vertices: rh_names.append(label.name) if len(rh_names) != length + 1: rh_names.append(labels[57].name) length += 1 names = lh_names + rh_names names_sym = np.array([''] * n_support, dtype='U30') names_sym[iindices] = names for ii in np.where(names_sym == '')[0]: if indices_sym[ii] < n_used: ind = np.where(indices == indices_sym[ii] + n_rh)[0] if ind.shape[0] == 0: ind = np.where(indices == indices_sym[ii] - 2 + n_rh)[0] name = np.array(names)[ind][0][:-3] + '-lh' else: ind = np.where(indices == indices_sym[ii] - n_used)[0] if ind.shape[0] == 0: ind = np.where(indices == indices_sym[ii] - 2 - n_used)[0] name = np.array(names)[ind][0][:-3] + '-rh' names_sym[ii] = name names = names_sym dipole_colors = list() names_lh = list() # For each found label find its color for label in names: if label[:-3] != 'n': idx = label_names.index(label) if labels[idx].color == (0., 0., 0., 1.): labels[idx].color = (0.5, 0.5, 0.5, 1.) dipole_colors.append(labels[idx].color) names_lh.append(label[:-3]) else: dipole_colors.append((0., 0., 0., 1.)) names_lh.append('none') names_lh = names_lh[:n_support // 2] seen_labels = list() node_order = list() # Find the good order for names and cooecc for label in lh_labels: if label not in seen_labels and label[:-3] in names_lh: node_order.append(np.where(np.array(names_lh) == label[:-3])[0]) seen_labels.append(label) lh_order = list(np.concatenate(np.array(node_order))) node_order = lh_order[::-1] # colors = list(np.array(dipole_colors)[node_order]) node_order.extend(list(np.array(lh_order) + len(lh_order))) node_width = 2 * 180. / n_support label_indices = range(n_support) node_angles = circular_layout(label_indices, node_order, start_pos=90, group_boundaries=[0, len(label_indices) / 2]) dipole_colors = dipole_colors[:n_support // 2] colors = np.concatenate(np.array([dipole_colors, dipole_colors])) if not label_name: names = np.array([''] * len(indices_sym), dtype=np.dtype((str, 35))) if plot_circular: fig, ax = plot_connectivity_circle(cooecc, names, n_lines=None, node_angles=node_angles, node_colors=colors, node_width=node_width, vmin=vmin, vmax=vmax, fig=fig, subplot=subplot, title=title, padding=4, textcolor='black', facecolor='white', colormap='viridis', node_edgecolor=None, colorbar=colorbar) plot_bars_circular(n_support, node_angles, cooecc.diagonal(), ax) if plot_labels: brain_labels(labels, names_sym, subjects_dir)
node_names = list(vertices.name[3:]) node_order = ['V1', 'PCU', 'PCC', 'lIPL', 'rIPL', 'lHP', 'rHP', 'ACC'] # find V1 v1_pos = [i for i, x in enumerate(node_order) if (x == 'V1')] if v1_pos[0] == 7: v1_pos.append(0) else: v1_pos.append(v1_pos[0] + 1) v1_pos.sort() node_angles = circular_layout(node_names, node_order, start_pos=90, group_boundaries=v1_pos) indices = (From - 4, To - 4) # undirected connectivity con, ind = np.unique(conn, return_index=True) indices = (From[ind] - 4, To[ind] - 4) #color rgb n_colors = [None] * len(node_order) n = 0 # counter for i in range(len(node_order)): if node_order[i] == 'V1': n_colors[i] = (0, 0, 0) else:
with open(yaml_fname, 'r') as f: xlabels = yaml.safe_load(f) # the yaml file has been hand curated to follow the same order as label_names # if not the node order has to be changed appropriately node_order = list() node_order.extend(label_names) group_bound = [len(list(key.values())[0]) for key in xlabels] group_bound = [0] + group_bound group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))] group_boundaries.pop() rsn_colors = ['m', 'b', 'y', 'c', 'r', 'g', 'w'] group_bound.pop(0) label_colors = [] for ind, rep in enumerate(group_bound): label_colors += [rsn_colors[ind]] * rep assert len(label_colors) == len(node_order), 'Number of colours do not match' from mne.viz.circle import circular_layout node_angles = circular_layout(label_names, label_names, start_pos=90, group_boundaries=group_boundaries) # Plot the graph using node colors from the FreeSurfer parcellation. plot_connectivity_circle(con_res['wpli'], label_names, n_lines=300, node_angles=node_angles, node_colors=label_colors, title='Connectivity between standard RSNs') # plt.savefig('circle.png', facecolor='black')
def plot_connectivity(fc: Union[np.ndarray, pd.DataFrame], threshold: Optional[float] = None, plot_style: str = 'heatmap', bg_style: str = 'whitegrid', node_order: Optional[list] = None, auto_cluster: bool = False, **kwargs) -> plt.Axes: """Plot functional connectivity between nodes in backend. Parameters ---------- fc Pandas dataframe containing or numpy array containing the functional connectivities. threshold Connectivtiy threshold to be applied (only connectivities larger than the threshold will be shown). plot_style Can either be `heatmap` for plotting with seaborn.heatmap or `circular_graph` for plotting with mne.viz.plot_connectivity_circle. Check out the respective function docstrings for information on their arguments (can be passed to kwargs). bg_style Only relevant if plot_style == heatmap. Then this will define the style of the background of the plot. node_order Order in which the nodes should appear in the plot. auto_cluster If true, automatic cluster detection will be used to arange the nodes kwargs Additional arguments for the fc calculation or fc plotting that can be passed. Returns ------- plt.Axes Handle of the axis the plot was created in. """ import seaborn as sb # turn fc into dataframe if necessary if type(fc) is np.ndarray: rows = kwargs.pop('yticklabels') if 'yticklabels' in kwargs.keys() else [str(i) for i in range(fc.shape[0])] cols = kwargs.pop('xticklabels') if 'xticklabels' in kwargs.keys() else [str(i) for i in range(fc.shape[1])] fc = pd.DataFrame(fc, index=[str(r) for r in rows], columns=[str(c) for c in cols]) # apply threshold if threshold: fc[fc < threshold] = 0. # cluster the columns ##################### if auto_cluster: idx_r = [i for i in range(fc.shape[0])] idx_c = [i for i in range(fc.shape[1])] # Create a categorical color palette for node groups col_pal_args = ['h', 's', 'l'] kwargs_tmp = {} for key in kwargs.keys(): if key in col_pal_args: kwargs_tmp[key] = kwargs.pop(key) node_pal = sb.husl_palette(len(idx_c), **kwargs_tmp) nodes = fc.columns.values node_lut = dict(zip(map(str, nodes), node_pal)) # Convert the palette to vectors that will be drawn on the side of the fc plot node_colors = pd.Series(nodes, index=fc.columns).map(node_lut) elif node_order: idx_c = [node_order.index(n) for n in fc.columns.values] idx_r = [i for i in range(fc.shape[0])] else: idx_r = [i for i in range(fc.shape[0])] idx_c = [i for i in range(fc.shape[1])] fc = fc.iloc[idx_r, idx_c] # plot the functional connectivities #################################### # choose plot style if plot_style == 'heatmap': # seaborn plot if 'xticklabels' not in kwargs: kwargs['xticklabels'] = fc.columns.values[idx_c] if 'yticklabels' not in kwargs: kwargs['yticklabels'] = fc.index[idx_r] sb.set_style(bg_style) if auto_cluster: ax = sb.clustermap(data=fc, row_colors=node_colors, col_colors=node_colors, **kwargs) else: ax = sb.heatmap(fc, **kwargs) # ax.invert_yaxis() elif plot_style == 'circular_graph': # mne python plot from mne.viz import circular_layout, plot_connectivity_circle # get node order for node layout node_names = fc.columns.values if auto_cluster: cluster_args = ['method', 'metric', 'z_score', 'standard_scale'] kwargs_tmp = {} for key in kwargs.keys(): if key in cluster_args: kwargs_tmp[key] = kwargs.pop(key) clust_map = sb.clustermap(data=fc, row_colors=node_colors, col_colors=node_colors, **kwargs_tmp) node_order = [node_names[idx] for idx in clust_map.dendrogram_row.reordered_ind] elif not node_order: node_order = list(node_names) # create circular node layout kwargs_tmp = {} layout_args = ['start_pos', 'start_between', 'group_boundaries', 'group_sep'] for key in kwargs.keys(): if key in layout_args: kwargs_tmp[key] = kwargs.pop(key) node_angles = circular_layout(node_names, node_order, **kwargs_tmp) # plot the circular graph ax = plot_connectivity_circle(fc.values, node_names, node_angles=node_angles, **kwargs) else: raise ValueError(f'Plot style is not supported by this function: {plot_style}. Check the documentation of the ' f'argument `plot_style` for valid options.') return ax
with open('/Users/pinheirochagas/Desktop/labels.csv', 'r') as f: reader = csv.reader(f, delimiter=',') labels = list(reader) labels = labels[1:] l1 = ['a' for i in range(len(labels))] for i in range(len(labels)): l1[i] = labels[i][0] labels = l1 label_colors = [labels for label in labels] labels[1][0] node_angles = circular_layout(labels, labels, group_boundaries = boundaries) fig = plt.figure(figsize=(20,20)) plot_connectivity_circle(corr_chans, labels, node_angles=node_angles, node_colors=[(.5,.5,.5, 1)], facecolor = [0.1,0.1,0.1], node_edgecolor=[0.1,0.1,0.1], textcolor=[1,1,1], fontsize_names = 10, colormap='viridis', vmin=np.min(corr_chans), vmax = np.max(corr_chans), linewidth = 1.5, fig=fig)
def make_circle(authors_df, label_names): ## Prep all labels, colors, etc # Create node colors types_colors = [ncol[0]] * len(type_labels) mm_colors = [ncol[1]] * len(authors_df.loc[authors_df['GendCat'] == 'MM', 'CitationKey']) mw_colors = [ncol[2]] * len(authors_df.loc[authors_df['GendCat'] == 'MW', 'CitationKey']) wm_colors = [ncol[3]] * len(authors_df.loc[authors_df['GendCat'] == 'WM', 'CitationKey']) ww_colors = [ncol[4]] * len(authors_df.loc[authors_df['GendCat'] == 'WW', 'CitationKey']) u_colors = [ncol[5]] * len(authors_df.loc[authors_df['GendCat'].str.contains(r'U'), 'CitationKey']) # LABEL COLORS GO IN THE ORIGINAL/MATRIX ORDER , not the reordered order! label_colors = types_colors + mm_colors + mw_colors + wm_colors + ww_colors + u_colors # MAKE NODE ORDER TO MAKE THE CIRCLE LOOK NICER - Node order is ONLY on the circle, not the matrix order. pre_labels = ['Man - Man','Man - Woman','Spacer1'] post_labels = ['Spacer2','Woman - Man','Woman - Woman','Unknown'] # This node order is for the graph only! (ordered from starting point counter clockwise) node_order = pre_labels + papers_label_list + post_labels # now clean node order remove spacer labels only for graphing (angles needs all to be unique and match matrix) cleaned_label_names = [' ' if 'Spacer' in i else i for i in label_names] # Optional(?) clean paper titles for better looking graph cleaned_titles = [] for paper in cleaned_label_names: x = re.split('(\d+)',paper) if len(x) == 3: cleaned_titles.append(f'{x[0]} ({x[1]})') else: cleaned_titles.append(paper) logger.debug(f'\n-Cleaned titles list: {cleaned_titles}\n') ## PREP FIGURE ## fig = plt.figure(figsize=(30, 30), facecolor='black') ## MAKE NODES ANGLES ## sp = 90 node_angles = circular_layout(label_names, node_order, start_pos=sp) ## Make custom colormap (if used) cmap = colors.ListedColormap(['black', ccol[0],ccol[1], ccol[2],ccol[3], ccol[4]]) boundaries = [0, 1, 2, 3, 4, 5] norm = colors.BoundaryNorm(boundaries, cmap.N, clip=True) # Make Custom/Manual Legend MM_patch = mpatches.Patch(facecolor=ncol[1], label='Man / Man', linewidth = 1, edgecolor = 'black') MW_patch = mpatches.Patch(facecolor=ncol[2], label='Man / Woman', linewidth = 1, edgecolor = 'black') WM_patch = mpatches.Patch(facecolor=ncol[3], label='Woman / Man', linewidth = 1, edgecolor = 'black') WW_patch = mpatches.Patch(facecolor=ncol[4], label='Woman / Woman', linewidth = 1, edgecolor = 'black') U_patch = mpatches.Patch(facecolor=ncol[5], label='Unknown', linewidth = 1, edgecolor = 'black') legend = plt.gcf().legend(handles=[MM_patch,MW_patch,WM_patch,WW_patch,U_patch], loc=1, facecolor=args.lcol, framealpha=.98, prop={'size':35}, fancybox=True, title='Citation Type',title_fontsize=40) # change legen color text? # plt.setp(legend.get_texts(), color='g') ## Create Circle Graph plot_connectivity_circle(cite_mat, cleaned_titles, node_angles=node_angles, node_colors=label_colors, title=title, padding=4, fontsize_title=48, textcolor='white', facecolor='black', colormap=cmap, colorbar=False, fig=fig, linewidth=4, fontsize_names=25, subplot=111, interactive=False, show=False ) ## SAVE FIGURE ## out_fig = os.path.abspath(os.path.join(args.out_dir,png_name)) # have to re-set the facecolor before saving # fig.savefig(out_fig, facecolor='black')
# Average across different k-values: df_k_feat = df_feat.reset_index().groupby(['band','targets'])['features'].apply(lambda x: np.vstack(x).mean(0)) # This is a weighted average ks = np.unique(df_feat.reset_index()['k'].values)[::-1] fx = lambda x: np.average(np.vstack(x), 0, weights=ks) df_k_feat = df_feat.reset_index().groupby(['band','targets'])['features'].apply(fx) df = df_k_feat.reset_index() # Connectome labels loading labels = np.loadtxt("/home/robbis/ROI_MNI_V4.txt", dtype=np.str_) node_names = labels.T[1][:99] node_idx = np.argsort(np.array([node[-1] for node in node_names])) node_angles = circular_layout(node_names.tolist(), node_names[node_idx].tolist(), start_pos=90, group_boundaries=[0, len(node_names) / 2.+1]) # Plot of the connectivity circle of selected features for band in np.unique(df['band'].values): for condition in np.unique(df['targets'].values): features = filter_dataframe(df, selection_dict={'band':[band], 'targets':[condition]}).reset_index() matrix = array_to_matrix(features['features'].values[0], copy=True, diagonal_filler=0.) f, a = plot_connectivity_circle_edited(matrix, node_names=node_names, con_thresh=70, node_angles=node_angles, colormap='magma',
print("E2E prediction results:") test_metrics_0 = regression_metrics(y_pred_0, y_true_0) print("class 0: {0}".format(test_metrics_0)) test_metrics_1 = regression_metrics(y_pred_1, y_true_1) print("class 1: {0}".format(test_metrics_1)) # Saliency map is the gradient of the maximum score value with respect to # the input image. model.model.eval() X = torch.from_numpy(x_test) X.requires_grad_() scores = model.model(X) scores.backward(torch.ones(scores.shape, dtype=torch.float32)) saliency, _ = torch.max(X.grad.data.abs(), dim=1) saliency = np.mean(saliency.numpy(), axis=0) hemi_size = len(labels) // 2 node_order = labels[:hemi_size] node_order.extend(labels[hemi_size:][::-1]) node_angles = circular_layout(labels, node_order, start_pos=90, group_boundaries=[0, hemi_size]) plot_connectivity_circle(saliency, labels, n_lines=300, node_angles=node_angles, title="Partial derivatives mapped on a circle plot") plt.show()
for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1]) label_ypos.append(ypos) # Reorder the labels based on their location lh_labels = [label for (ypos, label) in sorted(zip(label_ypos, lh_labels))] # For the right hemi rh_labels = [label[:-2] + 'rh' for label in lh_labels] # Save the plot order and create a circular layout node_order = list() node_order.extend(lh_labels[::-1]) # reverse the order node_order.extend(rh_labels) node_angles = circular_layout(label_names, node_order, start_pos=90) # Plot the graph using node colors from the FreeSurfer parcellation. We only # show the 300 strongest connections. plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, node_colors=label_colors, title='All-to-All Connectivity left-Auditory ' 'Condition') import matplotlib.pyplot as plt plt.savefig('circle.png', facecolor='black') plt.show()
def plot_tab_circular_connectivity(list_list_conmat, all_elec_labels, plot_filename, coh_low_thresh=0.0, coh_high_thresh=1.0, color_bar='gist_rainbow', column_labels=[], row_labels=[]): """Plot tab circular conectivity.""" nb_lines = len(list_list_conmat) print(nb_lines) print(len(list_list_conmat[0])) if len(list_list_conmat) != 1: for i, j in combinations(list(range(nb_lines)), 2): assert len(list_list_conmat[i]) == len( list_list_conmat[j]), ("Error, not all the same length {} != " "{}".format(len(list_list_conmat[i]), len(list_list_conmat[j]))) nb_cols = len(list_list_conmat[0]) # for i in # print list_list_conmat[0][0].shape # Angles bounds = [0, len(all_elec_labels) / 2] all_node_angles = circular_layout(all_elec_labels, node_order=all_elec_labels, start_pos=90, group_boundaries=bounds) # print all_node_angles fig, axes = plt.subplots(nrows=nb_lines, ncols=nb_cols, figsize=(4 * nb_cols, 4 * nb_lines), facecolor='black') # fig = plt.figure(num=None, figsize=(4*nb_cols, 4*nb_lines), # facecolor='black') if len(column_labels) == 0: column_labels = ['Column {}'.format(col) for col in range(nb_cols)] if len(row_labels) == 0: row_labels = ['Line {}'.format(row) for row in range(nb_lines)] assert len(column_labels) == nb_cols, ( "Error, specifying invalid number of column labels") assert len(row_labels) == nb_lines, ( "Error, specifying invalid number of line labels") for index_sess, list_conmat in enumerate(list_list_conmat): print(len(list_conmat)) for index_win, np_all_mean_con_mats in enumerate(list_conmat): print(np_all_mean_con_mats.shape) kw = dict(textcolor="black", facecolor="white", n_lines=None, node_angles=all_node_angles, fontsize_names=15, show=False, colormap=color_bar, vmin=coh_low_thresh, vmax=coh_high_thresh, fig=fig, subplot=(nb_lines, nb_cols, 1 + index_win + nb_cols * index_sess)) if index_win == len(list_conmat) - 1: fig, ax = plot_connectivity_circle(np_all_mean_con_mats, all_elec_labels, colorbar_size=0.5, **kw) # (nb_lines,nb_cols,1+index_win+nb_cols*index_sess)) else: fig, ax = plot_connectivity_circle(np_all_mean_con_mats, all_elec_labels, colorbar=False, **kw) if index_win == 0: ax.set_ylabel(row_labels[index_sess], rotation=0, size='large', fontsize=25) if index_sess == 0: ax.set_title(column_labels[index_win], fontdict={'fontsize': 25}) # saving print(plot_filename) fig.savefig(plot_filename, facecolor='white') plt.close(fig) # fig1.close() del fig
labels = labels_lr[:99] node_idx = np.lexsort((labels.T[-1], [l[-1] for l in labels.T[1]])) node_idx = np.hstack((node_idx[:49], node_idx[49:][::-1])) labels_ord = labels[node_idx] coords_lr_ord = coords_lr[node_idx] names = labels_ord.T[1] names = np.array([n.replace("_", " ") for n in names]) node_angles = circular_layout(names.tolist(), names.tolist(), start_between=False, start_pos=90, group_boundaries=[0, 49, len(names) / 2.+1], group_sep=3.) node_network = labels_ord.T[3] networks, count = np.unique(node_network, return_counts=True) color_network = sns.color_palette("Paired", len(networks)+1) colors_ = dict(zip(networks, color_network[1:])) colors = [colors_[n] for n in node_network] ######################################################## path = "/scratch/work/guidotr1/data/derivatives" path = "/media/robbis/Seagate_Pt1/data/working_memory/data/derivatives/" dataframes = []
def test_plot_connectivity_circle(): """Test plotting connectivity circle """ node_order = [ "frontalpole-lh", "parsorbitalis-lh", "lateralorbitofrontal-lh", "rostralmiddlefrontal-lh", "medialorbitofrontal-lh", "parstriangularis-lh", "rostralanteriorcingulate-lh", "temporalpole-lh", "parsopercularis-lh", "caudalanteriorcingulate-lh", "entorhinal-lh", "superiorfrontal-lh", "insula-lh", "caudalmiddlefrontal-lh", "superiortemporal-lh", "parahippocampal-lh", "middletemporal-lh", "inferiortemporal-lh", "precentral-lh", "transversetemporal-lh", "posteriorcingulate-lh", "fusiform-lh", "postcentral-lh", "bankssts-lh", "supramarginal-lh", "isthmuscingulate-lh", "paracentral-lh", "lingual-lh", "precuneus-lh", "inferiorparietal-lh", "superiorparietal-lh", "pericalcarine-lh", "lateraloccipital-lh", "cuneus-lh", "cuneus-rh", "lateraloccipital-rh", "pericalcarine-rh", "superiorparietal-rh", "inferiorparietal-rh", "precuneus-rh", "lingual-rh", "paracentral-rh", "isthmuscingulate-rh", "supramarginal-rh", "bankssts-rh", "postcentral-rh", "fusiform-rh", "posteriorcingulate-rh", "transversetemporal-rh", "precentral-rh", "inferiortemporal-rh", "middletemporal-rh", "parahippocampal-rh", "superiortemporal-rh", "caudalmiddlefrontal-rh", "insula-rh", "superiorfrontal-rh", "entorhinal-rh", "caudalanteriorcingulate-rh", "parsopercularis-rh", "temporalpole-rh", "rostralanteriorcingulate-rh", "parstriangularis-rh", "medialorbitofrontal-rh", "rostralmiddlefrontal-rh", "lateralorbitofrontal-rh", "parsorbitalis-rh", "frontalpole-rh", ] label_names = [ "bankssts-lh", "bankssts-rh", "caudalanteriorcingulate-lh", "caudalanteriorcingulate-rh", "caudalmiddlefrontal-lh", "caudalmiddlefrontal-rh", "cuneus-lh", "cuneus-rh", "entorhinal-lh", "entorhinal-rh", "frontalpole-lh", "frontalpole-rh", "fusiform-lh", "fusiform-rh", "inferiorparietal-lh", "inferiorparietal-rh", "inferiortemporal-lh", "inferiortemporal-rh", "insula-lh", "insula-rh", "isthmuscingulate-lh", "isthmuscingulate-rh", "lateraloccipital-lh", "lateraloccipital-rh", "lateralorbitofrontal-lh", "lateralorbitofrontal-rh", "lingual-lh", "lingual-rh", "medialorbitofrontal-lh", "medialorbitofrontal-rh", "middletemporal-lh", "middletemporal-rh", "paracentral-lh", "paracentral-rh", "parahippocampal-lh", "parahippocampal-rh", "parsopercularis-lh", "parsopercularis-rh", "parsorbitalis-lh", "parsorbitalis-rh", "parstriangularis-lh", "parstriangularis-rh", "pericalcarine-lh", "pericalcarine-rh", "postcentral-lh", "postcentral-rh", "posteriorcingulate-lh", "posteriorcingulate-rh", "precentral-lh", "precentral-rh", "precuneus-lh", "precuneus-rh", "rostralanteriorcingulate-lh", "rostralanteriorcingulate-rh", "rostralmiddlefrontal-lh", "rostralmiddlefrontal-rh", "superiorfrontal-lh", "superiorfrontal-rh", "superiorparietal-lh", "superiorparietal-rh", "superiortemporal-lh", "superiortemporal-rh", "supramarginal-lh", "supramarginal-rh", "temporalpole-lh", "temporalpole-rh", "transversetemporal-lh", "transversetemporal-rh", ] group_boundaries = [0, len(label_names) / 2] node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=group_boundaries) con = np.random.randn(68, 68) plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, title="test") plt.close("all") assert_raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[-1]) assert_raises(ValueError, circular_layout, label_names, node_order, group_boundaries=[20, 0])
def plot_fica_grouped_circle(yaml_fname, con, node_order_size, out_fname='grouped_circle.png', title=None, facecolor='white', fontsize_names=6, subplot=111, include_legend=False, n_lines=None, fig=None, show=True): ''' Plot the connectivity circle grouped and ordered according to groups in the yaml input file provided. This is not specific to 'aparc' parcellation and does not split the labels into left and right hemispheres. Note: Currently requires fica_names.txt in jumeg/examples. This needs to be removed. ''' # load the label names in the original order # TODO remove empty lines / strings if any # TODO remove below code from here labels_fname = get_jumeg_path() + '/examples/fica_names.txt' with open(labels_fname, 'r') as f: orig_labels = [line.rstrip('\n') for line in f] # read the yaml file with grouping if op.isfile(yaml_fname): with open(yaml_fname, 'r') as f: labels = yaml.load(f) else: print '%s - File not found.' % yaml_fname sys.exit() cortex_colors = ['m', 'b', 'y', 'c', 'r', 'g'] # make list of label_names (without individual cortex locations) label_names = list() for lab in labels: label_names.extend(labels[lab]) group_labels = labels.keys() # Save the plot order and create a circular layout node_order = label_names assert len(node_order) == node_order_size, 'Node order length is correct.' # save the group order group_node_order = group_labels from mne.viz.circle import circular_layout group_node_angles = circular_layout(group_node_order, group_node_order, start_pos=75.) # the respective no. of regions in each cortex group_bound = [len(labels[key]) for key in labels.keys()] group_bound = [0] + group_bound # group_bound = [0] + group_bound[::-1] + group_bound group_boundaries = [ sum(group_bound[:i + 1]) for i in range(len(group_bound)) ] # remove the first element of group_bound # make label colours such that each cortex is of one colour group_bound.pop(0) label_colors = [] for ind, rep in enumerate(group_bound): label_colors += [cortex_colors[ind]] * rep assert len(label_colors) == len(node_order), 'Num. of colours do not match' # remove the last total sum of the list group_boundaries.pop() # obtain the node angles node_angles = circular_layout(orig_labels, node_order, start_pos=90, group_boundaries=group_boundaries) # the order of the node_colors must match that of orig_labels # therefore below reordering is necessary reordered_colors = [ label_colors[node_order.index(orig)] for orig in orig_labels ] # Plot the graph using node_order and colours _plot_connectivity_circle(con, orig_labels, n_lines=n_lines, facecolor=facecolor, textcolor='black', group_node_order=group_node_order, group_node_angles=group_node_angles, group_colors=cortex_colors, fontsize_groups=6, node_angles=node_angles, node_colors=reordered_colors, fontsize_names=8, node_edgecolor='white', fig=fig, colorbar=False, show=show, subplot=subplot, title=title) if include_legend: import matplotlib.patches as mpatches legend_patches = [ mpatches.Patch(color=col, label=key) for col, key in zip(['g', 'r', 'c', 'y', 'b', 'm'], labels.keys()) ] plt.legend(handles=legend_patches, loc=(0.02, 0.02), ncol=1, mode=None, fontsize='small') if out_fname: plt.savefig(out_fname, facecolor='white', dpi=300)
def main(): parser = buildArgsParser() args = parser.parse_args() if not os.path.exists(args.matrix): parser.error("{0} is not a valid file path.".format(args.matrix)) if not os.path.splitext(args.matrix)[1] == ".npy": parser.error("Connectivity matrix must be given in .npy format.") if not os.path.exists(args.row_map): parser.error("{0} is not a valid file path.".format(args.row_map)) if os.path.splitext(args.row_map)[1] != ".pkl": parser.error("Name mapping must be given in a .pkl file.") if args.save and os.path.exists(args.save) and not args.force: parser.error("Output image: {0} already exists.\n".format(args.save) + "Use -f to force overwriting.") con_mat = np.load(args.matrix) with open(args.row_map) as f: row_name_map = pickle.load(f) lh_tags = ['_lh_', 'Left'] rh_tags = ['_rh_', 'Right'] if args.clean_lbl: label_names = [row_name_map[k]['lut_name'] for k in sorted(row_name_map)] lh_tags = ['LH'] rh_tags = ['RH'] else: label_names = [row_name_map[k]['free_name'] for k in sorted(row_name_map)] lh_tags.append('-lh-') rh_tags.append('-rh-') lh_labels = [name for name in label_names if any(tag in name for tag in lh_tags)] rh_labels = [name for name in label_names if any(tag in name for tag in rh_tags)] # Validate if all labels were found uncut_labels = set(label_names) - set(lh_labels) - set(rh_labels) if len(uncut_labels) > 0: raise ValueError("Some labels were not filtered as Left or Right.") if args.sort_y: # TODO choose color # label_colors = [label.color for label in labels] label_ypos = [] for name in lh_labels: label_ypos.append(find_mean_y_pos(row_name_map, name)) lh_labels = [label for (ypos, label) in sorted(zip(label_ypos, lh_labels))] rh_labels = [label for (ypos, label) in sorted(zip(label_ypos, rh_labels))] node_order = list() node_order.extend(lh_labels[::-1]) # reverse the order node_order.extend(rh_labels) node_angles = circular_layout(label_names, node_order, start_pos=90, group_boundaries=[0, len(label_names) / 2]) fig, axes = plot_connectivity_circle(con_mat, label_names, linewidth=1.5, interactive=True, vmin=0, vmax=1, node_angles=node_angles, title='All-to-all Connectivity') # plot_connectivity_circle( # node_colors=label_colors, # fontsize_colorbar=6, plt.show(block=True) if args.save: fig.savefig(args.save, facecolor='black')
def plot_fica_grouped_circle(yaml_fname, con, node_order_size, out_fname='grouped_circle.png', title=None, facecolor='white', fontsize_names=6, subplot=111, include_legend=False, n_lines=None, fig=None, show=True): ''' Plot the connectivity circle grouped and ordered according to groups in the yaml input file provided. This is not specific to 'aparc' parcellation and does not split the labels into left and right hemispheres. Note: Currently requires fica_names.txt in jumeg/examples. This needs to be removed. ''' # load the label names in the original order # TODO remove empty lines / strings if any # TODO remove below code from here labels_fname = get_jumeg_path() + '/examples/fica_names.txt' with open(labels_fname, 'r') as f: orig_labels = [line.rstrip('\n') for line in f] # read the yaml file with grouping if op.isfile(yaml_fname): with open(yaml_fname, 'r') as f: labels = yaml.load(f) else: print '%s - File not found.' % yaml_fname sys.exit() cortex_colors = ['m', 'b', 'y', 'c', 'r', 'g'] # make list of label_names (without individual cortex locations) label_names = list() for lab in labels: label_names.extend(labels[lab]) group_labels = labels.keys() # Save the plot order and create a circular layout node_order = label_names assert len(node_order) == node_order_size, 'Node order length is correct.' # save the group order group_node_order = group_labels from mne.viz.circle import circular_layout group_node_angles = circular_layout(group_node_order, group_node_order, start_pos=75.) # the respective no. of regions in each cortex group_bound = [len(labels[key]) for key in labels.keys()] group_bound = [0] + group_bound # group_bound = [0] + group_bound[::-1] + group_bound group_boundaries = [sum(group_bound[:i+1]) for i in range(len(group_bound))] # remove the first element of group_bound # make label colours such that each cortex is of one colour group_bound.pop(0) label_colors = [] for ind, rep in enumerate(group_bound): label_colors += [cortex_colors[ind]] * rep assert len(label_colors) == len(node_order), 'Num. of colours do not match' # remove the last total sum of the list group_boundaries.pop() # obtain the node angles node_angles = circular_layout(orig_labels, node_order, start_pos=90, group_boundaries=group_boundaries) # the order of the node_colors must match that of orig_labels # therefore below reordering is necessary reordered_colors = [label_colors[node_order.index(orig)] for orig in orig_labels] # Plot the graph using node_order and colours _plot_connectivity_circle(con, orig_labels, n_lines=n_lines, facecolor=facecolor, textcolor='black', group_node_order=group_node_order, group_node_angles=group_node_angles, group_colors=cortex_colors, fontsize_groups=6, node_angles=node_angles, node_colors=reordered_colors, fontsize_names=8, node_edgecolor='white', fig=fig, colorbar=False, show=show, subplot=subplot, title=title) if include_legend: import matplotlib.patches as mpatches legend_patches = [mpatches.Patch(color=col, label=key) for col, key in zip(['g', 'r', 'c', 'y', 'b', 'm'], labels.keys())] plt.legend(handles=legend_patches, loc=(0.02, 0.02), ncol=1, mode=None, fontsize='small') if out_fname: plt.savefig(out_fname, facecolor='white', dpi=300)
# Get the y-location of the label label_ypos = list() for name in lh_labels: idx = label_names.index(name) ypos = np.mean(labels[idx].pos[:, 1]) label_ypos.append(ypos) # Reorder the labels based on their location lh_labels = [label for (ypos, label) in sorted(zip(label_ypos, lh_labels))] # For the right hemi rh_labels = [label[:-2] + 'rh' for label in lh_labels] # Save the plot order and create a circular layout node_order = list() node_order.extend(lh_labels[::-1]) # reverse the order node_order.extend(rh_labels) node_angles = circular_layout(label_names, node_order, start_pos=90) # Plot the graph using node colors from the FreeSurfer parcellation. We only # show the 300 strongest connections. plot_connectivity_circle(con, label_names, n_lines=300, node_angles=node_angles, node_colors=label_colors, title='All-to-All Connectivity left-Auditory ' 'Condition') import matplotlib.pyplot as plt plt.savefig('circle.png', facecolor='black') plt.show()
node_order = models_only print 'test1', len(models_only) print models_only print 'test2', len(model_runs) print model_runs else: label_names = model_runs node_order = model_runs label_colors = model_colors node_angles = circular_layout( label_names, node_order, start_pos=90, #start_pos=95, #group_boundaries=[0, len(label_names) / 2]) #group_boundaries=[0], #group_boundaries=[0, len(label_names)-1], #group_boundaries = gbdy, ) figure = plt.figure(figsize=(20, 20), dpi=100, facecolor='black') if OnePerMod: ftsiz = 10 else: ftsiz = 5 fig, ax = plot_connectivity_circle( M, label_names,