/
09_plot_clustering_results.py
467 lines (390 loc) · 17.7 KB
/
09_plot_clustering_results.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
"""
=====================================
Compute T-map for effect of condition
=====================================
Mass-univariate analysis of cue evoked activity.
Authors: José C. García Alanis <alanis.jcg@gmail.com>
License: BSD (3-clause)
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colorbar import ColorbarBase
from matplotlib.colors import Normalize
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mne.stats.cluster_level import _setup_adjacency, _find_clusters
from mne.channels import make_1020_channel_selections, find_ch_adjacency
from mne.evoked import EvokedArray
from mne import read_epochs, grand_average
from config import subjects, fname
# exclude subjects 51
subjects = subjects[subjects != 51]
###############################################################################
# 1) Load results of bootstrap procedure
# load f-max distribution
f_H0 = np.load(fname.results + '/f_H0_10000b_2t_m250_null_robust.npy')
# load cluster mass distribution
cluster_H0 = np.load(fname.results +
'/cluster_H0_10000b_2t_m250_null_robust.npy')
# also load individual beta coefficients
betas = np.load(fname.results + '/subj_betas_cue_m250_robust.npy')
r2 = np.load(fname.results + '/subj_r2_cue_m250_robust.npy')
###############################################################################
# 1) import epochs to use as template
# baseline to be applied
baseline = (-0.300, -0.050)
# import the output from previous processing step
input_file = fname.output(subject=subjects[0],
processing_step='cue_epochs',
file_type='epo.fif')
cue_epo = read_epochs(input_file, preload=True)
cue_epo = cue_epo['Correct A', 'Correct B'].copy()
cue_epo_nb = cue_epo.copy().crop(tmin=-0.250, tmax=2.450, include_tmax=False)
cue_epo = cue_epo.apply_baseline(baseline).crop(tmin=-0.300)
# save the generic info structure of cue epochs (i.e., channel names, number of
# channels, etc.).
epochs_info = cue_epo_nb.info
n_channels = len(epochs_info['ch_names'])
n_times = len(cue_epo_nb.times)
times = cue_epo_nb.times
tmin = cue_epo_nb.tmin
# split channels into ROIs for results section
selections = make_1020_channel_selections(epochs_info, midline='12z')
# placeholder for results
betas_evoked = dict()
r2_evoked = dict()
# ###############################################################################
# 2) loop through subjects and extract betas
for n_subj, subj in enumerate(subjects):
subj_beta = betas[n_subj, :]
subj_beta = subj_beta.reshape((n_channels, n_times))
betas_evoked[str(subj)] = EvokedArray(subj_beta, epochs_info, tmin)
subj_r2 = r2[n_subj, :]
subj_r2 = subj_r2.reshape((n_channels, n_times))
r2_evoked[str(subj)] = EvokedArray(subj_r2, epochs_info, tmin)
effect_of_cue = grand_average([betas_evoked[str(subj)] for subj in subjects])
cue_r2 = grand_average([r2_evoked[str(subj)] for subj in subjects])
###############################################################################
# 3) Plot beta weights for the effect of condition
# arguments fot the time-series maps
ts_args = dict(gfp=False,
time_unit='s',
ylim=dict(eeg=[-6.5, 6.5]),
xlim=[-.25, 2.5])
# times to plot
ttp = [0.20, 0.35, 0.60, 0.70, 1.00, 1.25, 2.35]
# arguments fot the topographical maps
topomap_args = dict(sensors=False,
time_unit='ms',
vmin=7, vmax=-7,
average=0.05,
extrapolate='head',
outlines='head')
# create plot
title = 'Regression coefficients (B - A, 64 EEG channels)'
fig = effect_of_cue.plot_joint(ttp,
ts_args=ts_args,
topomap_args=topomap_args,
title=title,
show=False)
fig.axes[-1].texts[0]._fontproperties._size = 12.0 # noqa
fig.axes[-1].texts[0]._fontproperties._weight = 'bold' # noqa
fig.axes[0].set_xticks(list(np.arange(-0.25, 2.55, 0.25)), minor=False)
fig.axes[0].set_yticks(list(np.arange(-6.0, 6.5, 3.0)), minor=False)
fig.axes[0].set_xticklabels(list(np.arange(-250, 2550, 250)))
fig.axes[0].set_xlabel('Time (ms)')
fig.axes[0].axhline(y=0.0, xmin=-0.5, xmax=2.5,
color='black', linestyle='dashed', linewidth=0.8)
fig.axes[0].axvline(x=0.0, ymin=-6.0, ymax=6.0,
color='black', linestyle='dashed', linewidth=0.8)
fig.axes[0].spines['top'].set_visible(False)
fig.axes[0].spines['right'].set_visible(False)
fig.axes[0].spines['left'].set_bounds(-6.0, 6.0)
fig.axes[0].spines['bottom'].set_bounds(-0.25, 2.5)
fig.axes[0].xaxis.set_label_coords(0.5, -0.2)
w, h = fig.get_size_inches()
fig.set_size_inches(w * 1.15, h * 1.15)
fig_name = fname.figures + '/Evoked_average_betas.pdf'
fig.savefig(fig_name, dpi=300)
###############################################################################
# 4) Plot R-squared for the effect of condition
# arguments fot the time-series maps
ts_args = dict(gfp=False,
time_unit='s',
unit=False,
ylim=dict(eeg=[-0.005, 0.06]),
xlim=[-0.25, 2.5])
# times to plot
ttp = [0.20, 0.35, 0.60, 0.70, 1.00, 1.25, 2.35]
# arguments fot the topographical maps
topomap_args = dict(cmap='magma_r',
scalings=dict(eeg=1),
sensors=False,
time_unit='ms',
vmin=0.0, vmax=0.06,
average=0.05,
extrapolate='head',
outlines='head')
# create R-squared plot
title = 'Proportion of variance explained by cue type'
fig = cue_r2.plot_joint(ttp,
ts_args=ts_args,
topomap_args=topomap_args,
title=title,
show=False)
fig.axes[-1].texts[0]._fontproperties._size = 12.0 # noqa
fig.axes[-1].texts[0]._fontproperties._weight = 'bold' # noqa
fig.axes[0].set_xticks(list(np.arange(-0.25, 2.55, 0.25)), minor=False)
fig.axes[0].set_xticklabels(list(np.arange(-250, 2550, 250)))
fig.axes[0].set_xlabel('Time (ms)')
fig.axes[0].set_yticks(list(np.arange(0.0, 0.065, 0.03)), minor=False)
fig.axes[0].axvline(x=0.0, ymin=0.0, ymax=1,
color='black', linestyle='dashed', linewidth=.8)
fig.axes[0].spines['top'].set_visible(False)
fig.axes[0].spines['right'].set_visible(False)
fig.axes[0].spines['left'].set_bounds(0.0, 0.06)
fig.axes[0].spines['bottom'].set_bounds(-0.25, 2.5)
fig.axes[0].xaxis.set_label_coords(0.5, -0.2)
fig.axes[0].set_ylabel('Average R-squared')
w, h = fig.get_size_inches()
fig.set_size_inches(w * 1.15, h * 1.15)
fig_name = fname.figures + '/Evoked_average_R2.pdf'
fig.savefig(fig_name, dpi=300)
###############################################################################
# 5) Estimate t-test based on original condition betas
se = betas.std(axis=0) / np.sqrt(betas.shape[0])
t_vals = betas.mean(axis=0) / se
f_vals = t_vals ** 2
# transpose for later clustering
t_clust = t_vals.reshape((n_channels, n_times))
f_clust = np.transpose(t_clust, (1, 0))
t_clust = f_clust.ravel()
# get upper CI bound from cluster mass H0
# (equivalent to alpha < 0.01 sig. level)
# f values above alpha level (based on f-max statistics)
sig_mask = f_vals > np.quantile(f_H0, [.99], axis=0)
# clusters threshold
cluster_thresh = np.quantile(cluster_H0, [0.99], axis=0)
# ###############################################################################
# 6) Plot results
# back projection to channels x time points
t_vals = t_vals.reshape((n_channels, n_times))
f_vals = f_vals.reshape((n_channels, n_times))
sig_mask = sig_mask.reshape((n_channels, n_times))
# create evoked object containing the resulting t-values
group_t = dict()
group_t['effect of cue (B-A)'] = EvokedArray(t_vals, epochs_info, tmin)
channels = group_t['effect of cue (B-A)'].ch_names
gfp_times = {'t1': [0.07, 0.07],
't2': [0.14, 0.11],
't3': [0.25, 0.14],
't4': [0.39, 0.36],
# 't5': [0.60, 0.15],
't6': [0.90, 0.20],
't7': [2.00, 0.45]}
# use viridis colors
colors = np.linspace(0, 1, len(gfp_times.values()))
cmap = cm.get_cmap('viridis')
# initialise plot
fig, ax = plt.subplots(figsize=(7, 11))
fig.subplots_adjust(
left=0.15, right=0.95, bottom=0.10, top=0.95, wspace=0.3, hspace=0.25)
font = 'Arial'
group_t['effect of cue (B-A)'].plot_image(xlim=[-0.250, 2.500],
clim=dict(eeg=[-12, 12]),
colorbar=False,
axes=ax,
mask=sig_mask,
mask_cmap='RdBu_r',
mask_alpha=0.5,
show=False,
unit=False,
# keep values scale
scalings=dict(eeg=1),
)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_bounds(0, 63)
ax.spines['left'].set_linewidth(1.5)
ax.spines['bottom'].set_bounds(-0.250, 2.500)
ax.spines['bottom'].set_linewidth(1.5)
# customize title and axis texts
title = 'Effect of cue (B-A)'
ax.set_title(title, fontname=font,
size=16.0, pad=15.0, fontweight='bold')
ax.set_ylabel('EEG sensors', fontname=font,
fontsize=14.0, labelpad=15.0, fontweight='bold')
ax.set_xlabel('Time (ms)', fontname=font,
fontsize=14.0, labelpad=15.0, fontweight='bold')
# Specify tick label size
ax.tick_params(axis='both', which='major', labelsize=12)
ax.tick_params(axis='both', which='minor', labelsize=8)
# add axis ticks
ax.set_xticks(list(np.arange(-.250, 2.550, .250)))
ax.set_xticklabels(list(np.arange(-250, 2550, 250)), rotation=45,
fontname=font)
ax.set_yticks(np.arange(0, len(channels), 5))
y_labs = [channels[i] for i in np.arange(0, len(channels), 5)]
ax.set_yticklabels(y_labs, fontname=font, fontweight='bold')
ax.set_yticks(np.arange(0, len(channels), 1), minor=True)
y_labs = [channels[i] for i in np.arange(0, len(channels), 1)]
ax.set_yticklabels(y_labs, fontname=font, minor=True)
ax.axvline(x=0, color='black', linestyle='dotted')
# if any additional text in fig
for text in ax.texts:
text.set_visible(False)
for i, val in enumerate(gfp_times.values()):
ax.add_patch(plt.Rectangle((val[0], -1.5), val[1], 1.0,
facecolor=cmap(colors[i]),
clip_on=False, linewidth=0, alpha=0.50))
fig.subplots_adjust(
left=0.15, right=0.95, bottom=0.15, wspace=0.3, hspace=0.25)
# initialise plot
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(23, 5.5))
# plot channel ROIs
for s, selection in enumerate(selections):
picks = selections[selection]
group_t['effect of cue (B-A)'].plot_image(xlim=[-0.25, 2.5],
picks=picks,
clim=dict(eeg=[-12, 12]),
colorbar=False,
axes=ax[s],
mask=sig_mask,
mask_cmap='RdBu_r',
mask_alpha=0.5,
show=False,
unit=False,
# keep values scale
scalings=dict(eeg=1)
)
# tweak plot appearance
if selection in {'Left', 'Right'}:
title = selection + ' hemisphere'
else:
title = 'Midline'
ax[s].title._text = title # noqa
ax[s].set_ylabel('Channels', labelpad=10.0,
fontsize=11.0, fontweight='bold')
ax[s].set_xlabel('Time (s)',
labelpad=10.0, fontsize=11.0, fontweight='bold')
ax[s].set_xticks(list(np.arange(-.25, 2.55, .25)), minor=False)
ax[s].set_xticklabels(list(np.arange(-250, 2550, 250)), rotation=45)
ax[s].set_xlabel('Time (ms)')
ax[s].set_yticks(np.arange(len(picks)), minor=False)
labels = [group_t['effect of cue (B-A)'].ch_names[i] for i in picks]
ax[s].set_yticklabels(labels, minor=False)
ax[s].spines['top'].set_visible(False)
ax[s].spines['right'].set_visible(False)
ax[s].spines['left'].set_bounds(-0.5, len(picks)-0.5)
ax[s].spines['bottom'].set_bounds(-.25, 2.5)
ax[s].texts = []
# add intercept line (at 0 s) and customise figure boundaries
ax[s].axvline(x=0, ymin=0, ymax=len(picks),
color='black', linestyle='dashed', linewidth=1.0)
colormap = cm.get_cmap('RdBu_r')
orientation = 'vertical'
norm = Normalize(vmin=-12.0, vmax=12.0)
divider = make_axes_locatable(ax[s])
cax = divider.append_axes('right', size='2.5%', pad=0.2)
cbar = ColorbarBase(cax, cmap=cm.get_cmap('RdBu_r'),
ticks=[-12.0, -6.0, 0.0, 6.0, 12.0], norm=norm,
label=r'Effect of cue (T-value B-A)',
orientation=orientation)
cbar.outline.set_visible(False)
cbar.ax.set_frame_on(True)
label = r'Difference B-A (in $\mu V$)'
for key in ('left', 'top',
'bottom' if orientation == 'vertical' else 'right'):
cbar.ax.spines[key].set_visible(False)
fig.subplots_adjust(
left=0.05, right=0.95, bottom=0.15, wspace=0.3, hspace=0.25)
# save figure
fig.savefig(fname.figures + '/T-map_image_effect_of_cue.pdf', dpi=300)
# # inspect topomaps
# group_t['effect of cue (B-A)'].plot_topomap(times=[0.20, 0.50, 1.3],
# average=0.1,
# mask=sig_mask,
# units=None,
# scalings=dict(eeg=1),
# outlines='head',
# sensors=True)
# ###############################################################################
# 7) Plot results
# set up channel adjacency matrix
n_tests = betas.shape[1]
adjacency, ch_names = find_ch_adjacency(epochs_info, ch_type='eeg')
adjacency = _setup_adjacency(adjacency, n_tests, n_times)
# threshold parameters for clustering
threshold = dict(start=0.2, step=0.2)
clusters, cluster_stats = _find_clusters(t_clust,
t_power=1,
threshold=threshold,
adjacency=adjacency,
tail=0)
# get significant clusters
cl_sig_mask = cluster_stats > cluster_thresh
cl_sig_mask = np.transpose(
cl_sig_mask.reshape((n_times, n_channels)), (1, 0))
cluster_stats = np.transpose(
cluster_stats.reshape((n_times, n_channels)), (1, 0))
# create evoked object containing the resulting t-values
cluster_map = dict()
cluster_map['ST-clustering effect of cue (B-A)'] = EvokedArray(cluster_stats,
epochs_info,
tmin)
# initialise plot
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(20, 5))
# plot channel ROIs
for s, selection in enumerate(selections):
picks = selections[selection]
effect_of_cue.plot_image(xlim=[-0.25, 2.5],
picks=picks,
clim=dict(eeg=[-5.0, 5.0]),
colorbar=False,
axes=ax[s],
mask=cl_sig_mask,
mask_cmap='RdBu_r',
mask_alpha=0.5,
show=False)
# tweak plot appearance
if selection in {'Left', 'Right'}:
title = selection + ' hemisphere'
else:
title = 'Midline'
ax[s].title._text = title # noqa
ax[s].set_ylabel('Channels', labelpad=10.0,
fontsize=11.0, fontweight='bold')
ax[s].set_xlabel('Time (s)',
labelpad=10.0, fontsize=11.0, fontweight='bold')
ax[s].set_xticks(list(np.arange(-.25, 2.55, .25)), minor=False)
ax[s].set_yticks(np.arange(len(picks)), minor=False)
labels = [cluster_map['ST-clustering effect of cue (B-A)'].ch_names[i]
for i in picks]
ax[s].set_yticklabels(labels, minor=False)
ax[s].spines['top'].set_visible(False)
ax[s].spines['right'].set_visible(False)
ax[s].spines['left'].set_bounds(-0.5, len(picks)-0.5)
ax[s].spines['bottom'].set_bounds(-.25, 2.5)
ax[s].texts = []
# add intercept line (at 0 s) and customise figure boundaries
ax[s].axvline(x=0, ymin=0, ymax=len(picks),
color='black', linestyle='dashed', linewidth=1.0)
colormap = cm.get_cmap('RdBu_r')
orientation = 'vertical'
norm = Normalize(vmin=-5.0, vmax=5.0)
divider = make_axes_locatable(ax[s])
cax = divider.append_axes('right', size='2.5%', pad=0.2)
cbar = ColorbarBase(cax, cmap=cm.get_cmap('RdBu_r'),
ticks=[-5.0, 0, 5.0], norm=norm,
label=r'Effect of cue (ß-weight B-A)',
orientation=orientation)
cbar.outline.set_visible(False)
cbar.ax.set_frame_on(True)
label = r'Difference B-A (in $\mu V$)'
for key in ('left', 'top',
'bottom' if orientation == 'vertical' else 'right'):
cbar.ax.spines[key].set_visible(False)
fig.subplots_adjust(
left=0.05, right=0.95, bottom=0.15, wspace=0.3, hspace=0.25)
# save figure
fig.savefig(fname.figures + '/Cluster-map_image_effect_of_cue.pdf', dpi=300)