def plot_within_between_weights(connections, condition, savepath, atlas='findlab', background='white'): import matplotlib.pyplot as pl names_lr, colors_lr, index_, coords, networks = get_atlas_info(atlas, background=background) _, idxnet = np.unique(networks, return_index=True) _, idx = np.unique(colors_lr, return_index=True) color_net = dict(zip(networks[np.sort(idxnet)], colors_lr[np.sort(idx)])) fig = pl.figure(figsize=(13.2,10), dpi=200) for k_, v_ in connections.iteritems(): lines_ = [pl.plot(v_, 'o-', c=color_net[k_], markersize=20, linewidth=5, alpha=0.6, label=k_)] pl.legend() pl.ylabel("Average connection weight") pl.xticks([0,1,1.4], ['Between-Network', 'Within-Network','']) pl.title(condition+' within- and between-networks average weights') pl.savefig(os.path.join(savepath, condition+'_decoding_within_between.png'), dpi=200) return fig
def plot_within_between_weights(connections, condition, savepath, atlas='findlab', background='white'): import matplotlib.pyplot as pl names_lr, colors_lr, index_, coords, networks = get_atlas_info( atlas, background=background) _, idxnet = np.unique(networks, return_index=True) _, idx = np.unique(colors_lr, return_index=True) color_net = dict(zip(networks[np.sort(idxnet)], colors_lr[np.sort(idx)])) fig = pl.figure(figsize=(13.2, 10), dpi=200) for k_, v_ in connections.iteritems(): lines_ = [ pl.plot(v_, 'o-', c=color_net[k_], markersize=20, linewidth=5, alpha=0.6, label=k_) ] pl.legend() pl.ylabel("Average connection weight") pl.xticks([0, 1, 1.4], ['Between-Network', 'Within-Network', '']) pl.title(condition + ' within- and between-networks average weights') pl.savefig(os.path.join(savepath, condition + '_decoding_within_between.png'), dpi=200) return fig
def plot_matrix(matrix, roi_names, networks, threshold=0, zscore=True, **kwargs): """ This function is used to plot connections in square matrix form. Parameters ---------- matrix : numpy array (n x n) float The values of connectivity between each of n ROI roi_names : list of n string The names of each of the n ROI networks : list of p string List of names representing the networks subdivision threshold : int Indicates the value of the most important connections ticks_type : {'networks', 'roi'}, optional Indicates if the tick names should be ROI or networks ticks_color : list of colors, optional The list in matplotlib formats of colors used to color the ticks names, this should be in line with the ticks_type choice: p colors if we choose 'networks' facecolor : string, optional As in matplotlib it indicates the background color of the plot Returns ------- f : matplotlib figure The figure just composed. """ _plot_cfg = {'ticks_type':'networks', 'ticks_color':get_atlas_info('findlab')[1], 'facecolor':'k', 'zscore': True } _plot_cfg.update(kwargs) facecolor_ = _plot_cfg['facecolor'] if facecolor_ == 'k': ax_color = 'white' else: ax_color = 'k' facecolor_ = 'white' f = plt.figure(figsize=(16., 12.), facecolor=facecolor_, dpi=300) #f = plt.figure() a = f.add_subplot(111) max_value = np.max(np.abs(matrix)) # plot gray values print _plot_cfg['zscore'] if _plot_cfg['zscore'] == True: z_matrix = (matrix - matrix.mean())/matrix.std() else: z_matrix = matrix max_value = np.max(np.abs(z_matrix)) ax = a.imshow(z_matrix, interpolation='nearest', cmap=plt.cm.RdBu_r, #cmap='Greys', alpha=0.5, vmax=max_value, vmin=max_value*-1 ) # plot colored values thresh_matrix = masked_array(z_matrix, (np.abs(z_matrix) < threshold)) ax = a.imshow(thresh_matrix, interpolation='nearest', cmap=plt.cm.bwr, #cmap='gray', vmax=max_value, vmin=max_value*-1, ) min_ = -0.5 max_ = len(networks) + 0.5 ### Draw networks separation lines ### network_ticks = [] network_name, indices = np.unique(networks, return_index=True) counter = -0.5 colors_ = [] for net in np.unique(networks): items_idx = np.nonzero(networks == net) items = items_idx[0].shape[0] ix = np.nonzero(networks == net) if _plot_cfg['ticks_type'] == 'networks': tick_ = items_idx[0].mean() colors_.append(np.unique(_plot_cfg['ticks_color'])) else: tick_ = items_idx[0] colors_.append(_plot_cfg['ticks_color'][tick_]) counter = counter + items network_ticks.append(tick_) a.axvline(x=counter, ymin=min_, ymax=max_) a.axhline(y=counter, xmin=min_, xmax=max_) if _plot_cfg['ticks_type'] == 'networks': ticks_labels = np.unique(networks) else: ticks_labels = roi_names network_ticks = np.hstack(network_ticks) colors_ = np.hstack(colors_) a.set_yticks(network_ticks) a.set_yticklabels(ticks_labels, fontsize=15) a.set_xticks(network_ticks) a.set_xticklabels(ticks_labels, fontsize=15, rotation=80) colors_[colors_ == facecolor_] = ax_color colors_[colors_ == 'beige'] = 'darkgray' [t.set_color(colors_[i]) for i,t in enumerate(a.xaxis.get_ticklabels())] [t.set_color(colors_[i]) for i,t in enumerate(a.yaxis.get_ticklabels())] cbar = f.colorbar(ax) [t.set_color(ax_color) for i,t in enumerate(cbar.ax.yaxis.get_ticklabels())] return f
def analyze_results(directory, conditions, n_permutations=1000.): """Write the results of the regression analysis Parameters ---------- directory : string or list of strings Path or list of paths where put results. condition : string or list of strings Conditions to be analyzed. Returns ------- fig : instance of matplotlib.pyplot.Figure The figure handle. """ res_path = '/media/robbis/DATA/fmri/monks/0_results/' subjects = np.loadtxt('/media/robbis/DATA/fmri/monks/attributes_struct.txt', dtype=np.str) path = '/media/robbis/DATA/fmri/monks/' roi_list = [] roi_list = np.loadtxt('/media/robbis/DATA/fmri/templates_fcmri/findlab_rois.txt', delimiter=',', dtype=np.str) if isinstance(directory, str): directory = [directory] if isinstance(conditions, str): conditions = [conditions] for dir_ in directory: for cond_ in conditions: fname_ = os.path.join(res_path, dir_, cond_+'_values_1000_50.npz') results_ = np.load(fname_) values_ = results_['arr_0'].tolist() errors_ = values_['error'] #values_['errors_'] sets_ = values_['features'] #values_['sets_'] weights_ = values_['weights'] #values_['weights_'] samples_ = values_['subjects'] #values_['samples_'] fname_ = os.path.join(res_path, dir_, cond_+'_permutation_1000_50.npz') results_ = np.load(fname_) values_p = results_['arr_0'].tolist() errors_p = values_p['error'] #values_p['errors_p'] sets_p = values_p['features'] #values_p['sets_p'] weights_p = values_p['weights'] #values_p['weights_p'] samples_p = values_p['subjects'] #values_p['samples_p'] errors_p = np.nanmean(errors_p, axis=1) print('-----------'+dir_+'-------------') print(cond_) print ('MSE = '+str(errors_[:,0].mean())+' -- p '+ \ str(np.count_nonzero(errors_p[:,0] < errors_[:,0].mean())/n_permutations)) print('COR = '+str(np.nanmean(errors_[:,1]))+' -- p '+ \ str(np.count_nonzero(errors_p[:,1] > np.nanmean(errors_[:,1]))/n_permutations)) directory_ = dir_ learner_ = "SVR_C_1" prename = "%s_%s" %(cond_, learner_) ######## Get matrix infos ############### conn_test = ConnectivityLoader(res_path, subjects, directory_, roi_list) # Get nan mask to correctly fill matrix nan_mask = conn_test.get_results(['Samatha', 'Vipassana']) # Transform matrix into float of ones mask_ = np.float_(~np.bool_(nan_mask)) # Get the upper part of the matrix mask_ = np.triu(mask_, k=1) mask_indices = np.nonzero(mask_) n_bins = np.count_nonzero(mask_) ###### Plot of distributions of errors and permutations ######### #errors_p = np.nanmean(errors_p, axis=1) fig_ = pl.figure() bpp = pl.boxplot(errors_p, showfliers=False, showmeans=True, patch_artist=True) bpv = pl.boxplot(errors_, showfliers=False, showmeans=True, patch_artist=True) fname = "%s_perm_1000_boxplot.png" %(prename) for box_, boxp_ in zip(bpv['boxes'], bpp['boxes']): box_.set_facecolor('lightgreen') boxp_.set_facecolor('lightslategrey') pl.xticks(np.array([1,2]), ['MSE', 'COR']) pl.savefig(os.path.join(res_path, directory_, fname)) pl.close() n_permutations = np.float(errors_p[:,0].shape[0]) ##### Plot of connection distributions ######## pl.figure() h_values_p, _ = np.histogram(sets_p.flatten(), bins=np.arange(0, n_bins+1)) #pl.plot(zscore(h_values_p)) pl.hist(zscore(h_values_p), bins=25) fname = "%s_features_set_dist.png" %(prename) pl.savefig(os.path.join(res_path, directory_, fname)) pl.figure() h_values_, _ = np.histogram(sets_.flatten(), bins=np.arange(0, n_bins+1)) pl.plot(zscore(h_values_)) fname = "%s_features_set_cross_validation.png" %(prename) pl.savefig(os.path.join(res_path, directory_, fname)) pl.close('all') ######## Plot connectivity stuff ########### weights_ = weights_.squeeze() filling_vector = np.zeros(np.count_nonzero(mask_)) counting_vector = np.zeros(np.count_nonzero(mask_)) for s, w in zip(sets_, weights_): filling_vector[s] += zscore(w) counting_vector[s] += 1 # Calculate the average weights and then zscore avg_weigths = np.nan_to_num(filling_vector/counting_vector) mask_[mask_indices] = avg_weigths matrix_ = np.nan_to_num(copy_matrix(mask_, diagonal_filler=0)) names_lr, colors_lr, index_, coords, _ = get_atlas_info(dir_) ''' matrix_[matrix_ == 0] = np.nan matrix_[np.abs(matrix_) < 1] = np.nan ''' size_w = np.zeros_like(matrix_) size_w[mask_indices] = np.abs(avg_weigths) size_w = np.nan_to_num(copy_matrix(size_w, diagonal_filler=0)) size_w = np.sum(size_w, axis=0) f, _ = plot_connectivity_circle_edited(matrix_[index_][:,index_], names_lr[index_], node_colors=colors_lr[index_], node_size=2*size_w[index_]**2, con_thresh = 1.4, title=cond_, node_angles=circular_layout(names_lr, list(names_lr), ), fontsize_title=19, fontsize_names=13, fontsize_colorbar=13, colorbar_size=0.3, colormap='bwr', #colormap=cm_, vmin=-3., vmax=3., fig=pl.figure(figsize=(16,16)) ) fname = "%s_features_weight.png" %(prename) f.savefig(os.path.join(res_path, directory_, fname), facecolor='black', dpi=150) for d_ in ['x', 'y', 'z']: fname = "%s_connectome_feature_weight_%s.png" %(prename, d_) fname = os.path.join(res_path, directory_, fname) plot_connectome(matrix_, coords, colors_lr, 2*size_w**2, 1.4, fname, #cmap=pl.cm.bwr, title=None, display_=d_, #max_=3., #min_=3. ) fname = "%s_connections_list_feature_weights.txt" %(prename) fname = os.path.join(res_path, directory_, fname) #print_connections(matrix_, names_lr, fname) ######### mask_ = np.float_(~np.bool_(nan_mask)) mask_ = np.triu(mask_, k=1) mask_indices = np.nonzero(mask_) mask_[mask_indices] = h_values_ matrix_ = np.nan_to_num(copy_matrix(mask_, diagonal_filler=0)) size_ = np.zeros_like(matrix_) size_[mask_indices] = counting_vector size_ = np.nan_to_num(copy_matrix(size_, diagonal_filler=0)) size_ = np.sum(size_, axis=0) f, _ = plot_connectivity_circle_edited(matrix_[index_][:,index_], names_lr[index_], node_colors=colors_lr[index_], node_size=size_[index_]*5, con_thresh = 15., title=cond_, node_angles=circular_layout(names_lr, list(names_lr), ), fontsize_title=19, fontsize_names=13, fontsize_colorbar=13, colorbar_size=0.3, #colormap='bwr', #colormap='terrain', #vmin=40, fig=pl.figure(figsize=(16,16)) ) fname = "%s_features_choices.png" %(prename) f.savefig(os.path.join(res_path, directory_, fname), facecolor='black', dpi=150) for d_ in ['x', 'y', 'z']: fname = "%s_connectome_feature_choices_%s.png" %(prename, d_) fname = os.path.join(res_path, directory_, fname) plot_connectome(matrix_, coords, colors_lr, 4.*size_, 15., fname, title=None, max_=50., min_=0., display_=d_ ) fname = "%s_connections_list_feature_choices.txt" %(prename) fname = os.path.join(res_path, directory_, fname) #print_connections(matrix_, names_lr,fname) pl.close('all')