def reg_single_channel_wrap(model, subs=cfg.subs, bands=cfg.bands, alpha=cfg.alpha, name=''): # load data df = cf.load_df(f"reg_{model['tag']}", bands=bands, subs=subs) # filter out not significant df = df.query(f'p<{alpha}') time_start = time.time() for i in range(len(df)): cf.display_progress( f"{df.iloc[i]['sub']} {df.iloc[i]['ch_name']} {df.iloc[i]['band']}", i, len(df), time_start) for predictor in model['predictors_stepwise']: if df.iloc[i]['p' + predictor] < alpha and df.iloc[i][ 'r2' + predictor] > 0: band = cfg.bands[[b['name'] for b in cfg.bands ].index(df.iloc[i]['band'])] reg_single_channel(df.iloc[i]['sub'], df.iloc[i]['ch_name'], band, model, plot=False) cf.concatenate_pdfs(cf.check_path( ['..', 'Figures' + cfg.out, f"reg_{model['tag']}"]), 'temp', f"single_channel_reg-{model['tag']}{name}.pdf", remove=True)
def channel_summary_plot(a, sub, ch_name, tag, predictors, bands=cfg.bands, alpha=cfg.alpha): # load data df = cf.load_df(f"reg_{tag}", bands=bands, subs=[sub]) # filter out regressions with negative score df = df.query(f"p<{alpha} and ch_name=='{ch_name}'") a.spines['right'].set_visible(False) a.spines['top'].set_visible(False) a.spines['bottom'].set_visible(False) a.spines['left'].set_visible(False) a.tick_params(axis='both', which='both', size=0, labelsize=7) a.set_yticks(range(len(bands))) a.set_yticklabels([band['name'] for band in bands]) a.set_xticks(range(len(predictors) + 1)) a.set_xticklabels(['full'] + [p for p in predictors], rotation=90) T = np.zeros((len(bands), len(predictors) + 1)) for i_band, band in enumerate(bands): df_band = df.query(f"band=='{band['name']}'") #print(df_band) try: T[i_band, 0] = df_band['t'] except: T[i_band, :] = -1 continue for i_p, pred in enumerate(predictors): #print(pred,df_band[f'p_{pred}'].values, df_band[f'p_{pred}'].values) T[i_band, i_p + 1] = df_band[f't{pred}'] if df_band.iloc[0][f'p{pred}'] > alpha: T[i_band, i_p + 1] = -1 #print(df_band.iloc[0][f'p_{pred}']>alpha) palette = copy.copy(plt.cm.viridis) palette.set_under('w', 1.0) im = a.imshow(T, vmin=0, vmax=0.6, cmap=palette) divider = make_axes_locatable(a) cax = divider.append_axes("right", size="2%", pad=0.05) cbar = plt.colorbar(im, cax=cax) cbar.ax.tick_params(labelsize=5, length=0) cbar.outline.set_visible(False) cbar.set_label('t (s)', rotation=90, fontsize=7)
def reg_clustering(model, predictors=[], subs=cfg.subs, bands=cfg.bands, alpha=cfg.alpha, name='', r2=1): # load data df = cf.load_df(f"reg_{model['tag']}", bands=bands, subs=subs) if predictors == 'all': predictors = model['predictors'] #keys = ['r2','p','t'] + ['dr2_'+p,'p_'+p,'t_'+p for p in predictors] keys = ['r2'] * r2 + ['dr2_' + p for p in predictors] ps = ['p'] * r2 + ['p_' + p for p in predictors] for i in range(len(keys)): X = [] for band in bands: df_band = df.query(f"band =='{band['name']}'") scores = df_band[keys[i]].values p_value = df_band[ps[i]].values p_value_full = df_band['p'].values X += [(p_value < alpha) * (p_value_full < alpha)] #x_ch += (scores*(p_values<alpha)*(p_values[0]<alpha)).tolist() #x_ch += (1.*(p_values<alpha)*(p_values[0]<alpha)).tolist() #x_ch += (-np.log10(p_values)*(p_values[0]<alpha)).tolist() X = np.array(X) # Standardize the data to have a mean of ~0 and a variance of 1 X = StandardScaler().fit_transform(X.T).T #C = np.corrcoef(X) C = np.cov(X) U, S, Vh = scipy.linalg.svd(C) #idx = np.argsort(C.mean(axis=0)) #idx = np.argsort(Vh[0,:]) idx = [0, 10, 8, 6, 9, 7, 5, 4, 3, 2, 1] fig, ax = plt.subplots(1, 2, figsize=(8, 3)) fig.suptitle(keys[i], fontsize=20) m = np.percentile(np.abs(C), 90) ax[0].imshow(C, vmin=-m, vmax=m, cmap='RdBu_r') #ax[0].imshow(C) ax[0].set_yticks(range(len(bands))) ax[0].set_yticklabels([band['name'] for band in bands]) ax[0].set_xticks(range(len(bands))) ax[0].set_xticklabels([band['name'] for band in bands], rotation=90) im = ax[1].imshow(C[idx, :][:, idx], vmin=-m, vmax=m, cmap='RdBu_r') #ax[1].imshow(C[idx,:][:,idx]) ax[1].set_yticks(range(len(bands))) ax[1].set_yticklabels([bands[i]['name'] for i in idx]) ax[1].set_xticks(range(len(bands))) ax[1].set_xticklabels([bands[i]['name'] for i in idx], rotation=90) divider = make_axes_locatable(ax[1]) cax = divider.append_axes("right", size="2%", pad=0.05) cbar = plt.colorbar(im, cax=cax) cbar.ax.tick_params(labelsize=10, length=0) cbar.outline.set_visible(False) cbar.set_label('corr coeff', rotation=90, fontsize=10) for a in ax: a.spines['right'].set_visible(False) a.spines['left'].set_visible(False) a.spines['top'].set_visible(False) a.spines['bottom'].set_visible(False) a.tick_params(axis='both', which='both', size=0, labelsize=10) fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.3, hspace=0.4) plt.show()
def reg_maps(model, predictors=[''], subs=cfg.subs, bands=cfg.bands, alpha=cfg.alpha, filter_tag='', fdr=False, plot=True, save=True, concat=True, time=True): """ Plot brain maps for variables (p_value, r2, ...) stored in files for each band Parameters ---------- alpha : float level of significance (leave out p>alpha) subs : list of str list of subjects to include f.e. [sub-01, sub-02] bands : list of dict list of bands to include """ print(f"\nBand comparison brain map for reg {model['tag']}") if predictors == 'all': predictors = [''] + model['predictors'] # load data df = cf.load_df(f"reg_{model['tag']}", bands=bands, subs=subs) # get total number of channels L = len(df[df['band'] == bands[0]['name']]) # filter out regressions with negative score df = df.query(f'r2>0 and p<{alpha}') if time: conditions, keys = [], [] for p in predictors: conditions += 2 * ['p' + p] keys += ['r2' + p, 't' + p] else: conditions = ['p' + p for p in predictors] keys = ['r2' + p for p in predictors] # loop over figures for i, (k, c) in enumerate(zip(keys, conditions)): print(i, k) fig, ax = plt.subplots(len(bands), 2, figsize=(12, 3 * len(bands)), gridspec_kw={'width_ratios': [3, 1]}) if len(bands) == 1: ax = np.array([ax]) fig.suptitle(fr"reg {model['tag']}, {k}, {c} $\leq {alpha}$", fontsize=20) for i_band, band in enumerate(bands): df_band = df[df['band'] == band['name']] if len(df_band) == 0: continue # extract data to plot x = df_band[k] coords = np.array([c for c in df_band['coords'].values]) pl.brain_plot(ax[i_band, 0], coords, x, ylabel=band['name'], mask=(df_band[c] > alpha), colorbar='' + (i_band == (len(bands) - 1)) * k, mode='interval', interval=[max(0, np.min(df[k])), np.max(df[k])]) s = df_band[df_band[c] < alpha][k] x = np.linspace(0, np.max(df[k]), 20) h, x = np.histogram(s, bins=x, density=False) ax[i_band, 1].bar(x[:-1] + .5 * (x[1] - x[0]), h, width=.8 * (x[1] - x[0])) ax[i_band, 1].set_xlabel(k) ax[i_band, 1].spines['right'].set_visible(False) ax[i_band, 1].spines['top'].set_visible(False) ax[i_band, 1].tick_params(axis='both', which='both', size=0, labelsize=9) if k != 'r2': L = len(df) ax[i_band, 1].set_title(f"{np.sum(h)}/{L} {int(100*np.sum(h)/L)}%") fig.subplots_adjust(left=0.1, right=0.9, hspace=0.5) if save: fig_name = os.path.join( cf.check_path( ['..', 'Figures' + cfg.out, f"reg_{model['tag']}"]), f"brain_map_reg_{model['tag']}_{str(i).zfill(2)}{'_temp'*concat}.pdf" ) fig.savefig(fig_name, format='pdf', dpi=100) if plot: plt.show() else: plt.close() if save and concat: cf.concatenate_pdfs(cf.check_path( ['..', 'Figures' + cfg.out, f"reg_{model['tag']}"]), 'temp', f"brain_map_reg-{model['tag']}.pdf", remove=True)
def reg_statistics(model, predictors=[''], subs=cfg.subs, bands=cfg.bands, alpha=cfg.alpha, filter_tag='', plot=True, save=True): # load data df = cf.load_df(f"reg_{model['tag']}", bands=bands, subs=subs) L = len(df) # filter out regressions with negative score df = df.query(f'r2>0 and p<{alpha}') if predictors == 'all': predictors = [''] + model['predictors'] keys = ['p' + p for p in predictors] conditions = ['r2' + p for p in predictors] fig, ax = plt.subplots(len(keys), 3, figsize=(12, 3 * len(keys)), gridspec_kw={'width_ratios': [1, 2, 0.5]}) if len(keys) == 1: ax = np.array([ax]) fig.suptitle(f"Regression stats summary", fontsize=15) colors = plt.get_cmap('viridis')(np.linspace(0, 1, len(bands))) for i, (k, c) in enumerate(zip(keys, conditions)): # scatter r2 vs p ------------------------------------------------------------- for i_band, band in enumerate(bands): ax[i, 0].scatter(df[df['band'] == band['name']][k], df[df['band'] == band['name']][c], c=[colors[i_band]], alpha=0.3) ax[i, 0].set_xlabel(k) ax[i, 0].set_ylabel(c) ax[i, 0].axvline(alpha, color='k', linewidth=0.5) ax[i, 0].axhline(0, color='k', linewidth=0.5) ax[i, 0].spines['right'].set_visible(False) ax[i, 0].spines['top'].set_visible(False) ax[i, 0].tick_params(axis='both', which='both', size=0, labelsize=9) # number of significant channels ---------------------------------------------- n = [] for sub in subs: # load subject params dp = cf.sub_params(sub) # significant channels for subjec-band pair n_sub = [] # iterate over bands ----------------------------------------------- for i_band, band in enumerate(bands): n_sub += [ np.sum( np.array(df[(df['sub'] == sub) & (df['band'] == band['name'])][k]) < alpha) ] # go to next band -------------------------------------------------- n += [n_sub] # go to next subject ====================================================== n = np.array(n).T # width and positions of bars width = 0.8 / len(bands) x = np.arange(len(subs)) colors = plt.get_cmap('viridis')(np.linspace(0, 1, len(bands))) for i_band, band in enumerate(bands): ax[i, 1].bar(x + i_band * width, n[i_band], width, color=colors[i_band]) ax[i, 2].bar(i_band * width, np.sum(n[i_band]), width, label=band['name'], color=colors[i_band]) ax[i, 1].set_ylabel("# significant channels") ax[i, 1].set_xticks(np.arange(len(subs)) + 0.4) ax[i, 1].set_xticklabels(subs, rotation=45) ax[i, 1].spines['right'].set_visible(False) ax[i, 1].spines['top'].set_visible(False) ax[i, 1].tick_params(axis='both', which='both', size=0, labelsize=9) ax[i, 2].set_xticks([0.4]) ax[i, 2].set_xlim([-0.2, 1]) ax[i, 2].set_xticklabels(['Total']) ax[i, 2].spines['right'].set_visible(False) ax[i, 2].spines['top'].set_visible(False) ax[i, 2].tick_params(axis='both', which='both', size=0, labelsize=9) if i > 0: L = len(df) ax[i, 2].set_title(f"{np.sum(n)}/{L} {int(100*np.sum(n)/L)}%") ax[0, 2].legend(frameon=False, loc=(1, 0.2), fontsize=9) fig.subplots_adjust(left=0.1, right=0.9, wspace=0.3, hspace=0.5) # save figure fig_name = os.path.join( cf.check_path(['..', 'Figures' + cfg.out, f"reg_{model['tag']}"]), f"stats_reg_{model['tag']}.pdf") if save: fig.savefig(fig_name, format='pdf', dpi=100) if plot: plt.show() else: plt.close()
def num_significant_channels(key, test, tag, split=None, alpha=sp.alpha, subs=sp.subject_list, bands=sp.bands): """ Make a bar plot with number of significant channels per subject per band for some test or regression Parameters ---------- key : str name of the column to extract test : str name of the test/regression that works as a label for files queries : dict generated with cf.compose_queries, contains mne queries, file tag, queries list split : int or str if int divide the time window into 'split' chunks and run one test in each if string separate epochs by values of metadata column 'split', f.ex. split = 'w_position' run the test for each word position alpha : float level of significance (leave out p>alpha) subs : list of str list of subjects to include f.e. [sub-01, sub-02] bands : list of dict list of bands to include """ print(f"\n{test} {tag} summary figure") df = cf.load_df(test + '_' + tag) if split == None: labels = [''] # no split elif isinstance(split, int): labels = list(np.unique(df['tw'].to_numpy())) # split by time windows elif isinstance(split, str): labels = list(np.unique(df[split].to_numpy())) # split by conditions num_plots = len(labels) fig, ax = plt.subplots(num_plots, 1, figsize=(len(subs), 3 * num_plots), sharex=True) fig.suptitle(fr"{test} {tag}, {key} $\leq {alpha}$") if split == None: ax = np.array([ax]) # loop over plots for i_plot, label in enumerate(labels): # number of significant channels n = [] for sub in subs: # load subject params dp = cf.sub_params(sub) # significant channels for subjec-band pair n_sub = [] # iterate over bands ----------------------------------------------- for i_band, band in enumerate(bands): if split == None: n_sub += [ np.sum( np.array(df[(df['sub'] == sub) & ( df['band'] == band['name'])][key]) < alpha) ] title = '' elif isinstance(split, int): n_sub += [ np.sum( np.array(df[ (df['sub'] == sub) & (df['band'] == band['name']) & ([x == label for x in df['tw'].to_numpy()])] [key]) < alpha) ] title = str(label) + ' s' elif isinstance(split, str): n_sub += [ np.sum( np.array(df[(df['sub'] == sub) & (df['band'] == band['name']) & (df[split] == label)][key]) < alpha) ] title = f"{split} = {label}" # go to next band -------------------------------------------------- n += [n_sub] # go to next subject ====================================================== n = np.array(n).T # width and positions of bars width = 0.8 / len(bands) x = np.arange(len(subs)) colors = plt.get_cmap('viridis')(np.linspace(0, 1, len(bands))) for i_band, band in enumerate(bands): ax[i_plot].bar(x + i_band * width, n[i_band], width, label=band['name'], color=colors[i_band]) ax[i_plot].set_ylabel("# significant channels") ax[i_plot].set_title(title) ax[i_plot].set_xticks(np.arange(len(subs)) + 0.4) ax[i_plot].set_xticklabels(subs) ax[i_plot].spines['right'].set_visible(False) ax[i_plot].spines['top'].set_visible(False) ax[i_plot].tick_params(axis='both', which='both', size=0, labelsize=9) ax[i_plot].legend(frameon=False, loc=(1, 0.2), fontsize=9) fig.subplots_adjust(right=0.8) # save figure fig_name = os.path.join(cf.check_path(['..', 'Figures', test + sp.out]), f"summary_{test}_{tag}_{key}.pdf") fig.savefig(fig_name, format='pdf', dpi=100) if sp.plot: plt.show() plt.close()
def band_comparison_matrix(key, file_tag, path, title='', label='', subs=sp.subject_list, bands=sp.bands, log10=False): """ Compare variables (p_value, r2, ...) between bands with scatter plots Parameters ---------- key : str name of the column to extract file_tag : str name of the figure will be brain_map_{file_tag}.pdf subs : list of str list of subjects to include f.e. [sub-01, sub-02] bands : list of dict list of bands to include """ print(f'\nBand comparison matrix for {file_tag}') if len(bands) == 1: sys.exit('At least 2 bands needed only 1 was passed') df = cf.load_df(file_tag, subs=subs, bands=bands) # fig 2: comparison accros bands --------------------------------------------------------------------- fig, ax = plt.subplots(len(bands) - 1, len(bands) - 1, figsize=(2.5 * (len(bands) - 1), 2.5 * (len(bands) - 1))) fig.suptitle(title, fontsize=20) clear_axes(ax) for i, band in enumerate(bands[:-1]): # data for first band x = df[df['band'] == band['name']][key] if log10: x = -np.log10(x) ax[-1, i].set_xlabel(band['name']) ax[i, 0].set_ylabel(bands[i + 1]['name']) # comparison across bands for j in range(i, len(bands) - 1): y = df[df['band'] == bands[j + 1]['name']][key] if log10: y = -np.log10(y) ax[j, i].scatter(x, y) #ax[j,i].hist2d(x,y,bins=np.linspace(min(x.min(),y.min()),max(x.max(),y.max()),10),cmap='Reds') # draw diagonal line ax[j, i].axis('equal') ax[j, i].plot([0, 1], [0, 1], 'k--', transform=ax[j, i].transAxes) ax[j, i].spines['left'].set_visible(True) ax[j, i].spines['bottom'].set_visible(True) #ax[i,j].set_xlim([0,np.log10(sp.n_permutations)]) #ax[i,j].set_ylim([0,np.log10(sp.n_permutations)]) #ax[i,j].set_xticks([0,1,2]) #ax[i,j].set_yticks([0,1,2]) fig.subplots_adjust(left=0.05, bottom=0.05, right=0.95, top=0.95, wspace=0.3, hspace=0.3) # save figure fig_name = os.path.join(cf.check_path(path), f"matrix_{file_tag}.pdf") fig.savefig(fig_name, format='pdf', dpi=100) if sp.plot: plt.show() plt.close()
def band_comparison_lateralization(key, test, tag, split=None, alpha=sp.alpha, subs=sp.subject_list, bands=sp.bands): """ Bar plots for proportion of significant channels on left right axis and frontal occipital axis Parameters ---------- key : str name of the column to extract test : str name of the test/regression that works as a label for files tag : str test tag alpha : float level of significance (leave out p>alpha) subs : list of str list of subjects to include f.e. [sub-01, sub-02] bands : list of dict list of bands to include """ print(f"\nLateralization figure for {test} {tag}") df = cf.load_df(f"{test}_{tag}", subs=subs, bands=bands) if split == None: labels = [''] # no split elif isinstance(split, int): labels = list(np.unique(df['tw'].to_numpy())) # split by time windows elif isinstance(split, str): labels = list(np.unique(df[split].to_numpy())) # split by conditions num_plots = len(labels) if len(sp.bands) == 1: ax = ax[np.newaxis, :] # loop over plots for i_plot, label in enumerate(labels): fig, ax = plt.subplots(len(bands), 2, figsize=(5, 3 * len(bands))) fig.suptitle(fr"{test} {tag}, $p \leq {alpha}$", fontsize=20) # for axis limits x, y = 0, 0 for i_band, band in enumerate(bands): # filter df by band and split if split == None: df_band = df[df['band'] == band['name']] title = '' figtag = '' elif isinstance(split, int): df_band = df[(df['band'] == band['name']) & ([x == label for x in df['tw'].to_numpy()])] title = '' + (str(label) + ' s') * (i_band == 0) figtag = f'_tw{i_plot}' elif isinstance(split, str): df_band = df[(df['band'] == band['name']) & (df[split] == label)] title = '' + f"{split} = {label}" * (i_band == 0) figtag = f"_{split}-{label}" df_sig = df_band[df_band[key] <= alpha] # get channel positions coords_all = np.array([c for c in df_band['coords']]) coords_sig = np.array([c for c in df_sig['coords']]) # skip if there aren't significant channels if len(coords_sig.shape) != 2: continue # left rigth h_all, bins = np.histogram(coords_all[:, 0], bins=6, density=False) h_sig, bins = np.histogram(coords_sig[:, 0], bins=bins, density=False) width = (bins[1] - bins[0]) ax[i_band, 0].bar(bins[:-1] + width / 2, h_sig / h_all, width=width * 0.9, color='firebrick') ax[i_band, 0].set_xticks([bins[0], bins[-1]]) ax[i_band, 0].set_xticklabels(['L', 'R']) #ax[i_band,0].set_ylim([0,1]) ax[i_band, 0].spines['right'].set_visible(False) ax[i_band, 0].spines['top'].set_visible(False) ax[i_band, 0].tick_params(axis='both', which='both', size=0, labelsize=9) y = max(y, np.max(h_sig / h_all)) # frontal occipital h_all, bins = np.histogram(coords_all[:, 1], bins=6, density=False) h_sig, bins = np.histogram(coords_sig[:, 1], bins=bins, density=False) width = (bins[1] - bins[0]) ax[i_band, 1].barh(bins[:-1] + width / 2, h_sig / h_all, height=width * 0.9, color='firebrick') ax[i_band, 1].set_yticks([bins[0], bins[-1]]) ax[i_band, 1].set_yticklabels(['O', 'F']) #ax[i_band,1].set_xlim([0,1]) ax[i_band, 1].spines['right'].set_visible(False) ax[i_band, 1].spines['top'].set_visible(False) ax[i_band, 1].tick_params(axis='both', which='both', size=0, labelsize=9) x = max(x, np.max(h_sig / h_all)) for i_band in range(len(bands)): ax[i_band, 0].set_ylim([0, y]) ax[i_band, 1].set_xlim([0, x]) fig.subplots_adjust(left=0.1, bottom=0.15, right=0.95, top=0.85, wspace=0.4, hspace=0.4) # save figure fig_name = os.path.join( cf.check_path(['..', 'Figures', f"{test}_{tag}" + sp.out]), f"lateralization_{test}_{tag}_{key}.pdf") fig.savefig(fig_name, format='pdf', dpi=100) if sp.plot: plt.show() plt.close()
def contrast(key1, key2, test1, test2, model1, model2, alpha=sp.alpha, subs=sp.subject_list, bands=sp.bands, plot=True, save=True): """ Plot brain maps for variables (p_value, r2, ...) stored in files for each band Parameters ---------- key : str name of the column to extract test : str name of the test/regression that works as a label for files model1, model2 : dict contains mne queries, file tag alpha : float level of significance (leave out p>alpha) subs : list of str list of subjects to include f.e. [sub-01, sub-02] bands : list of dict list of bands to include """ print(f"\nContrast {test1} {model1['tag']} {test2} {model2['tag']}") df1 = cf.load_df(f"{test1}_{model1['tag']}", subs=subs, bands=bands) df2 = cf.load_df(f"{test2}_{model2['tag']}", subs=subs, bands=bands) fig, ax = plt.subplots(len(bands), 1, figsize=(10, 3 * len(bands))) if len(bands) == 1: ax = np.array([ax]) fig.suptitle( fr"{test1} {key1} {model1['tag']} vs {test2} {key3} {model2['tag']}, $p \leq {alpha}$", fontsize=20) for i_band, band in enumerate(bands): df1_band = df1[df1['band'] == band['name']] df2_band = df2[df2['band'] == band['name']] mask1 = df1_band[key].values < alpha mask2 = df2_band[key].values < alpha # for regression results filter significant channels if test == 'reg': mask1 *= (df1_band['r2'].values > 0) * (df1_band['p'].values < alpha) mask2 *= (df2_band['r2'].values > 0) * (df2_band['p'].values < alpha) x = 1. * mask1 + 2 * mask2 cb = '' if i_band == len(bands) - 1: cb = [model1['tag'], model2['tag'], 'both'] pl.brain_plot(ax[i_band], cf.eval_coords(df1_band['coords']), x, ylabel=band['name'], mask=(x < 0.5), mode='contrast', colorbar=cb) #fig.subplots_adjust(left=0.05, bottom=0.05, right=0.9, top=0.9, wspace=0.3, hspace=0.3) # save figure if save: fig_name = os.path.join( cf.check_path(['..', 'Figures', test1 + sp.out]), f"contrast_{test1}-{model1['tag']}_{test2}-{model2['tag']}.pdf") fig.savefig(fig_name, format='pdf', dpi=100) if plot: plt.show() else: plt.close()
def band_comparison_brain(key, test, file_tag, split=None, alpha=sp.alpha, subs=sp.subject_list, bands=sp.bands): """ Plot brain maps for variables (p_value, r2, ...) stored in files for each band Parameters ---------- key : str name of the column to extract test : str name of the test/regression that works as a label for files queries : dict generated with cf.compose_queries, contains mne queries, file tag, queries list split : int or str if int divide the time window into 'split' chunks and run one test in each if string separate epochs by values of metadata column 'split', f.ex. split = 'w_position' run the test for each word position alpha : float level of significance (leave out p>alpha) subs : list of str list of subjects to include f.e. [sub-01, sub-02] bands : list of dict list of bands to include """ print(f"\nBand comparison brain map for {test} {file_tag}") df = cf.load_df(f"{test}-{file_tag}", subs=subs, bands=bands) if split == None: labels = [''] # no split elif isinstance(split, int): labels = list(np.unique(df['tw'].to_numpy())) # split by time windows elif isinstance(split, str): labels = list(np.unique(df[split].to_numpy())) # split by conditions num_plots = len(labels) # threshold is given in units of p, has to be transformed if key[0] == 'p': alpha = -np.log10(alpha) if len(sp.bands) == 1: ax = ax[np.newaxis, :] # loop over plots for i_plot, label in enumerate(labels): fig, ax = plt.subplots(len(bands), 1, figsize=(10, 3 * len(bands))) fig.suptitle(fr"{test} {file_tag}, $p \leq {alpha}$", fontsize=20) for i_band, band in enumerate(bands): # filter df by band and split if split == None: df_band = df[df['band'] == band['name']] title = '' figtag = '' elif isinstance(split, int): df_band = df[(df['band'] == band['name']) & ([x == label for x in df['tw'].to_numpy()])] title = '' + (str(label) + ' s') * (i_band == 0) figtag = f'_tw{i_plot}' elif isinstance(split, str): df_band = df[(df['band'] == band['name']) & (df[split] == label)] title = '' + f"{split} = {label}" * (i_band == 0) figtag = f"_{split}-{label}" # extract data to plot x = df_band[key] # for p values if key[0] == 'p': # transform p values and threshold x = -np.log10(x) cbar_label = r'-log$_{10}(p)$' # get channel positions coords = np.array([c for c in df_band['coords']]) pl.brain_plot(ax[i_band], coords, np.clip(x, alpha, 3), title=title, ylabel=band['name'], colorbar='' + (i_band == (len(bands) - 1)) * cbar_label, mask=(x < alpha), mode='interval', interval=[alpha, 3]) #fig.subplots_adjust(left=0.05, bottom=0.05, right=0.9, top=0.9, wspace=0.3, hspace=0.3) # save figure fig_name = os.path.join( cf.check_path(['..', 'Figures', test + sp.out]), f"brain_map_{test}_{file_tag}{figtag}.pdf") fig.savefig(fig_name, format='pdf', dpi=100) if sp.plot: plt.show() plt.close()