#p4f, p4ax = plt.subplots(4, 4, sharex=True, sharey=True) for m, metric_type in enumerate( ['magnitude', 'n_spindles', 'amplitude', 'duration']): for k, fb_type in enumerate(['FB0', 'FB250', 'FB500', 'FBMock']): results = smf.ols( 'np.log(env) ~ k:fb_type + C(channel) + C(subj_id) - 1', data=y_df.query( 'fb_type == "{}" & subj_id!="s11" & metric_type=="{}"'.format( fb_type, metric_type))).fit() ax[m, k].set_title('{}\n{}'.format(fb_type, metric_type)) print(results.summary()) indx = [ CHANNELS.index(chn.split('[')[1].split(']')[0]) for c, chn in enumerate(results.params.index) if 'channel' in chn ] im = plot_topomap( np.exp(results.params[:32] - max(results.params[:32])) * (np.exp(results.params[-1])), MONTAGE.get_pos()[indx], vmin=0, vmax=1.2, axes=ax[m, k], show=False, cmap='inferno', contours=[1.25]) plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9) cax = plt.axes([0.85, 0.1, 0.075, 0.8]) plt.colorbar(im[0], cax=cax)
data = y_df.query('metric_type == "{}"'.format(metric_type)) md = sm.MixedLM.from_formula("np.log(env) ~ k:fb_type:channel", data, groups=data["subj_id"], re_formula='1+k:channel:fb_type') results = md.fit() print(results.summary()) #topo0 = np.exp([results.params['channel[T.{}]'.format(ch)] if ch !='C3' else 0 for ch in CHANNELS]) topo_fb0 = np.exp([ results.params['k:fb_type[FBMock]:channel[{}]'.format(ch)] for ch in CHANNELS ]) plot_topomap(topo_fb0, MONTAGE.get_pos(), vmin=0, vmax=1) md = sm.MixedLM.from_formula("np.log(env) ~ channel + k:fb_type:channel", data, groups=data["subj_id"], re_formula='1') results = md.fit() print(results.summary()) m = sm.OLS.from_formula( 'env ~ fb_type*channel', data=y_df.query('metric_type == "n_spindles" & k==0')).fit() #m1 = sm.OLS.from_formula('env ~ fb_type:k', data=y_df.query('metric_type == "n_spindles" & channel=="P4"')).fit() print(m.summary()) from statsmodels.stats.anova import anova_lm anova_lm(m)
axis_spinecolor='white'): curves = {} for f, fb_type in enumerate(['FB0', 'FB250', 'FB500', 'FBMock']): curves[fb_type] = y_df.query( 'metric_type=="{}" & fb_type=="{}" & channel=="{}"'.format( metric_type, fb_type, CHANNELS[idx])).groupby('k').median()['env'].values curves_array[f, idx, :] = curves[fb_type] ax.plot(curves['FB0'] - curves['FBMock'] * 0) ax.plot(curves['FB250'] - curves['FBMock'] * 0) ax.plot(curves['FB500'] - curves['FBMock'] * 0) ax.plot(curves['FBMock']) ax.set_xlabel(CHANNELS[idx]) ax.axhline(0, color='k', alpha=0.3) if idx > 0: ax.get_shared_x_axes().join(prev_ax, ax) ax.get_shared_y_axes().join(prev_ax, ax) prev_ax = ax #ax.set_ylim(0, y_df.query('metric_type=="{}"'.format(metric_type))['env'].max()) plt.gcf().suptitle(metric_type) plt.show() fig, axes = plt.subplots(4) for f, fb_type in enumerate(['FB0', 'FB250', 'FB500', 'FBMock']): plot_topomap(curves_array[f].mean(1), MONTAGE.get_pos(), 0, curves_array.mean(2).max(), axes=axes[f], show=False, cmap='inferno')
for c, comp in enumerate(all_stats_df['Contrast'].unique()): for m, metric_type in enumerate(['magnitude', 'n_spindles', 'duration', 'amplitude']): comp_df = all_stats_df.query('metric_type=="{}" & Contrast == "{}"'.format(metric_type, comp)) data_t[b, c, m] = np.array([comp_df.query('channel == "{}" & band=="{}"'.format(ch, band))['T-stat'].values[0] for ch in CHANNELS]) data[b, c, m] = np.array([stats.t.sf(comp_df.query('channel == "{}" & band=="{}"'.format(ch, band))['T-stat'].values[0], 9) for ch in CHANNELS]) data = fdr_correction(data, 0.05)[1] fig, axes = plt.subplots(3*4, 6) col_order = {'FB0 - FBMock': 0, 'FB250 - FBMock': 1, 'FB500 - FBMock': 2, 'FB0 - FB250': 3, 'FB0 - FB500': 4, 'FB250 - FB500': 5} for b, band in enumerate(['alpha', 'beta', 'theta']): for c, comp in enumerate(all_stats_df['Contrast'].unique()): for m, metric_type in enumerate(['magnitude', 'n_spindles', 'duration', 'amplitude']): d = np.log10(data[b, c, m]) d[(data_t[b, c, m] > 0)] *= -1 im=plot_topomap(d, MONTAGE.get_pos(), axes=axes[m+4*b, col_order[comp]], show=False, vmin=-4, vmax=4, cmap='RdBu_r', contours=[np.log10(0.05), -np.log10(0.05)]) axes[m+4*b, col_order[comp]].set_title('{}\n{}\n{}'.format(band, metric_type, comp)) plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9) cax = plt.axes([0.85, 0.1, 0.075, 0.8]) b = plt.colorbar(im[0], cax=cax) b.set_ticks([np.log10(0.05), -np.log10(0.05), 0, np.log10(0.01), -np.log10(0.01), np.log10(0.001), -np.log10(0.001)]) b.set_ticklabels([ '* (<)', '* (>)', 'ns', '** (<)', '** (>)', '*** (<)', '*** (>)']) cax.set_title('p-value') col_order = {'FB0 - FBMock': 0, 'FB250 - FBMock': 1, 'FB500 - FBMock': 2, 'FB0 - FB250': 3, 'FB0 - FB500': 4, 'FB250 - FB500': 5} for b, band in enumerate(['alpha', 'beta', 'theta']):
import pandas as pd from scipy import stats import seaborn as sns import numpy as np from scipy.stats import rankdata import pylab as plt from proc.settings import FB_ALL from proc.settings import CHANNELS, MONTAGE from mne.viz import plot_topomap from tqdm import tqdm import scipy.signal as sg from itertools import combinations poses = MONTAGE.get_pos() def ranksums(x, y): x, y = map(np.asarray, (x, y)) n1 = len(x) n2 = len(y) alldata = np.concatenate((x, y)) ranked = rankdata(alldata) x = ranked[:n1] s = np.sum(x, axis=0) return s all_stats_df = pd.read_pickle('data/metrics_chs_ica_all.pkl') all_stats_df = all_stats_df.loc[all_stats_df['block_number'].isin(FB_ALL)] all_stats_df = all_stats_df.loc[all_stats_df['channel'].isin(CHANNELS)] all_stats_df = all_stats_df.loc[all_stats_df['threshold_factor'].isin([2])]
#axes[f, s].plot(np.arange(30)*lin_r.slope + lin_r.intercept) if s == 9: axes[0, s+1].plot(np.median(curves[f, :, c], 0)) if f > 0: axes[f, s + 1].plot(np.median(curves[f, :, c], 0)) vmax = 10 fig, axes = plt.subplots(4, 11) pers = 0.5/29*10000 for f in range(4): for s in range(10): plot_topomap(slopes[f, s], MONTAGE.get_pos(), mask=slopes[f, s]>pers, axes=axes[f, s], cmap='viridis', vmin=0, vmax=np.percentile(slopes, 90), contours=0) plot_topomap(np.median(slopes[f], 0), MONTAGE.get_pos(), mask=np.median(slopes[f], 0)>pers, axes=axes[f, -1], cmap='viridis', vmin=0, vmax=np.percentile(slopes, 90), contours=0) vmax = 10 fig, axes = plt.subplots(4, 11) pers = 0.5/29*10000 for f in range(4): for s in range(10): plot_topomap(curves[f, s].mean(1), MONTAGE.get_pos(), axes=axes[f, s], cmap='viridis', vmin=0, vmax=0.5, contours=0) pvals = np.array([ttest_1samp(np.mean(curves[f, :, c], 1), 0) for c in range(32)]) plot_topomap(np.mean(curves[f], 0).mean(1), MONTAGE.get_pos(), axes=axes[f, -1], mask=pvals<0.01, cmap='viridis', vmin=0, vmax=0.5, contours=0)
res = get_slope(y[:, np.random.randint(0, 10, 10)]) print(res.fun, res.x[-1] * 29 * 100) topos.append(res.x[10:10 + 32]) funs.append(res.fun) slopes.append(res.x[-1]) plt.figure() wean = lambda x, a: np.sum([topo * 1 / fun for topo, fun in zip(x, funs)], 0 ) / np.sum(1 / np.array(funs), a) indx = [ CHANNELS.index(chn) for c, chn in enumerate(all_stats_df['channel'].unique()) ] plot_topomap(wean(topos, 0), MONTAGE.get_pos()[indx], vmin=0, vmax=1) plt.title('{}\n{} +- {}'.format( fb_type, int(wean(slopes, 0) * 29 * 100), int(wean((np.array(slopes) - wean(slopes, 0))**2, 0)**0.5 * 29 * 100))) plt.tight_layout() fig, axes = plt.subplots(11, sharey=True, sharex=True) for c in np.arange(32): for s in range(10): axes[s].plot( np.arange(30) / 30 + c, (y[:, s, c] - res.x[s]) / res.x[10 + c] / res.x[10 + 32 + s] - 1, 'b') axes[s].plot(np.arange(30) / 30 + c, np.arange(30) * res.x[-1], 'r') axes[0].set_ylim(-1, 1)