-
Notifications
You must be signed in to change notification settings - Fork 0
/
4_plotting.py
1513 lines (1337 loc) · 60.6 KB
/
4_plotting.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import os.path as op
import numpy as np
import pandas as pd
import mne
from mne.gui._ieeg_locate import _CMAP
import nibabel as nib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib import patheffects
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.colors import Normalize
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from scipy import stats
from utils import load_raw, compute_tfr, DESTRIEUX_DICT
from params import PLOT_DIR as plot_dir
from params import BIDS_ROOT as bids_root
from params import EXTENSIONS as exts
from params import EVENTS as event_dict
from params import SUBJECTS as subjects
from params import TASK as task
from params import TEMPLATE as template
from params import ATLASES as asegs
from params import ALPHA as alpha
from params import LEFT_HANDED_SUBJECTS as lh_sub
from params import FREQUENCIES as freqs
from params import EXCLUDE_CH as exclude_ch
freqs = np.array([0] + list(freqs)) # add evoked
def swarm(x, bins): # plot helper function
counts = np.ones((bins.size))
y = np.zeros((len(x)))
for i, this_x in enumerate(x):
idx = np.where(this_x < bins)[0][0] - 1
y[i] = counts[idx] // 2 if counts[idx] % 2 else -counts[idx] // 2
counts[idx] += 1
return y
fig_dir = op.join(plot_dir, 'derivatives', 'plots')
data_dir = op.join(bids_root, 'derivatives', 'analysis_data')
if not op.isdir(fig_dir):
os.makedirs(fig_dir)
# get plotting information
subjects_dir = op.join(bids_root, 'derivatives', 'freesurfer-7.3.2')
ieeg_dir = op.join(bids_root, 'derivatives', 'mne-ieeg')
brain_kwargs = dict(cortex='low_contrast', alpha=0.2, background='white',
subjects_dir=subjects_dir, units='m')
template_brain_kwargs = dict(
brain_kwargs, subjects_dir=os.environ['SUBJECTS_DIR'])
lut, colors = mne._freesurfer.read_freesurfer_lut()
cmap = plt.get_cmap('viridis')
template_subjects_dir = op.join(
os.environ['FREESURFER_HOME'], 'subjects')
template_trans = mne.coreg.estimate_head_mri_t(
template, template_subjects_dir)
# get svm information
scores, clusters, images, pca_vars, svm_coef = \
({event: dict() for event in ('event', 'go_event', 'null')}
for _ in range(5))
for sub in subjects:
print(f'Loading subject {sub} data')
with np.load(op.join(data_dir, f'sub-{sub}_pca_svm_data.npz'),
allow_pickle=True) as data:
for event in ('event', 'go_event', 'null'):
scores[event].update(data['scores'].item()[event])
clusters[event].update(data['clusters'].item()[event])
images[event].update(data['images'].item()[event])
pca_vars[event].update(data['pca_vars'].item()[event])
svm_coef[event].update(data['svm_coef'].item()[event])
# exclude epileptogenic contacts
for name in exclude_ch:
for event in ('event', 'go_event', 'null'):
if name not in scores[event]:
print(f'{name} not found')
continue
scores[event].pop(name)
clusters[event].pop(name)
images[event].pop(name)
pca_vars[event].pop(name)
svm_coef[event].pop(name)
for event in ('event', 'go_event', 'null'):
print('Event {} variance explained {}+/-{}'.format(
event,
np.mean(np.sum(np.array(list(pca_vars[event].values())), axis=1)),
np.std(np.sum(np.array(list(pca_vars[event].values())), axis=1))))
spec_shape = images['event'][list(images['event'].keys())[0]].shape
times = {'event': np.linspace(-0.5, 0.5, spec_shape[1]),
'go_event': np.linspace(0, 1, spec_shape[1])}
# compute significant indices pooled across subjects
sig_thresh = np.quantile(list(scores['null'].values()), 1 - alpha)
not_sig = {event: [name for name, score in scores['event'].items()
if score <= sig_thresh]
for event in ('event', 'go_event')}
sig = {event: [name for name, score in scores['event'].items()
if score > sig_thresh]
for event in ('event', 'go_event')}
# compute null distribution thresholds per image
image_thresh = np.quantile(
abs(np.array(list(images['null'].values()))), 1 - alpha)
# feature map computation
feature_maps = {'event': np.zeros((3, 2) + spec_shape),
'go_event': np.zeros((3, 2) + spec_shape)}
for event in feature_maps:
for name, image in images[event].items():
ch_cluster = clusters[event][name]
score = scores[event][name]
if score > sig_thresh:
feature_maps[event][0, 0] += abs(image) > image_thresh # count
feature_maps[event][1, 0] += image > image_thresh
feature_maps[event][2, 0] += score * (abs(image) > image_thresh)
feature_maps[event][0, 1] += ~np.isnan(ch_cluster)
feature_maps[event][1, 1] += ~np.isnan(ch_cluster) * ch_cluster > 0
feature_maps[event][2, 1] += score * ~np.isnan(ch_cluster)
# normalize
feature_maps[event][1, 0] /= feature_maps[event][0, 0] # scale by count
feature_maps[event][2, 0] /= feature_maps[event][0, 0] # scale by count
feature_maps[event][0, 0] /= feature_maps[event][0, 0].max()
feature_maps[event][1, 1] /= feature_maps[event][0, 1] # scale by count
feature_maps[event][2, 1] /= feature_maps[event][0, 1] # scale by count
feature_maps[event][0, 1] /= feature_maps[event][0, 1].max()
# time-frequency areas of interest
prop_thresh = 1 / 3
areas = {'Pre-Movement Beta': (1, 22, 37, -0.35, -0.05),
'Delta': (0, 1, 4, -0.5, 0.25),
'Event-Related Potential': (0, 0, 0, -0.5, 0.5),
'Post-Movement High-Beta': (1, 27, 36, 0.05, 0.2),
'Post-Movement Low-Beta': (1, 14, 23, 0.1, 0.25),
'Post-Movement Gamma': (0, 43, 140, 0.1, 0.23),
'Pre-Movement Alpha': (0, 7, 13, -0.25, 0)}
area_directions = {'Pre-Movement Beta': (-1,), 'Delta': (1,),
'Event-Related Potential': (-1, 1),
'Post-Movement High-Beta': (1,),
'Post-Movement Low-Beta': (1,),
'Post-Movement Gamma': (1,),
'Pre-Movement Alpha': (-1, 1)}
area_contacts = {'event': {area: dict() for area in areas},
'go_event': {area: dict() for area in areas}}
for event in area_contacts:
for name, cluster in clusters[event].items():
mask = ~np.isnan(cluster) * np.sign(cluster)
for area, (fm_idx, fmin, fmax, tmin, tmax) in areas.items():
fmin_idx = np.argmin(abs(freqs - fmin))
fmax_idx = np.argmin(abs(freqs - fmax))
tmin_idx = np.argmin(abs(times[event] - tmin))
tmax_idx = np.argmin(abs(times[event] - tmax))
this_area = mask[slice(fmin_idx, fmax_idx + 1),
slice(tmin_idx, tmax_idx + 1)]
area_contacts[event][area][name] = \
np.nansum(this_area) / this_area.size
# channel positions in template and individual
ch_pos = {'template': dict(), 'individual': dict()}
for sub in subjects: # first, find associated labels
# individual
info = mne.io.read_info(op.join(
ieeg_dir, f'sub-{sub}', 'ieeg',
f'sub-{sub}_task-{task}_info.fif'))
montage = mne.channels.make_dig_montage(
dict(zip(info.ch_names, [ch['loc'][:3] for ch in info['chs']])),
coord_frame='head')
trans = mne.coreg.estimate_head_mri_t(f'sub-{sub}', subjects_dir)
montage.apply_trans(trans)
pos = montage.get_positions()['ch_pos']
for ch_name, this_pos in pos.items():
ch_name = ch_name.replace(' ', '')
ch_pos['individual'][f'sub-{sub}_ch-{ch_name}'] = this_pos
# template
info = mne.io.read_info(op.join(
ieeg_dir, f'sub-{sub}', 'ieeg',
f'sub-{sub}_template-{template}_task-{task}_info.fif'))
montage = mne.channels.make_dig_montage(
dict(zip(info.ch_names, [ch['loc'][:3] for ch in info['chs']])),
coord_frame='head')
montage.apply_trans(template_trans)
pos = montage.get_positions()['ch_pos']
for ch_name, this_pos in pos.items():
ch_name = ch_name.replace(' ', '')
ch_pos['template'][f'sub-{sub}_ch-{ch_name}'] = this_pos
ignore_keywords = ('unknown', '-vent', 'choroid-plexus', 'vessel',
'white-matter', 'wm-', 'cc_', 'cerebellum',
'brain-stem')
# get data for removing multiple
aseg_data = list()
aseg_trans = list()
for aseg in asegs:
aseg_obj = nib.load(op.join(
template_subjects_dir, template, 'mri', aseg + '.mgz'))
aseg_data.append(np.array(aseg_obj.dataobj))
aseg_trans.append(np.linalg.inv(aseg_obj.header.get_vox2ras_tkr()))
ch_labels = {aseg: dict() for aseg in asegs}
for sub in subjects: # first, find associated labels
info = mne.io.read_info(op.join(
ieeg_dir, f'sub-{sub}', 'ieeg',
f'sub-{sub}_task-{task}_info.fif'))
trans = mne.coreg.estimate_head_mri_t(f'sub-{sub}', subjects_dir)
montage = mne.channels.make_dig_montage(
dict(zip(info.ch_names, [ch['loc'][:3] for ch in info['chs']])),
coord_frame='head')
montage.apply_trans(trans)
for aseg, aseg_lut, this_aseg_trans in zip(asegs, aseg_data, aseg_trans):
sub_labels = mne.get_montage_volume_labels(
montage, f'sub-{sub}', subjects_dir=subjects_dir,
aseg=aseg, dist=2)[0]
for ch_name, labels in sub_labels.items():
ch_name_fix = ch_name.replace(' ', '')
for label in labels.copy():
if 'unknown' in label.lower():
labels.remove(label)
# fix multiple
if len(labels) > 1:
labels_filtered = [label for label in labels if not
any([kw in label.lower()
for kw in ignore_keywords])]
if len(labels_filtered) >= 1: # assign gray matter first
labels = labels_filtered
this_pos = montage.get_positions()['ch_pos'][ch_name]
min_dists = list()
for label in labels:
min_dists.append(np.min(np.linalg.norm(
np.array(np.where(aseg_lut == lut[label])).T -
mne.transforms.apply_trans(
this_aseg_trans, this_pos * 1000), axis=1)))
for label, this_dist in zip(labels.copy(), min_dists):
if this_dist != np.min(min_dists):
labels.remove(label)
ch_labels[aseg][f'sub-{sub}_ch-{ch_name_fix}'] = labels
# check to ensure no multiples
multiple = dict()
for name, labels in ch_labels[asegs[1]].items():
if len(labels) > 1:
multiple[name] = labels
# check number unlabelled
unlabelled = list()
for name, labels in ch_labels[asegs[1]].items():
if len(labels) == 0 and not np.isnan(ch_pos['individual'][name]).any():
unlabelled.append(name)
brain = mne.viz.Brain(template, **template_brain_kwargs)
for name in unlabelled:
if name in ch_pos['individual']:
brain._renderer.sphere(center=ch_pos['individual'][name],
color='yellow', scale=0.005)
def format_label_dk(label, combine_hemi=False, cortex=True):
label = label.lower()
# add spaces
for kw in ('middle', 'inferior', 'superior', 'isthmus', 'temporal',
'caudal', 'pars', 'rostral', 'medial', 'anterior',
'frontal', 'occipital', 'lateral'):
label = label.replace(kw, kw + ' ')
label = label.replace('bankssts', 'banks of superior temporal sulcus')
if 'ctx-' in label:
label = label.replace('ctx-', '') + (' Cortex' if cortex else '')
if combine_hemi:
label = label.replace('lh-', '').replace('rh-', '').replace(
'left-', '').replace('right-', '')
else:
if 'lh-' in label or 'left-' in label:
label = 'Left ' + label.replace('lh-', '').replace('left-', '')
if 'rh-' in label or 'right-' in label:
label = 'Right ' + label.replace('rh-', '').replace('right-', '')
return label.replace('-', ' ').title().strip()
def format_label_destrieux(label, combine_hemi=False, cortex=True):
label_short = label.replace('ctx_', '').replace(
'rh_', '').replace('lh_', '')
if label_short in DESTRIEUX_DICT:
prefix = ''
if 'rh' in label:
prefix = 'Right '
elif 'lh' in label:
prefix = 'Left '
return prefix + DESTRIEUX_DICT[label_short].title()
return label.replace('-', ' ')
#########
# Plots #
#########
# %%
# Figure 1: Schematic
sub = 1
raw = load_raw(sub=sub)
events, event_id = mne.events_from_annotations(raw)
raw_filtered = raw.copy().filter(l_freq=0.1, h_freq=40)
n_channels = 20
n_samples = int(10 * raw.info['sfreq'])
start_sample = events[99, 0] # response event
i = raw.ch_names.index('LPM 1')
raw_data = 1e3 * raw._data[i:i + n_channels,
start_sample: start_sample + n_samples]
raw_data -= raw_data.mean(axis=1)[:, None]
keep = np.array(pd.read_csv(op.join(
bids_root, 'derivatives', f'sub-{sub}', 'ieeg',
f'sub-{sub}_reject_mask.tsv'), sep='\t')['keep'])
event, tmin, tmax = event_dict['event']
epochs = mne.Epochs(
raw, events[events[:, 2] == event_id[event]][keep],
preload=True, tmin=tmin, tmax=tmax, detrend=1, baseline=None)
evoked = epochs.average()
n_epochs = 10
epochs_data = 1e4 * epochs.get_data(picks=['LPM 1'])[:n_epochs, 0]
tfr_data = compute_tfr(raw, i, raw_filtered, keep)
X = np.concatenate([tfr_data['baseline']['data'],
tfr_data['event']['data']], axis=0)
X = X.reshape(X.shape[0], -1).astype('float32') # flatten features
y = np.concatenate(
[np.repeat(0, tfr_data['baseline']['data'].shape[0]),
np.repeat(1, tfr_data['event']['data'].shape[0])])
X_train, X_test, y_train, y_test = \
train_test_split(X, y, test_size=0.2, random_state=99)
pca = PCA(n_components=50,
svd_solver='randomized', whiten=True).fit(X_train)
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
classifier = SVC(kernel='linear', random_state=99)
classifier.fit(X_train_pca, y_train)
score = classifier.score(X_test_pca, y_test)
eigenvectors = pca.components_.reshape(
(50, len(tfr_data['event']['freqs']),
tfr_data['event']['times'].size))
image = np.sum(
classifier.coef_[0][:, np.newaxis, np.newaxis] * eigenvectors,
axis=0)
pred = classifier.predict(X_test_pca)
tp = np.where(np.logical_and(pred == y_test, y_test == 1))[0]
fp = np.where(np.logical_and(pred != y_test, y_test == 1))[0]
tn = np.where(np.logical_and(pred == y_test, y_test == 0))[0]
fn = np.where(np.logical_and(pred != y_test, y_test == 0))[0]
sr = 800 / 1200 # screen ratio
x_min, x_max = X_test_pca[:, 0].min() * 1.1, X_test_pca[:, 0].max() * 1.1
y_min, y_max = X_test_pca[:, 1].min() * 1.1, X_test_pca[:, 1].max() * 1.1
XX, YY = np.meshgrid(np.linspace(x_min, x_max, 1000),
np.linspace(y_min, y_max, 1000))
XY = np.zeros((XX.size, 50)) # n_components == 50
XY[:, 0] = XX.ravel()
XY[:, 1] = YY.ravel()
ZZ = classifier.decision_function(XY)
ZZ = ZZ.reshape(XX.shape)
fig, (ax, ax2, ax3) = plt.subplots(3, 1, figsize=(8, 8),
gridspec_kw={'height_ratios': [1, 2, 1]})
fig.text(0.03, 0.97, 'a', fontsize=18)
ax.axis('off')
# fixation 700 + blank 700 + go 1200 + iti 4000 = 6600
ax.axis([-0.02, 6.62, -1, 1])
# main experimental design
ax.plot([0, 0, 0, 6.6, 6.6, 6.6], [0.2, -0.2, 0, 0, -0.2, 0.2], color='black')
# fixation
for t in (0.3, 0.4, 0.5, 0.6, 0.7):
ax.plot([t, t], [-0.2, 0.2], color=(0.5, 0.5, 0.5))
ax.plot([0, 0.35, 0.7], [0.2, 0.35, 0.2], color=(0.5, 0.5, 0.5)) # zoom
ax.fill([0, 0.7, 0.7, 0, 0], 0.37 + np.array([0, 0, 0.7 * sr, 0.7 * sr, 0]),
color=(0, 0, 0))
ax.fill([0.31, 0.39, 0.39, 0.31, 0.31],
0.37 + sr * np.array([0.31, 0.31, 0.39, 0.39, 0.31]),
color=(0.996, 0.996, 0.996))
ax.text(0.35, 0.55 + 0.7 * sr, 'Fixation\n300-700 ms jittered',
va='center', ha='center', fontsize=8, color=(0.5, 0.5, 0.5))
# blank
for t in (0.3, 0.4, 0.5, 0.6, 0.7):
ax.plot(0.7 + np.array([t, t]), [-0.2, 0.2], color=(0.7, 0.7, 0.7))
ax.plot([0.7, 1.05, 1.4], [-0.2, -0.35, -0.2], color=(0.7, 0.7, 0.7)) # zoom
ax.fill(0.7 + np.array([0, 0.7, 0.7, 0, 0]),
-0.37 - np.array([0, 0, 0.7 * sr, 0.7 * sr, 0]), color=(0, 0, 0))
ax.text(1.05, -0.58 - 0.7 * sr, 'Blank\n300-700 ms jittered',
va='center', ha='center', fontsize=8, color=(0.7, 0.7, 0.7))
# cue
ax.plot(1.4 + np.array([0.45, 0.45]), [-0.2, 0.2], color=(0.4, 0.4, 0.4))
ax.plot(1.4 + np.array([1.2, 1.2]), [-0.2, 0.2], color=(0.4, 0.4, 0.4))
ax.plot([1.4, 2.05, 2.6], [0.2, 0.5, 0.2], color=(0.4, 0.4, 0.4)) # zoom
ax.fill(1.75 + np.array([0, 0.7, 0.7, 0, 0]),
0.53 + np.array([0, 0, 0.7 * sr, 0.7 * sr, 0]), color=(0, 0, 0))
ax.fill(1.75 + np.array([0.28, 0.42, 0.42, 0.28]),
0.53 + sr * np.array([0.35, 0.47, 0.23, 0.35]),
color=(0.996, 0.996, 0.996))
ax.text(2.5, 0.75, 'Cue\n1.4 or 4 x\npractice RT',
va='center', ha='left', fontsize=8, color=(0.4, 0.4, 0.4))
# inter-trial interval
ax.plot([2.6, 4.6, 6.6], [0.2, 0.5, 0.2], color=(0.3, 0.3, 0.3)) # zoom
ax.fill(4.25 + np.array([0, 0.7, 0.7, 0, 0]),
0.53 + np.array([0, 0, 0.7 * sr, 0.7 * sr, 0]), color=(0, 0, 0))
ax.text(5, 0.75, 'Inter-trial inveral\n4000 ms',
va='center', ha='left', fontsize=8, color=(0.3, 0.3, 0.3))
# analysis markers
rt = 0.324
ax.plot(1.4 + np.array([rt, rt]), [-0.2, 0.2], color='red')
ax.fill_between([1.4 + rt - 0.5, 1.4 + rt + 0.5], -0.2, 0.2,
color='red', alpha=0.25)
ax.plot([1.32, 1.8, 1.4 + rt + 0.5], [-0.27, -0.38, -0.22],
color='red', alpha=0.25)
ax.text(2.3, -0.72, 'Response Epoch\n-500 to 500 ms\nrelative to\nresponse',
va='center', ha='center', fontsize=8, color='red', alpha=0.5)
ax.fill_between([5.1, 6.1], -0.2, 0.2, color='blue', alpha=0.25)
ax.plot([5.13, 5.7, 6.07], [-0.22, -0.38, -0.22], color='blue', alpha=0.25)
ax.text(5.7, -0.72,
'Baseline Epoch\n-1500 to -500 ms\nrelative to\nend of trial',
va='center', ha='center', fontsize=8, color='blue', alpha=0.5)
ax.fill_between([4.1, 5.1], -0.2, 0.2, color='green', alpha=0.25)
ax.plot([4.13, 4.5, 5.07], [-0.22, -0.68, -0.22], color='green', alpha=0.25)
ax.text(4, -0.85, 'Null Epoch\n-2500 to -1500 ms\nrelative to end of trial',
va='center', ha='center', fontsize=8, color='green', alpha=0.5)
ax = ax2
fig.text(0.03, 0.75, 'b', fontsize=18)
ax.axis('off')
ax.set_xlim([-0.1, 13.1])
ax.set_ylim([-2.1, 22.1])
# raw plot
ax.plot(np.linspace(0, 3, raw_data.shape[1]),
(raw_data + np.linspace(10, 20, n_channels)[:, None]).T,
color='black', linewidth=0.25)
ax.text(1.5, 21, 'Example Subject\nsEEG Recording', ha='center')
ax.text(1.5, 9.25, '...', ha='center', fontsize=32, color='gray')
ax.text(-0.5, 15, 'Amplitude (mV)', va='center', rotation=90)
ax.text(1.5, 8, 'Time (s)', ha='center', fontsize=8)
ax.plot([0, 3, 3, 0, 0], [20.5, 20.5, 19.5, 19.5, 20.5],
color='red', linewidth=0.5)
ax.text(3.7, 20.5, 'Epoch', ha='center', fontsize=8)
for offset in np.linspace(10, 20, n_channels):
ax.fill([3.25, 4, 4, 4.25, 4, 4, 3.25, 3.25],
offset + np.array([0.1, 0.1, 0.15, 0, -0.15, -0.1, -0.1, 0.1]),
color='tab:red' if offset == 20 else 'tab:blue')
'''
# evoked plot
ax.fill([3.45, 3.45, 3.4, 3.5, 3.6, 3.55, 3.55, 3.45],
[9.5, 8.5, 8.5, 8, 8.5, 8.5, 9.5, 9.5], color='tab:green')
ax.plot(np.linspace(1.5, 4.5, evoked.data.shape[1]),
7.5e4 * evoked.data.T + 3.5, color='black', linewidth=0.25)
ax.text(3, 6.5, 'Evoked Plot', ha='center')
ax.text(3, -3.5, 'Time Relative\nto Key Response', ha='center', color='r')
ax.plot([3, 3], [-1, 6], color='r')'''
# epochs plot
ax.plot(np.linspace(4.5, 7.5, epochs_data.shape[1]),
(epochs_data + np.linspace(13, 20, n_epochs)[:, None]).T,
color='black', linewidth=0.25)
ax.text(6, 21, 'Epochs for an\nExample Channel', ha='center', fontsize=8)
ax.text(4.65, 22.3, '1', ha='center', fontsize=8)
ax.scatter([4.65], [22.6], marker='o', s=120, clip_on=False,
edgecolors='black', facecolors='none')
ax.plot([6, 6], [12.75, 20.5], color='r')
ax.text(6, 12, '...', ha='center', fontsize=32, color='gray')
ax.text(6, 10.5, 'Average', ha='center')
ax.plot(np.linspace(4.5, 7.5, epochs_data.shape[1]),
epochs_data.mean(axis=0) + 10, color='black', linewidth=0.25)
ax.text(6, 7.5, 'Time Relative\nto Key Response',
fontsize=8, ha='center', color='r')
ax.plot([6, 6], [9.75, 10.25], color='r')
ax.text(8.25, 20.5, 'TFR', ha='center', va='center', fontsize=8)
for offset in np.linspace(13, 20, n_epochs):
ax.fill(8 + np.array([0, 0.5, 0.5, 0.75, 0.5, 0.5, 0, 0]),
offset + np.array([0.1, 0.1, 0.15, 0, -0.15, -0.1, -0.1, 0.1]),
color='tab:blue')
# spectrogram
ax.text(11, 20.8, 'Example Training\nSpectrograms', ha='center')
ax.text(9, 22.3, '2', ha='center', fontsize=8)
ax.scatter([9], [22.6], marker='o', s=120, clip_on=False,
edgecolors='black', facecolors='none')
for i in range(10):
x0, x1 = 9.75 - i / 10, 12.75 - i / 10
y0, y1 = 14 - i / 10, 20 - i / 10
ax.imshow(tfr_data['event']['data'][9 - i][::-1],
extent=(x0, x1, y0, y1), zorder=i,
aspect='auto', cmap='viridis')
ax.plot([x0, x1, x1, x0, x0], [y0, y0, y1, y1, y0],
color='black', linewidth=0.5, zorder=i)
ax.text(13, 16, 'Frequency (Hz)', va='center', rotation=90, fontsize=8)
ax.text(10.25, 10, 'PCA', ha='center')
ax.fill([9.75, 9.75, 9.25, 10.25, 11.25, 10.75, 10.75, 9.75],
[11.5, 10, 10, 9, 10, 10, 11.5, 11.5], color='tab:blue')
# pca
ax.text(10.25, 6.5, 'Component Weights\nfor each Training Epoch',
ha='center', fontsize=10)
ax.text(7.9, 7.8, '3', ha='center', fontsize=8)
ax.scatter([7.9], [8.1], marker='o', s=120, clip_on=False,
edgecolors='black', facecolors='none')
ax.plot(np.linspace(8.75, 11.75, X_train_pca.shape[1]),
(0.1 * X_train_pca[:n_epochs] +
np.linspace(2, 6, n_epochs)[:, None]).T)
ax.text(10.25, 1, '...', ha='center', fontsize=32, color=(0.5, 0.5, 0.5))
ax.text(12, 4, 'Epochs', rotation=90, va='center')
ax.bar(np.linspace(8.75, 11.75, X_train_pca.shape[1]),
20 * pca.explained_variance_ratio_,
3 / X_train_pca.shape[1] * 0.75)
ax.text(8.4, 0.25, 'EV', rotation=90, fontsize=8)
ax.text(10.25, -1, 'Components', ha='center')
ax.text(8.2, 3, 'SVM', ha='center', va='center')
ax.fill([8.625, 7.875, 7.875, 7.625, 7.875, 7.875, 8.625, 8.625],
[4, 4, 4.5, 3, 1.5, 2, 2, 4], color='tab:blue')
# svm
ax.text(6, 6, 'SVM Coefficients', ha='center')
ax.text(4, 6.1, '4', ha='center', fontsize=8)
ax.scatter([4], [6.4], marker='o', s=120, clip_on=False,
edgecolors='black', facecolors='none')
ax.plot(np.linspace(4.5, 7.5, classifier.coef_[0].size),
5.25 + classifier.coef_[0] / abs(classifier.coef_[0]).max())
ax.imshow(image[::-1], extent=(4.5, 7.5, -2, 4), aspect='auto', cmap='viridis')
ax.text(2.5, 4.75, 'Classify', ha='center', fontsize=8)
ax.fill(1.5 + 3.5 * np.array([0.75, 0.25, 0.25, 0, 0.25, 0.25, 0.75, 0.75]),
4 + 2 * np.array([0.1, 0.1, 0.15, 0, -0.15, -0.1, -0.1, 0.1]),
color='tab:blue')
for i in range(10):
x0, x1 = 2.25 - i / 10, 4.25 - i / 10
y0, y1 = -1 - i / 10, 3 - i / 10
ax.imshow(tfr_data['event']['data'][-i][::-1],
extent=(x0, x1, y0, y1), zorder=i,
aspect='auto', cmap='viridis')
ax.plot([x0, x1, x1, x0, x0], [y0, y0, y1, y1, y0],
color='black', linewidth=0.5, zorder=i)
ax.text(1.5, -4.25, 'Example Testing\nSpectrograms and Component Weights',
ha='center', fontsize=8)
ax.plot(np.linspace(0, 1.25, X_test_pca.shape[1]),
(0.1 * X_test_pca[:n_epochs] +
np.linspace(-0.5, 3, n_epochs)[:, None]).T, linewidth=0.5)
ax.text(0.625, -1.5, '...', ha='center', fontsize=24, color=(0.5, 0.5, 0.5))
# decision boundary
ax.text(2, 6.1, '5', ha='center', fontsize=8)
ax.scatter([2], [6.4], marker='o', s=120, clip_on=False,
edgecolors='black', facecolors='none')
ax.contourf((XX - x_min) / x_max / 1.5, (YY - y_min) / y_max * 1.5 + 4.25, ZZ,
cmap='RdBu', levels=20)
ax.scatter((X_test_pca[y_test == 0, 0] - x_min) / x_max / 1.5,
(X_test_pca[y_test == 0, 1] - y_min) / y_max * 1.5 + 4.25,
marker='o', color='r', s=0.5)
ax.scatter((X_test_pca[y_test == 1, 0] - x_min) / x_max / 1.5,
(X_test_pca[y_test == 1, 1] - y_min) / y_max * 1.5 + 4.25,
marker='o', color='b', s=0.5)
'''
ax.text(0.5, 6.5, 'Confusion Matrix', ha='center')
ax.text(-0.25, 5.4, 'TP', ha='center', va='center', fontsize=8)
ax.text(0.25, 5.4, f'{tp.size}', ha='center', va='center', fontsize=8)
ax.text(1.25, 5.4, 'FP', ha='center', va='center', fontsize=8)
ax.text(0.75, 5.4, f'{fp.size}', ha='center', va='center', fontsize=8)
ax.text(-0.25, 4.2, 'FN', ha='center', va='center', fontsize=8)
ax.text(0.25, 4.2, f'{fn.size}', ha='center', va='center', fontsize=8)
ax.text(1.25, 4.2, 'FN', ha='center', va='center', fontsize=8)
ax.text(0.75, 4.2, f'{tn.size}', ha='center', va='center', fontsize=8)
ax.plot([0, 1, 1, 0, 0],
[3.5, 3.5, 6, 6, 3.5], color='black')
ax.plot([0, 1], [4.75, 4.75], color='black')
ax.plot([0.5, 0.5], [3.5, 6], color='black')
'''
# red outline
ax.plot([0, 4.4, 4.4], [7.5, 7.5, 22], color='tab:red')
# add eigenspectrograms
ax = ax3
fig.text(0.03, 0.285, 'c', fontsize=18)
ax.set_xlim([0, 3.5])
ax.set_ylim([0, 1])
for direction in ('right', 'top', 'bottom'):
ax.spines[direction].set_visible(False)
ax.invert_yaxis()
ax.imshow(eigenvectors[0], extent=(0, 1, 0, 1), aspect='auto', cmap='viridis')
ax.imshow(eigenvectors[1], extent=(1.2, 2.2, 0, 1),
aspect='auto', cmap='viridis')
ax.imshow(eigenvectors[2], extent=(2.4, 3.4, 0, 1),
aspect='auto', cmap='viridis')
ax.set_xticks([0, 0.5, 1, 1.2, 1.7, 2.2, 2.4, 2.9, 3.4])
ax.set_xticklabels([-0.5, 0, 0.5] * 3)
ax.set_xlabel('Time (s)')
ax.set_yticks(np.linspace(1, 0, len(freqs)))
ax.set_yticklabels([f'{f} ' if i % 2 else f for i, f in
enumerate(np.array(freqs).round(
).astype(int))], fontsize=4)
ax.set_ylabel('Frequency (Hz)')
pos = ax.get_position()
ax.set_position((pos.x0, pos.y0 - 0.05, pos.width, pos.height))
fig.subplots_adjust(top=0.98, bottom=0.1, left=0.1, right=0.98)
for ext in exts:
fig.savefig(op.join(fig_dir, f'schematic.{ext}'), dpi=300,
pil_kwargs={'compression': 'tiff_lzw'})
# %%
# Figure 2: Individual implant plots to show sampling
fig, axes = plt.subplots(len(subjects) // 2, 6, figsize=(12, 8))
axes = axes.reshape(len(subjects), 3)
for ax in axes.flatten():
for direction in ('left', 'right', 'top', 'bottom'):
ax.spines[direction].set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
ax.invert_yaxis()
axes[0, 0].set_title('Right front')
axes[0, 1].set_title('Top down')
axes[0, 2].set_title('Left front')
for i, sub in enumerate(subjects):
axes[i, 0].set_ylabel(f'Subject {sub}')
info = mne.io.read_info(op.join(
ieeg_dir, f'sub-{sub}', 'ieeg',
f'sub-{sub}_task-{task}_info.fif'))
trans = mne.coreg.estimate_head_mri_t(f'sub-{sub}', subjects_dir)
brain = mne.viz.Brain(f'sub-{sub}', **brain_kwargs)
groups = dict()
for ch_name in info.ch_names:
elec_name = ''.join([letter for letter in ch_name if
not letter.isdigit() and letter != ' '])
groups[ch_name] = elec_name
chs = {ch['ch_name']: mne.transforms.apply_trans(trans, ch['loc'][:3])
for ch in info['chs']}
for idx, group in enumerate(np.unique(list(groups.values()))):
pos = np.array([chs[ch] for i, ch in enumerate(info.ch_names)
if groups[ch] == group])
# first, the insertion will be the point farthest from the origin
# brains are a longer posterior-anterior, scale for this (80%)
insert_idx = np.argmax(np.linalg.norm(pos * np.array([1, 0.8, 1]),
axis=1))
# second, find the farthest point from the insertion
target_idx = np.argmax(np.linalg.norm(pos[insert_idx] - pos, axis=1))
# third, make a unit vector and to add to the insertion for the bolt
elec_v = pos[insert_idx] - pos[target_idx]
elec_v /= np.linalg.norm(elec_v)
brain._renderer.tube( # 30 mm outside head
[pos[target_idx]], [pos[insert_idx] + elec_v * 0.03],
radius=0.001, color=_CMAP(idx)[:3])[0]
for (x, y, z) in pos:
brain._renderer.sphere(center=(x, y, z), color=_CMAP(idx)[:3],
scale=0.005)
# will add above code to add_sensors eventually
# brain.add_sensors(info, trans)
brain.show_view(azimuth=60, elevation=100, distance=0.325)
axes[i, 0].imshow(brain.screenshot())
brain.show_view(azimuth=90, elevation=0, distance=0.36)
axes[i, 1].imshow(brain.screenshot())
brain.show_view(azimuth=120, elevation=100, distance=0.325)
axes[i, 2].imshow(brain.screenshot())
brain.close()
fig.subplots_adjust(left=0.03, right=1, top=0.95, bottom=0.03,
wspace=-0.3, hspace=0)
for ax in axes[::2].flatten():
pos = ax.get_position()
ax.set_position((pos.x0 - 0.02, pos.y0, pos.width, pos.height))
for ax in axes[1::2].flatten():
pos = ax.get_position()
ax.set_position((pos.x0 + 0.02, pos.y0, pos.width, pos.height))
for ext in exts:
fig.savefig(op.join(fig_dir, f'coverage.{ext}'), dpi=300,
pil_kwargs={'compression': 'tiff_lzw'})
# %%
# Figure 3: histogram of classification accuracies
#
# Radial basis function scores not shown, almost exactly the same
binsize = 0.01
bins = np.linspace(binsize, 1, int(1 / binsize)) - binsize / 2
for event in ('event', 'go_event'):
fig, ax = plt.subplots()
patches = ax.hist(list(scores[event].values()), bins=bins,
alpha=0.5, color='b')[2]
for i, left_bin in enumerate(bins[:-1]):
if left_bin > sig_thresh:
patches[i].set_facecolor('r')
ax.hist(list(scores['null'].values()), bins=bins, alpha=0.5, color='gray',
label='null')
y_bounds = ax.get_ylim()
ax.axvline(np.mean(list(scores['event'].values())),
*y_bounds, color='black')
ax.axvline(np.mean(list(scores['null'].values())), *y_bounds, color='gray')
ax.set_xlim([0.25, 1])
ax.set_xlabel('Test Accuracy')
ax.set_ylabel('Count')
not_sig_patch = mpatches.Patch(
color='b', alpha=0.5, label='not significant')
sig_patch = mpatches.Patch(color='r', alpha=0.5, label='significant')
ax.legend(handles=[not_sig_patch, sig_patch])
fig.suptitle('PCA Linear SVM Classification Accuracies')
for ext in exts:
fig.savefig(op.join(fig_dir, f'{event}_score_hist.{ext}'), dpi=300,
pil_kwargs={'compression': 'tiff_lzw'})
print('{} Paired t-test p-value: {}'.format(
event.replace('_', ' ').capitalize(),
stats.ttest_rel(list(scores[event].values()),
list(scores['null'].values()))[1]))
print('{} Significant contacts {} / {}'.format(
event.replace('_', ' ').capitalize(),
(np.array(list(scores[event].values())) > sig_thresh).sum(),
len(scores[event])))
# %%
# Figure 4: Plots of electrodes with high classification accuracies
for event in ('event', 'go_event'):
fig = plt.figure(figsize=(8, 6))
gs = fig.add_gridspec(4, 4)
axes = np.array([[fig.add_subplot(gs[i, j]) for j in range(3)]
for i in range(3)])
cax = fig.add_subplot(gs[:2, 3])
cax2 = fig.add_subplot(gs[2:, 3])
for ax in axes.flatten():
ax.axis('off')
ax.invert_yaxis()
tax = fig.add_subplot(gs[3, :3]) # table axis
# color contacts by accuracy
brain = mne.viz.Brain(template, **template_brain_kwargs)
norm = Normalize(vmin=0.5, vmax=1)
for name, score in scores[event].items():
if score > sig_thresh:
x, y, z = ch_pos['template'][name]
brain._renderer.sphere(center=(x, y, z),
color=cmap(norm(score))[:3],
scale=0.005)
axes[0, 0].set_title('Right front')
axes[0, 1].set_title('Top down')
axes[0, 2].set_title('Left front')
brain.show_view(azimuth=60, elevation=100, distance=.3)
axes[0, 0].imshow(brain.screenshot())
brain.show_view(azimuth=90, elevation=0)
axes[0, 1].imshow(brain.screenshot())
brain.show_view(azimuth=120, elevation=100)
axes[0, 2].imshow(brain.screenshot())
brain.close()
fig.text(0.1, 0.85, 'a')
# get labels
ignore_keywords = ('unknown', '-vent', 'choroid-plexus', 'vessel',
'white-matter', 'wm-', 'cc_', 'cerebellum',
'brain-stem')
labels = dict()
for name, score in scores[event].items():
these_labels = ch_labels[asegs[1]][name] # use plotting atlas
for label in these_labels:
if any([kw in label.lower() for kw in ignore_keywords]):
continue
if label in labels:
labels[label].append(score)
else:
labels[label] = [score]
label_names = sorted(list(labels.keys()))
acc_colors = [cmap(norm(np.mean(labels[name]))) for name in label_names]
brain = mne.viz.Brain(template, **dict(template_brain_kwargs, alpha=0))
brain.add_volume_labels(aseg=asegs[1], labels=label_names,
colors=acc_colors, alpha=1, smooth=0.9)
# this freesurfer command must be run first for ? = r and l
# mri_annotation2label --subject cvs_avg35_inMNI152 --hemi ?h \
# --annotation aparc.a2009s --outdir $SUBJECTS_DIR/cvs_avg35_inMNI152/label
for hemi in ('lh', 'rh'):
brain.add_label('S_central', hemi=hemi, color='red',
borders=200)
brain.show_view(azimuth=60, elevation=100, distance=.3)
axes[1, 0].imshow(brain.screenshot())
brain.show_view(azimuth=90, elevation=0)
axes[1, 1].imshow(brain.screenshot())
brain.show_view(azimuth=120, elevation=100)
axes[1, 2].imshow(brain.screenshot())
brain.close()
fig.text(0.1, 0.65, 'b')
# colorbar
gradient = np.linspace(0, 1, 256)
gradient = np.repeat(gradient[:, np.newaxis], 256, axis=1)
cax.imshow(gradient, aspect='auto', cmap=cmap)
cax.set_xticks([])
cax.invert_yaxis()
cax.yaxis.tick_right()
cax.set_yticks(np.array([0, 0.5, 1]) * 256)
cax.set_yticklabels([np.round(sig_thresh, 2),
np.round((sig_thresh + 1) / 2, 2), 1])
cax.yaxis.set_label_position('right')
cax.set_ylabel('Accuracy')
# plot counts of electrodes per area
counts = dict()
for these_labels in ch_labels[asegs[1]].values():
for label in these_labels:
if any([kw in label.lower() for kw in ignore_keywords]):
continue
if label in counts:
counts[label] += 1
else:
counts[label] = 1
density_colors = [cmap(min([counts[name] / 10, 1.]))
for name in label_names]
brain = mne.viz.Brain(template, **dict(template_brain_kwargs, alpha=0))
brain.add_volume_labels(aseg=asegs[1], labels=label_names,
colors=density_colors, alpha=1, smooth=0.9)
for hemi in ('lh', 'rh'):
brain.add_label('S_central', hemi=hemi, color='red',
borders=200)
brain.show_view(azimuth=60, elevation=100, distance=.3)
axes[2, 0].imshow(brain.screenshot())
brain.show_view(azimuth=90, elevation=0)
axes[2, 1].imshow(brain.screenshot())
brain.show_view(azimuth=120, elevation=100)
axes[2, 2].imshow(brain.screenshot())
brain.close()
fig.text(0.1, 0.45, 'c')
# count colorbar
gradient = np.linspace(0, 10, 256)
gradient = np.repeat(gradient[:, np.newaxis], 256, axis=1)
cax2.imshow(gradient, aspect='auto', cmap=cmap)
cax2.set_xticks([])
cax2.invert_yaxis()
cax2.yaxis.tick_right()
cax2.set_yticks(np.linspace(2, 10, 5) * 256 / 10)
cax2.set_yticklabels(['2', '4', '6', '8', '10+'])
cax2.yaxis.set_label_position('right')
cax2.set_ylabel('Contact Count')
fig.subplots_adjust(hspace=0)
pos = cax.get_position()
cax.set_position((pos.x0, pos.y0 + pos.height * 0.1,
0.05, pos.height * 0.8))
pos = cax2.get_position()
cax2.set_position((pos.x0, pos.y0 + pos.height * 0.1,
0.05, pos.height * 0.8))
# table for electrode counts
tax.axis('off')
tax.set_xlim((-0.25, len(label_names) + 0.25))
tax.set_ylim((0, 1))
fig.canvas.draw() # for bounding box
for i, label in enumerate(label_names):
text = tax.text(i, -0.05, format_label_dk(label),
fontsize=4, rotation=90, va='bottom')
bbox = text.get_window_extent().transformed(tax.transData.inverted())
if i < len(label_names) - 1:
tax.plot([i + 0.7, i + 0.7], [-0.15, bbox.y1], color='black',
clip_on=False)
tax.plot([-0.25, len(label_names) - 0.5], [-0.08, -0.08],
color='black', clip_on=False)
for i, count in enumerate([counts[label] for label in label_names]):
tax.text(i + 0.25, -0.1, str(count),
ha='center', va='top', fontsize=4, rotation=90,
path_effects=[patheffects.withStroke(
linewidth=0.5, foreground=density_colors[i])])
fig.text(0.1, 0.3, 'd')
for ext in exts:
fig.savefig(op.join(fig_dir, f'{event}_high_accuracy.{ext}'), dpi=300,
pil_kwargs={'compression': 'tiff_lzw'})
# %%
# Figure 5: Accuracy by label region of interest
ignore_keywords = ('unknown', '-vent', 'choroid-plexus', 'vessel', 'cc_',
'wm', 'cerebellum') # signal won't cross dura
labels = set([label for labels in ch_labels[asegs[1]].values()
for label in labels])
label_scores = dict()
for name, score in scores['event'].items():
these_labels = ch_labels[asegs[1]][name] # use table atlas
for label in these_labels:
if label in label_scores:
label_scores[label].append(score)
else:
label_scores[label] = [score]
labels = sorted(labels, key=lambda label: np.mean(label_scores[label]))
fig, ax = plt.subplots(figsize=(8, 12), facecolor='black')
fig.suptitle('Classification Accuracies by Label', color='w')
for idx, label in enumerate(labels):
for lh in (True, False):
for sig_label, names in {'sig': sig['event'],
'not_sig': not_sig['event']}.items():
these_scores = \
[scores['event'][name] for name in names
if label in ch_labels[asegs[1]][name] and
(lh == (int(name.split('_')[0].replace(
'sub-', '')) in lh_sub))]
color = colors[label][:3] / 255
if color.mean() > 0.9:
color *= 0.75 # gray out white
# triangle if left hand used, hollow if not significant
ax.scatter(these_scores, [idx] * len(these_scores),
color=color, marker='^' if lh else None,
facecolors=None if sig_label == 'sig' else 'none')
ax.axis([0.25, 1, -0.75, len(labels) - 0.25])
ax.set_yticks(range(len(label_scores)))
ax.set_yticklabels([format_label_dk(label) for label in labels])
for tick, label in zip(ax.get_yticklabels(), labels):
color = colors[label][:3] / 255
tick.set_color('w' if color.max() < 0.6 or
(color[2] > 0.6 and color.mean() < 0.5)
else 'black') # blue is dark
tick.set_fontsize(8)
tick.set_path_effects([patheffects.withStroke(
linewidth=5, foreground=color)])
for tick in ax.get_xticklabels():
tick.set_color('w')
ax.set_xlabel('Classification Accuracy', color='w')
ax.set_ylabel('Anatomical Label', color='w')
# make legend
ax.text(0.27, len(labels) - 2, 'Right hand', va='center')
ax.scatter([0.5], [len(labels) - 2], color='black')
ax.text(0.27, len(labels) - 3.5, 'Left hand', va='center')
ax.scatter([0.5], [len(labels) - 3.5], marker='^', color='black')
ax.text(0.27, len(labels) - 5, 'Significant', va='center')
ax.scatter([0.5], [len(labels) - 5], color='black')
ax.text(0.27, len(labels) - 6.5, 'Not significant', va='center')
ax.scatter([0.5], [len(labels) - 6.5], facecolors='none', color='black')
ax.plot([0.26, 0.26, 0.52, 0.52, 0.26],
len(labels) - np.array([1, 7.15, 7.15, 1, 1]), color='black')
fig.tight_layout()
fig.subplots_adjust(top=0.95, bottom=0.07)
for ext in exts:
fig.savefig(op.join(fig_dir, f'label_accuracies.{ext}'),
facecolor=fig.get_facecolor(), dpi=300,
pil_kwargs={'compression': 'tiff_lzw'})
# %%
# Figure 6: distribution of classification accuracies across
# subjects compared to CSP.
# decoding-specific parameters
csp_freqs = np.logspace(np.log(8), np.log(250), 50, base=np.e)
windows = np.linspace(0, 2, 11)
windows = (windows[1:] + windows[:-1]) / 2 # take mean
fig, axes = plt.subplots(len(subjects) // 2, 4, figsize=(12, 8))
fig.subplots_adjust(left=0.08, right=0.98, top=0.92, bottom=0.08,