-
Notifications
You must be signed in to change notification settings - Fork 0
/
eeg_microstates.py
1734 lines (1514 loc) · 58.2 KB
/
eeg_microstates.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Information theoretic analysis EEG microstates
# Ref.: von Wegner et al., NeuroImage 2017, 158:99-111
# FvW (12/2014)
import argparse, os, sys, time
from sys import stdout
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata
from scipy.signal import butter, filtfilt, welch
from scipy.stats import chi2, chi2_contingency
from sklearn.decomposition import PCA, FastICA, TruncatedSVD
from statsmodels.stats.multitest import multipletests
# in case you have a compiled Cython implementation:
# from mutinf.mutinf_cy import mutinf_cy_c_wrapper, mutinf_cy
def read_xyz(filename):
"""Read EEG electrode locations in xyz format
Args:
filename: full path to the '.xyz' file
Returns:
locs: n_channels x 3 (numpy.array)
"""
ch_names = []
locs = []
with open(filename, 'r') as f:
l = f.readline() # header line
while l:
l = f.readline().strip().split("\t")
if (l != ['']):
ch_names.append(l[0])
locs.append([float(l[1]), float(l[2]), float(l[3])])
else:
l = None
return ch_names, np.array(locs)
def read_edf(filename):
"""Basic EDF file format reader
EDF specifications: http://www.edfplus.info/specs/edf.html
Args:
filename: full path to the '.edf' file
Returns:
chs: list of channel names
fs: sampling frequency in [Hz]
data: EEG data as numpy.array (samples x channels)
"""
def readn(n):
"""read n bytes."""
return np.fromfile(fp, sep='', dtype=np.int8, count=n)
def bytestr(bytes, i):
"""convert byte array to string."""
return np.array([bytes[k] for k in range(i*8, (i+1)*8)]).tostring()
fp = open(filename, 'r')
x = np.fromfile(fp, sep='', dtype=np.uint8, count=256).tostring()
header = {}
header['version'] = x[0:8]
header['patientID'] = x[8:88]
header['recordingID'] = x[88:168]
header['startdate'] = x[168:176]
header['starttime'] = x[176:184]
header['length'] = int(x[184:192]) # header length (bytes)
header['reserved'] = x[192:236]
header['records'] = int(x[236:244]) # number of records
header['duration'] = float(x[244:252]) # duration of each record [sec]
header['channels'] = int(x[252:256]) # ns - number of signals
n_ch = header['channels'] # number of EEG channels
header['channelname'] = (readn(16*n_ch)).tostring()
header['transducer'] = (readn(80*n_ch)).tostring().split()
header['physdime'] = (readn(8*n_ch)).tostring().split()
header['physmin'] = []
b = readn(8*n_ch)
for i in range(n_ch): header['physmin'].append(float(bytestr(b, i)))
header['physmax'] = []
b = readn(8*n_ch)
for i in range(n_ch): header['physmax'].append(float(bytestr(b, i)))
header['digimin'] = []
b = readn(8*n_ch)
for i in range(n_ch): header['digimin'].append(int(bytestr(b, i)))
header['digimax'] = []
b = readn(8*n_ch)
for i in range(n_ch): header['digimax'].append(int(bytestr(b, i)))
header['prefilt'] = (readn(80*n_ch)).tostring().split()
header['samples_per_record'] = []
b = readn(8*n_ch)
for i in range(n_ch): header['samples_per_record'].append(float(bytestr(b, i)))
nr = header['records']
n_per_rec = int(header['samples_per_record'][0])
n_total = int(nr*n_per_rec*n_ch)
fp.seek(header['length'],os.SEEK_SET) # header end = data start
data = np.fromfile(fp, sep='', dtype=np.int16, count=n_total) # count=-1
fp.close()
# re-order
data = np.reshape(data,(n_per_rec,n_ch,nr),order='F')
data = np.transpose(data,(0,2,1))
data = np.reshape(data,(n_per_rec*nr,n_ch),order='F')
# convert to physical dimensions
for k in range(data.shape[1]):
d_min = float(header['digimin'][k])
d_max = float(header['digimax'][k])
p_min = float(header['physmin'][k])
p_max = float(header['physmax'][k])
if ((d_max-d_min) > 0):
data[:,k] = p_min+(data[:,k]-d_min)/(d_max-d_min)*(p_max-p_min)
#print(header)
# we want to print the information of the data that we read in
print("some info:\n\n")
print(data.shape)
return header['channelname'].split(),\
header['samples_per_record'][0]/header['duration'],\
data
def bp_filter(data, test, fs):
"""Digital band pass filter (6-th order Butterworth)
Args:
data: numpy.array, time along axis 0
(f_lo, f_hi): frequency band to extract [Hz]
fs: sampling frequency [Hz]
Returns:
data_filt: band-pass filtered data, same shape as data
"""
(f_lo, f_hi) = test
data_filt = np.zeros_like(data)
f_ny = fs/2. # Nyquist frequency
b_lo = f_lo/f_ny # normalized frequency [0..1]
b_hi = f_hi/f_ny # normalized frequency [0..1]
p_lp = {"N":6, "Wn":b_hi, "btype":"lowpass", "analog":False, "output":"ba"}
p_hp = {"N":6, "Wn":b_lo, "btype":"highpass", "analog":False, "output":"ba"}
bp_b1, bp_a1 = butter(**p_lp)
bp_b2, bp_a2 = butter(**p_hp)
data_filt = filtfilt(bp_b1, bp_a1, data, axis=0)
data_filt = filtfilt(bp_b2, bp_a2, data_filt, axis=0)
return data_filt
def plot_data(data, fs, filename="test"):
"""Plot the data
Args:
data: numpy.array
fs: sampling frequency [Hz]
"""
t = np.arange(len(data))/fs # time axis in seconds
fig = plt.figure(1, figsize=(20,4))
fig.patch.set_facecolor('white')
plt.plot(t, data, '-k', linewidth=1)
plt.xlabel("time [s]", fontsize=24)
plt.ylabel("potential [$\mu$V]", fontsize=24)
plt.tight_layout()
#plt.show()
# we want to save the plot
plt.savefig(filename)
def plot_psd(data, fs, n_seg=1024):
"""Plot the power spectral density (Welch's method)
Args:
data: numpy.array
fs: sampling frequency [Hz]
n_seg: samples per segment, default=1024
"""
freqs, psd = welch(data, fs, nperseg=n_seg)
fig = plt.figure(1, figsize=(16,8))
fig.patch.set_facecolor('white')
plt.semilogy(freqs, psd, 'k', linewidth=3)
#plt.loglog(freqs, psd, 'k', linewidth=3)
#plt.xlim(freqs.min(), freqs.max())
#plt.ylim(psd.min(), psd.max())
plt.title("Power spectral density (Welch's method n={:d})".format(n_seg))
plt.tight_layout()
plt.show()
def topo(data, n_grid=64):
"""Interpolate EEG topography onto a regularly spaced grid
Args:
data: numpy.array, size = number of EEG channels
n_grid: integer, interpolate to n_grid x n_grid array, default=64
Returns:
data_interpol: cubic interpolation of EEG topography, n_grid x n_grid
contains nan values
"""
channels, locs = read_xyz('cap.xyz')
n_channels = len(channels)
#locs /= np.sqrt(np.sum(locs**2,axis=1))[:,np.newaxis]
locs /= np.linalg.norm(locs, 2, axis=1, keepdims=True)
c = findstr('Cz', channels)[0]
# print 'center electrode for interpolation: ' + channels[c]
#w = np.sqrt(np.sum((locs-locs[c])**2, axis=1))
w = np.linalg.norm(locs-locs[c], 2, axis=1)
#arclen = 2*np.arcsin(w/2)
arclen = np.arcsin(w/2.*np.sqrt(4.-w*w))
phi = np.angle(map(complex, locs[:,0]-locs[c][0], locs[:,1]-locs[c][1]))
X = arclen*np.real(np.exp(1j*phi))
Y = arclen*np.imag(np.exp(1j*phi))
r = max([max(X),max(Y)])
Xi = np.linspace(-r,r,n_grid)
Yi = np.linspace(-r,r,n_grid)
data_ip = griddata((X, Y), data, (Xi[None,:], Yi[:,None]), method='cubic')
return data_ip
def eeg2map(data):
"""Interpolate and normalize EEG topography, ignoring nan values
Args:
data: numpy.array, size = number of EEG channels
n_grid: interger, interpolate to n_grid x n_grid array, default=64
Returns:
top_norm: normalized topography, n_grid x n_grid
"""
n_grid = 64
top = topo(data, n_grid)
mn = np.nanmin(top)
mx = np.nanmax(top)
top_norm = (top-mn)/(mx-mn)
return top_norm
def clustering(data, fs, chs, locs, mode, n_clusters, doplot=False):
"""EEG microstate clustering algorithms.
Args:
data: numpy.array (n_t, n_ch)
fs : sampling frequency [Hz]
chs : list of channel name strings
locs: numpy.array (n_ch, 2) of electrode locations (x, y)
mode: clustering algorithm
n_clusters: number of clusters
doplot: boolean
Returns:
maps: n_maps x n_channels NumPy array
L: microstate sequence (integers)
gfp_peaks: locations of local GFP maxima
gev: global explained variance
"""
#print("\t[+] Clustering algorithm: {:s}".format(mode))
# --- number of EEG channels ---
n_ch = data.shape[1]
#print("\t[+] EEG channels: n_ch = {:d}".format(n_ch))
# --- normalized data ---
data_norm = data - data.mean(axis=1, keepdims=True)
data_norm /= data_norm.std(axis=1, keepdims=True)
# --- GFP peaks ---
gfp = np.nanstd(data, axis=1)
gfp2 = np.sum(gfp**2) # normalizing constant
gfp_peaks = locmax(gfp)
data_cluster = data[gfp_peaks,:]
#data_cluster = data_cluster[:100,:]
data_cluster_norm = data_cluster - data_cluster.mean(axis=1, keepdims=True)
data_cluster_norm /= data_cluster_norm.std(axis=1, keepdims=True)
print("\t[+] Data format for clustering [GFP peaks, channels]: {:d} x {:d}"\
.format(data_cluster.shape[0], data_cluster.shape[1]))
start = time.time()
if (mode == "aahc"):
print("\n\t[+] Clustering algorithm: AAHC.")
maps = aahc(data, n_clusters, doplot=False)
if (mode == "kmeans"):
print("\n\t[+] Clustering algorithm: mod. K-MEANS.")
maps = kmeans(data, n_maps=n_clusters, n_runs=5, doplot=False)
if (mode == "kmedoids"):
print("\n\t[+] Clustering algorithm: K-MEDOIDS.")
C = np.corrcoef(data_cluster_norm)
C = C**2 # ignore EEG polarity
kmed_maps = kmedoids(S=C, K=n_clusters, nruns=10, maxits=500)
maps = np.array([data_cluster[kmed_maps[k].__int__(),:] for k in range(n_clusters)])
del C, kmed_maps
if (mode == "pca"):
print("\n\t[+] Clustering algorithm: PCA.")
params = {"n_components": n_clusters, "copy": True, "whiten": True, "svd_solver": "auto"}
pca = PCA(**params) # SKLEARN
pca.fit(data_cluster_norm)
maps = np.array([pca.components_[k,:] for k in range(n_clusters)])
#print "PCA - explained variance: " + str(pca.explained_variance_ratio_)
#print "PCA - total explained variance: " + str(np.sum(pca.explained_variance_ratio_))
del pca, params
# SKLEARN: TruncatedSVD(n_components=2, algorithm='randomized', n_iter=5, random_state=None, tol=0.0)
#params = {"n_components": n_clusters, "algorithm": "randomized", "n_iter": 5, "random_state": None, "tol": 0.0}
#svd = TruncatedSVD(**params)
#svd.fit(data_cluster_norm)
#maps = svd.components_
#print "explained variance (%): "
#print explained_variance_ratio_
##print "explained variance: "
#print explained_variance_
#del svd, params
if (mode == "ica"):
print("\n\t[+] Clustering algorithm: Fast-ICA.")
#''' Fast-ICA: algorithm= parallel;deflation, fun=logcosh;exp;cube
params = {"n_components": n_clusters, "algorithm": "parallel", "whiten": True, "fun": "exp", "max_iter": 200}
ica = FastICA(**params) # SKLEARN
S_ = ica.fit_transform(data_cluster_norm) # reconstructed signals
A_ = ica.mixing_ # estimated mixing matrix
IC_ = ica.components_
print("data: " + str(data_cluster_norm.shape))
print("ICs: " + str(IC_.shape))
print("mixing matrix: " + str(A_.shape))
maps = np.array([ica.components_[k,:] for k in range(n_clusters)])
del ica, params
end = time.time()
delta_t = end - start
print("\t[+] Computation time: {:.2f}".format(delta_t))
# --- microstate sequence ---
# we are modified the sequence of microstates by multiplying the data_norm
# to the maps so we have a map to each timepoint?
C = np.dot(data_norm, maps.T)/n_ch
print("\tC.shape: " + str(C.shape))
L = np.argmax(C**2, axis=1)
print("\tL.shape: " + str(L.shape))
del C
# --- GEV ---
maps_norm = maps - maps.mean(axis=1, keepdims=True)
maps_norm /= maps_norm.std(axis=1, keepdims=True)
# --- correlation data, maps ---
C = np.dot(data_norm, maps_norm.T)/n_ch
#print("\tC.shape: " + str(C.shape))
#print("\tC.min: {:.2f} Cmax: {:.2f}".format(C.min(), C.max()))
# --- GEV_k & GEV ---
gev = np.zeros(n_clusters)
for k in range(n_clusters):
r = L==k
gev[k] = np.sum(gfp[r]**2 * C[r,k]**2)/gfp2
print("\n\t[+] Global explained variance GEV = {:.3f}".format(gev.sum()))
for k in range(n_clusters): print("\t\tGEV_{:d}: {:.3f}".format(k, gev[k]))
if doplot:
plt.ion()
# matplotlib's perceptually uniform sequential colormaps:
# magma, inferno, plasma, viridis
cm = plt.cm.magma
fig, axarr = plt.subplots(1, n_clusters, figsize=(20,5))
fig.patch.set_facecolor('white')
for imap in range(n_clusters):
axarr[imap].imshow(eeg2map(maps[imap, :]), cmap=cm, origin='lower')
axarr[imap].set_xticks([])
axarr[imap].set_xticklabels([])
axarr[imap].set_yticks([])
axarr[imap].set_yticklabels([])
title = "Microstate maps ({:s})".format(mode.upper())
axarr[0].set_title(title, fontsize=16, fontweight="bold")
plt.show()
# --- assign map labels manually ---
order_str = raw_input("\n\t\tAssign map labels (e.g. 0, 2, 1, 3): ")
order_str = order_str.replace(",", "")
order_str = order_str.replace(" ", "")
if (len(order_str) != n_clusters):
if (len(order_str)==0):
print("\t\tEmpty input string.")
else:
print("\t\tParsed manual input: {:s}".format(", ".join(order_str)))
print("\t\tNumber of labels does not equal number of clusters.")
print("\t\tContinue using the original assignment...\n")
else:
order = np.zeros(n_clusters, dtype=int)
for i, s in enumerate(order_str):
order[i] = int(s)
print("\t\tRe-ordered labels: {:s}".format(", ".join(order_str)))
# re-order return variables
maps = maps[order,:]
for i in range(len(L)):
L[i] = order[L[i]]
gev = gev[order]
# Figure
fig, axarr = plt.subplots(1, n_clusters, figsize=(20,5))
fig.patch.set_facecolor('white')
for imap in range(n_clusters):
axarr[imap].imshow(eeg2map(maps[imap, :]), cmap=cm, origin='lower')
axarr[imap].set_xticks([])
axarr[imap].set_xticklabels([])
axarr[imap].set_yticks([])
axarr[imap].set_yticklabels([])
title = "re-ordered microstate maps"
axarr[0].set_title(title, fontsize=16, fontweight="bold")
plt.show()
plt.ioff()
return maps, L, gfp_peaks, gev
def aahc(data, N_clusters, doplot=False):
"""Atomize and Agglomerative Hierarchical Clustering Algorithm
AAHC (Murray et al., Brain Topography, 2008)
Args:
data: EEG data to cluster, numpy.array (n_samples, n_channels)
N_clusters: desired number of clusters
doplot: boolean, plot maps
Returns:
maps: n_maps x n_channels (numpy.array)
"""
def extract_row(A, k):
v = A[k,:]
A_ = np.vstack((A[:k,:],A[k+1:,:]))
return A_, v
def extract_item(A, k):
a = A[k]
A_ = A[:k] + A[k+1:]
return A_, a
#print("\n\t--- AAHC ---")
nt, nch = data.shape
# --- get GFP peaks ---
gfp = data.std(axis=1)
gfp_peaks = locmax(gfp)
#gfp_peaks = gfp_peaks[:100]
#n_gfp = gfp_peaks.shape[0]
gfp2 = np.sum(gfp**2) # normalizing constant in GEV
# --- initialize clusters ---
maps = data[gfp_peaks,:]
# --- store original gfp peaks and indices ---
cluster_data = data[gfp_peaks,:]
#n_maps = n_gfp
n_maps = maps.shape[0]
print("\t[+] Initial number of clusters: {:d}\n".format(n_maps))
# --- cluster indices w.r.t. original size, normalized GFP peak data ---
Ci = [[k] for k in range(n_maps)]
# --- main loop: atomize + agglomerate ---
while (n_maps > N_clusters):
s = "\r{:s}\r\t\tAAHC > n: {:d} => {:d}".format(80*" ", n_maps, n_maps-1)
stdout.write(s); stdout.flush()
#print("\n\tAAHC > n: {:d} => {:d}".format(n_maps, n_maps-1))
# --- correlations of the data sequence with each cluster ---
m_x, s_x = data.mean(axis=1, keepdims=True), data.std(axis=1)
m_y, s_y = maps.mean(axis=1, keepdims=True), maps.std(axis=1)
s_xy = 1.*nch*np.outer(s_x, s_y)
C = np.dot(data-m_x, np.transpose(maps-m_y)) / s_xy
# --- microstate sequence, ignore polarity ---
L = np.argmax(C**2, axis=1)
# --- GEV (global explained variance) of cluster k ---
gev = np.zeros(n_maps)
for k in range(n_maps):
r = L==k
gev[k] = np.sum(gfp[r]**2 * C[r,k]**2)/gfp2
# --- merge cluster with the minimum GEV ---
imin = np.argmin(gev)
#print("\tre-cluster: {:d}".format(imin))
# --- N => N-1 ---
maps, _ = extract_row(maps, imin)
Ci, reC = extract_item(Ci, imin)
re_cluster = [] # indices of updated clusters
#C_sgn = np.zeros(nt)
for k in reC: # map index to re-assign
c = cluster_data[k,:]
m_x, s_x = maps.mean(axis=1, keepdims=True), maps.std(axis=1)
m_y, s_y = c.mean(), c.std()
s_xy = 1.*nch*s_x*s_y
C = np.dot(maps-m_x, c-m_y)/s_xy
inew = np.argmax(C**2) # ignore polarity
#C_sgn[k] = C[inew]
re_cluster.append(inew)
Ci[inew].append(k)
n_maps = len(Ci)
# --- update clusters ---
re_cluster = list(set(re_cluster)) # unique list of updated clusters
''' re-clustering by modified mean
for i in re_cluster:
idx = Ci[i]
c = np.zeros(nch) # new cluster average
for k in idx: # add to new cluster, polarity according to corr. sign
if (C_sgn[k] >= 0):
c += cluster_data[k,:]
else:
c -= cluster_data[k,:]
c /= len(idx)
maps[i] = c
#maps[i] = (c-np.mean(c))/np.std(c) # normalize the new cluster
del C_sgn
'''
# re-clustering by eigenvector method
for i in re_cluster:
idx = Ci[i]
Vt = cluster_data[idx,:]
Sk = np.dot(Vt.T, Vt)
evals, evecs = np.linalg.eig(Sk)
c = evecs[:, np.argmax(np.abs(evals))]
c = np.real(c)
maps[i] = c/np.sqrt(np.sum(c**2))
print()
return maps
def kmeans(data, n_maps, n_runs=10, maxerr=1e-6, maxiter=500, doplot=False):
"""Modified K-means clustering as detailed in:
[1] Pascual-Marqui et al., IEEE TBME (1995) 42(7):658--665
[2] Murray et al., Brain Topography(2008) 20:249--264.
Variables named as in [1], step numbering as in Table I.
Args:
data: numpy.array, size = number of EEG channels
n_maps: number of microstate maps
n_runs: number of K-means runs (optional)
maxerr: maximum error for convergence (optional)
maxiter: maximum number of iterations (optional)
doplot: plot the results, default=False (optional)
Returns:
maps: microstate maps (number of maps x number of channels)
L: sequence of microstate labels
gfp_peaks: indices of local GFP maxima
gev: global explained variance (0..1)
cv: value of the cross-validation criterion
"""
n_t = data.shape[0]
n_ch = data.shape[1]
data = data - data.mean(axis=1, keepdims=True)
# GFP peaks
gfp = np.std(data, axis=1)
gfp_peaks = locmax(gfp)
gfp_values = gfp[gfp_peaks]
gfp2 = np.sum(gfp_values**2) # normalizing constant in GEV
n_gfp = gfp_peaks.shape[0]
# clustering of GFP peak maps only
V = data[gfp_peaks, :]
sumV2 = np.sum(V**2)
# store results for each k-means run
cv_list = [] # cross-validation criterion for each k-means run
gev_list = [] # GEV of each map for each k-means run
gevT_list = [] # total GEV values for each k-means run
maps_list = [] # microstate maps for each k-means run
L_list = [] # microstate label sequence for each k-means run
for run in range(n_runs):
# initialize random cluster centroids (indices w.r.t. n_gfp)
rndi = np.random.permutation(n_gfp)[:n_maps]
maps = V[rndi, :]
# normalize row-wise (across EEG channels)
maps /= np.sqrt(np.sum(maps**2, axis=1, keepdims=True))
# initialize
n_iter = 0
var0 = 1.0
var1 = 0.0
# convergence criterion: variance estimate (step 6)
while ( (np.abs((var0-var1)/var0) > maxerr) & (n_iter < maxiter) ):
# (step 3) microstate sequence (= current cluster assignment)
C = np.dot(V, maps.T)
C /= (n_ch*np.outer(gfp[gfp_peaks], np.std(maps, axis=1)))
L = np.argmax(C**2, axis=1)
# (step 4)
for k in range(n_maps):
Vt = V[L==k, :]
# (step 4a)
Sk = np.dot(Vt.T, Vt)
# (step 4b)
evals, evecs = np.linalg.eig(Sk)
v = evecs[:, np.argmax(np.abs(evals))]
maps[k, :] = v/np.sqrt(np.sum(v**2))
# (step 5)
var1 = var0
var0 = sumV2 - np.sum(np.sum(maps[L, :]*V, axis=1)**2)
var0 /= (n_gfp*(n_ch-1))
n_iter += 1
if (n_iter < maxiter):
print("\t\tK-means run {:d}/{:d} converged after {:d} iterations.".format(run+1, n_runs, n_iter))
else:
print("\t\tK-means run {:d}/{:d} did NOT converge after {:d} iterations.".format(run+1, n_runs, maxiter))
# CROSS-VALIDATION criterion for this run (step 8)
C_ = np.dot(data, maps.T)
C_ /= (n_ch*np.outer(gfp, np.std(maps, axis=1)))
L_ = np.argmax(C_**2, axis=1)
var = np.sum(data**2) - np.sum(np.sum(maps[L_, :]*data, axis=1)**2)
var /= (n_t*(n_ch-1))
cv = var * (n_ch-1)**2/(n_ch-n_maps-1.)**2
# GEV (global explained variance) of cluster k
gev = np.zeros(n_maps)
for k in range(n_maps):
r = L==k
gev[k] = np.sum(gfp_values[r]**2 * C[r,k]**2)/gfp2
gev_total = np.sum(gev)
# store
cv_list.append(cv)
gev_list.append(gev)
gevT_list.append(gev_total)
maps_list.append(maps)
L_list.append(L_)
# select best run
k_opt = np.argmin(cv_list)
#k_opt = np.argmax(gevT_list)
maps = maps_list[k_opt]
# ms_gfp = ms_list[k_opt] # microstate sequence at GFP peaks
gev = gev_list[k_opt]
L_ = L_list[k_opt]
if doplot:
plt.ion()
# matplotlib's perceptually uniform sequential colormaps:
# magma, inferno, plasma, viridis
cm = plt.cm.magma
fig, axarr = plt.subplots(1, n_maps, figsize=(20,5))
fig.patch.set_facecolor('white')
for imap in range(n_maps):
axarr[imap].imshow(eeg2map(maps[imap, :]), cmap=cm, origin='lower')
axarr[imap].set_xticks([])
axarr[imap].set_xticklabels([])
axarr[imap].set_yticks([])
axarr[imap].set_yticklabels([])
title = "K-means cluster centroids"
axarr[0].set_title(title, fontsize=16, fontweight="bold")
plt.show()
# --- assign map labels manually ---
order_str = raw_input("\n\t\tAssign map labels (e.g. 0, 2, 1, 3): ")
order_str = order_str.replace(",", "")
order_str = order_str.replace(" ", "")
if (len(order_str) != n_maps):
if (len(order_str)==0):
print("\t\tEmpty input string.")
else:
print("\t\tParsed manual input: {:s}".format(", ".join(order_str)))
print("\t\tNumber of labels does not equal number of clusters.")
print("\t\tContinue using the original assignment...\n")
else:
order = np.zeros(n_maps, dtype=int)
for i, s in enumerate(order_str):
order[i] = int(s)
print("\t\tRe-ordered labels: {:s}".format(", ".join(order_str)))
# re-order return variables
maps = maps[order,:]
for i in range(len(L)):
L[i] = order[L[i]]
gev = gev[order]
# Figure
fig, axarr = plt.subplots(1, n_maps, figsize=(20,5))
fig.patch.set_facecolor('white')
for imap in range(n_maps):
axarr[imap].imshow(eeg2map(maps[imap, :]), cmap=cm, origin='lower')
axarr[imap].set_xticks([])
axarr[imap].set_xticklabels([])
axarr[imap].set_yticks([])
axarr[imap].set_yticklabels([])
title = "re-ordered K-means cluster centroids"
axarr[0].set_title(title, fontsize=16, fontweight="bold")
plt.show()
plt.ioff()
#return maps, L_, gfp_peaks, gev, cv
return maps
def kmedoids(S, K, nruns, maxits):
"""Octave/Matlab: Copyright Brendan J. Frey and Delbert Dueck, Aug 2006
http://www.psi.toronto.edu/~frey/apm/kcc.m
Simplified by Kevin Murphy
Python 2.7.x - FvW, 02/2014
Args:
filename: full path to the '.xyz' file
Returns:
locs: n_channels x 3 (numpy.array)
"""
n = S.shape[0]
dpsim = np.zeros((maxits,nruns))
idx = np.zeros((n,nruns))
for rep in xrange(nruns):
tmp = np.random.permutation(range(n))
mu = tmp[:K]
t = 0
done = (t==maxits)
while ( not done ):
t += 1
muold = mu
dpsim[t,rep] = 0
# Find class assignments
cl = np.argmax(S[:,mu], axis=1) # max pos. of each row
# Set assignments of exemplars to themselves
cl[mu] = range(K)
for j in xrange(K): # For each class, find new exemplar
I = np.where(cl==j)[0]
S_I_rowsum = np.sum(S[I][:,I],axis=0)
Scl = max(S_I_rowsum)
ii = np.argmax(S_I_rowsum)
dpsim[t,rep] = dpsim[t,rep] + Scl
mu[j] = I[ii]
if all(muold==mu) | (t==maxits):
done = 1
idx[:,rep] = mu[cl]
dpsim[t+1:,rep] = dpsim[t,rep]
return np.unique(idx)
def p_empirical(data, n_clusters):
"""Empirical symbol distribution
Args:
data: numpy.array, size = length of microstate sequence
n_clusters: number of microstate clusters
Returns:
p: empirical distribution
"""
p = np.zeros(n_clusters)
n = len(data)
for i in range(n):
p[data[i]] += 1.0
p /= n
return p
def T_empirical(data, n_clusters):
"""Empirical transition matrix
Args:
data: numpy.array, size = length of microstate sequence
n_clusters: number of microstate clusters
Returns:
T: empirical transition matrix
"""
T = np.zeros((n_clusters, n_clusters))
n = len(data)
for i in range(n-1):
T[data[i], data[i+1]] += 1.0
p_row = np.sum(T, axis=1)
for i in range(n_clusters):
if ( p_row[i] != 0.0 ):
for j in range(n_clusters):
T[i,j] /= p_row[i] # normalize row sums to 1.0
return T
def p_equilibrium(T):
'''get equilibrium distribution from transition matrix: lambda=1 - (left) eigenvector'''
evals, evecs = np.linalg.eig(T.transpose())
i = np.where(np.isclose(evals, 1.0, atol=1e-6))[0][0] # locate max eigenval.
p_eq = np.abs(evecs[:,i]) # make eigenvec. to max. eigenval. non-negative
p_eq /= p_eq.sum() # normalized eigenvec. to max. eigenval.
return p_eq # stationary distribution
def max_entropy(n_clusters):
"""Maximum Shannon entropy of a sequence with n_clusters
Args:
n_clusters: number of microstate clusters
Returns:
h_max: maximum Shannon entropy
"""
h_max = np.log(float(n_clusters))
return h_max
def shuffle(data):
"""Randomly shuffled copy of data (i.i.d. surrogate)
Args:
data: numpy array, 1D
Returns:
data_copy: shuffled data copy
"""
data_c = data.copy()
np.random.shuffle(data_c)
return data_c
def surrogate_mc(p, T, n_clusters, n):
"""Surrogate Markov chain with symbol distribution p and
transition matrix T
Args:
p: empirical symbol distribution
T: empirical transition matrix
n_clusters: number of clusters/symbols
n: length of surrogate microstate sequence
Returns:
mc: surrogate Markov chain
"""
# NumPy vectorized code
psum = np.cumsum(p)
Tsum = np.cumsum(T, axis=1)
# initial state according to p:
mc = [np.min(np.argwhere(np.random.rand() < psum))]
# next state according to T:
for i in range(1, n):
mc.append(np.min(np.argwhere(np.random.rand() < Tsum[mc[i-1]])))
''' alternative implementation using loops
r = np.random.rand() # ~U[0,1], random threshold
s = 0.
y = p[s]
while (y < r):
s += 1.
y += p[s]
mc = [s] # initial state according to p
# iterate ...
for i in xrange(1,n):
r = np.random.rand() # ~U[0,1], random threshold
s = mc[i-1] # currrent state
t = 0. # trial state
y = T[s][t] # transition rate to trial state
while ( y < r ):
t += 1. # next trial state
y += T[s][t]
mc.append(t) # store current state
'''
return np.array(mc)
def mutinf(x, ns, lmax):
"""Time-lagged mutual information of symbolic sequence x with
ns different symbols, up to maximum lag lmax.
*** Symbols must be 0, 1, 2, ... to use as indices directly! ***
Args:
x: symbolic sequence, symbols = [0, 1, 2, ...]
ns: number of symbols
lmax: maximum time lag
Returns:
mi: time-lagged mutual information
"""
n = len(x)
mi = np.zeros(lmax)
for l in range(lmax):
if ((l+1)%10 == 0):
s = "\r\t\tmutual information lag: {:d}".format(l+1)
sys.stdout.write(s)
sys.stdout.flush()
nmax = n-l
h1 = H_1(x[:nmax], ns)
h2 = H_1(x[l:l+nmax], ns)
h12 = H_2(x[:nmax], x[l:l+nmax], ns)
mi[l] = h1 + h2 - h12
return mi
def mutinf_i(x, ns, lmax):
"""Time-lagged mutual information for each symbol of the symbolic
sequence x with ns different symbols, up to maximum lag lmax.
*** Symbols must be 0, 1, 2, ... to use as indices directly! ***
Args:
x: symbolic sequence, symbols = [0, 1, 2, ...]
ns: number of symbols
lmax: maximum time lag
Returns:
mi: time-lagged mutual informations for each symbol, ns x lmax
"""
n = len(x)
mi = np.zeros((ns,lmax))
for l in range(lmax):
if (l%10 == 0):
s = "\r\t\tmutual information lag: {:d}".format(l)
sys.stdout.write(s)
sys.stdout.flush()
nmax = n - l
# compute distributions
p1 = np.zeros(ns)
p2 = np.zeros(ns)
p12 = np.zeros((ns,ns))
for i in range(nmax):
i1 = int(x[i])
i2 = int(x[i+l])
p1[i1] += 1.0 # p( X_t = i1 )
p2[i2] += 1.0 # p( X_t+l = i2 )
p12[i1,i2] += 1.0 # p( X_t+l=i2 , X_t=i1 )
p1 /= nmax
p2 /= nmax
# normalize the transition matrix p( X_t+l=i2 | X_t=i1 )
rowsum = np.sum(p12, axis=1)
for i, j in np.ndindex(p12.shape):
p12[i,j] /= rowsum[i]
# compute entropies
H2 = np.sum(p2[p2>0] * np.log(p2[p2>0]))
for i in range(ns):
H12 = 0.0
for j in range(ns):
if ( p12[i,j] > 0.0 ):
H12 += ( p12[i,j] * np.log( p12[i,j] ) )
mi[i,l] = -H2 + p1[i] * H12
return mi
def mutinf_CI(p, T, n, alpha, nrep, lmax):
"""Return an array for the computation of confidence intervals (CI) for
the time-lagged mutual information of length lmax.
Null Hypothesis: Markov Chain of length n, equilibrium distribution p,
transition matrix T, using nrep repetitions."""
ns = len(p)
mi_array = np.zeros((nrep,lmax))
for r in range(nrep):
print("\n\t\tsurrogate MC # {:d} / {:d}".format(r+1, nrep))
x_mc = surrogate_mc(p, T, ns, n)
mi_mc = mutinf(x_mc, ns, lmax)
#mi_mc = mutinf_cy(X_mc, ns, lmax)
mi_array[r,:] = mi_mc
return mi_array
def excess_entropy_rate(x, ns, kmax, doplot=False):
# y = ax+b: line fit to joint entropy for range of histories k
# a = entropy rate (slope)
# b = excess entropy (intersect.)
h_ = np.zeros(kmax)
for k in range(kmax): h_[k] = H_k(x, ns, k+1)
ks = np.arange(1,kmax+1)
a, b = np.polyfit(ks, h_, 1)
# --- Figure ---
if doplot:
plt.figure(figsize=(6,6))
plt.plot(ks, h_, '-sk')
plt.plot(ks, a*ks+b, '-b')
plt.xlabel("k")
plt.ylabel("$H_k$")
plt.title("Entropy rate")
plt.tight_layout()
plt.show()
return (a, b)
def mc_entropy_rate(p, T):
"""Markov chain entropy rate.
- \sum_i sum_j p_i T_ij log(T_ij)
"""
h = 0.
for i, j in np.ndindex(T.shape):
if (T[i,j] > 0):
h -= ( p[i]*T[i,j]*np.log(T[i,j]) )
return h
def aif_peak1(mi, fs, doplot=False):
'''compute time-lagged mut. inf. (AIF) and 1st peak.'''
dt = 1000./fs # sampling interval [ms]
mi_filt = np.convolve(mi, np.ones(3)/3., mode='same')
#mi_filt = np.convolve(mi, np.ones(5)/5., mode='same')
mx0 = 8 # 8
jmax = mx0 + locmax(mi_filt[mx0:])[0]
mx_mi = dt*jmax
if doplot:
offset = 5
tmax = 100
fig = plt.figure(1, figsize=(22,4))
fig.patch.set_facecolor('white')
t = dt*np.arange(tmax)
plt.plot(t[offset:tmax], mi[offset:tmax], '-ok', label='AIF')
plt.plot(t[offset:tmax], mi_filt[offset:tmax], '-b', label='smoothed AIF')
plt.plot(mx_mi, mi[jmax], 'or', markersize=15, label='peak-1')
plt.xlabel("time lag [ms]")
plt.ylabel("mut. inf. [bits]")
plt.legend(loc=0)
#plt.title("mutual information of map sequence")
#plt.title(s, fontsize=16, fontweight='bold')