Newer
Older
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
# -*- coding: utf-8 -*-
"""
Updated Aug 7 2024
@author: Qianliang Li (glia@dtu.dk)
This is the main Python file containing the code that support the findings of
https://doi.org/10.1101/2024.05.06.592342
The data used in this analysis was previously described and preprocessed
by Zimmermann, M., Lomoriello, A. S., and Konvalinka, I.
Intra-individual behavioural and neural signatures of audience effects and
interactions in a mirror-game paradigm. Royal Society Open Science, 9(2) 2022
"""
# %% Load libraries
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mne
import pickle
import mat73
import time
import seaborn as sns
import nolds
from tqdm import tqdm # progress bar
# import Python script for microstates [von Wegner & Lauf, 2018]
# originally downloaded from https://github.com/Frederic-vW/eeg_microstates
# I modified the script for estimating two-brain microstates
# by defining kmeans_return_all and kmeans_dualmicro
from eeg_microstates3 import (kmeans_return_all, kmeans_dualmicro)
# import helper functions
from helper import (numpy_arr_to_pandas_df, time_now)
from dualmicro_functions import (load_epoch_from_fieldtrip, prepare_1P_micro_arr,
plot_microstates, reorder_microstate_results,
single_micro_fit_all_feature_computation,
interbrain_microstate_feature_computation,
prepare_2P_micro_arr_collapsed_events,
plot_dualmicro, sign_swap_microstates,
dualmicro_fit_all_feature_computation,
load_microstate_arrays,
get_synch_events_from_pseudo_pairs,
combine_two_person_microstate_arrays,
pseudo_pair_dualmicro_backfitting,
dualmicro_fit_all_pseudo_pair_feature_computation,
compute_dualmicro_DFA, compute_dualmicro_DFA_pseudo,
shifted_interbrain_microstate_feature_computation)
# Style for matplotlib/seaborn
plt.style.use('default')
# Root for project
os.chdir("C:/Users/glia/Documents/MirrorGame")
# Paths
data_path = "./data/external/EEG/"
mov_data_path = "./data/external/movement/"
fig_save_path = "./reports/figures/"
feat_save_path = "./data/features/"
microstate_save_path = "./data/features/microstates2/"
mov_save_path = "./data/features/movement/"
# %% Load preprocessed EEG data
# The data was originally preprocessed in Fieldtrip by Marius Zimmermann
# Get filenames for the EEG data
files = []
for r, d, f in os.walk(data_path):
for file in f:
if (".mat" in file) & ("ppn" in file):
files.append(os.path.join(r, file))
# Sort the filenames
files.sort()
n_subjects = len(files)
# Get Subject_id
Subject_id = [0]*n_subjects
for i in range(n_subjects):
id_number = files[i].split("/")[-1].split(".")[0].split("pair")[-1].split("pair")[-1].replace("_ppn","")
Subject_id[i] = int(id_number)+1000 # add 1000 to keep the first 0
# There are data from 23 pairs
# Pair 21 and 25 were excluded in the original analysis
# After looking at the data, it seems pair 21, participant 1 and pair 25
# participant 2 only had 1254 and 1440 epochs respectively.
# Their data also do not end with resting-state condition
# All the other EEG data have around 2400 1s epochs and start and ends with rest
bad_subjects = [1211, 1212, 1251, 1252] # the whole pair is dropped
good_subject_idx = [not i in bad_subjects for i in Subject_id]
# Update Subject_id and files
Subject_id = list(np.array(Subject_id)[good_subject_idx])
n_subjects = len(Subject_id)
files = list(np.array(files)[good_subject_idx])
Pair_id = [0]*(n_subjects//2)
for i in range(n_subjects//2):
Pair_id[i] = int(str(Subject_id[2*i])[1:-1])
# Add 100 to pair_id to fix sorting for 1 digit numbers, e.g. 03
Pair_id = [ele+100 for ele in Pair_id]
n_pairs = len(Pair_id)
# Save the IDs as environmental variables to be used in functions
# from dualmicro_functions.py
os.environ["Subject_id"] = Subject_id
os.environ["Pair_id"] = Pair_id
event_id = {"rest":1, "uncoupled":2, "coupled": 3, "observe, actor": 4,
"observe, observer": 6, "imitate, leader": 5, "imitate, follower": 7,
"control": 8}
# Clarification of the labels
# Cond4: ppn1 is observer, ppn2 is actor
# Cond6: ppn1 is actor, ppn2 is observer
# Cond5: ppn1 is follower, ppn2 is leader
# Cond5: ppn1 is leader, ppn2 is follower
event_id_inv = {v: k for k, v in event_id.items()}
# We collapsed condition 4 and 6 & 5 and 7 for two-brain microstates
# By swapping the EEG of ppn1 and ppn2 so ppn1 is always observer/follower and
# ppn2 actor/leader
collapsed_event_id = {"rest":1, "uncoupled":2, "coupled": 3,
"observer_actor": 4, "follower_leader": 5, "control": 8}
collapsed_event_id_inv = {v: k for k, v in collapsed_event_id.items()}
# Load the first EEG to get info about sfreq and n_channels
i = 0
epoch, trialinfo = load_epoch_from_fieldtrip(0, files, event_id)
n_channels = epoch.info["nchan"]
sfreq = int(epoch.info["sfreq"])
# Visualize the data
# epoch.plot(scalings=40e-6, n_channels=32)
# mne.viz.plot_events(epoch.events, sfreq = 1, event_id = event_id, first_samp=-3) # sfreq set to epoch length in s to reflect experiment time
# We compute microstates for the three frequency ranges
alpha_range = [8.0, 13.0]
beta_range = [13.0, 30.0]
broadband_range = None # Data is already 1 to 40 Hz broadband filtered
freq_names = ["alpha","beta","broadband"]
all_freq_ranges = [alpha_range, beta_range, broadband_range]
# %% Intrabrain microstates fit all data
# All subjects from all pairs are concatenated to find common microstates
single_brain_event_id = {"rest":1, "uncoupled":2, "coupled": 3, "observer": 4,
"actor": 6, "follower": 5, "leader": 7, "control": 8}
ppn2_correction = {6:4, 4:6, 7:5, 5:7}
# Loop over frequencies
for f in len(all_freq_ranges):
ff = freq_names[f]
freq_range0 = all_freq_ranges[f]
# =========================================================================
# First the microstate topographies are determined
# It might be an advantage to run the estimation of microstates on a HPC
# =========================================================================
# Get data from all pairs before performing kmeans
np.random.seed(1234)
n_clusters=[3, 4, 5, 6, 7, 8, 9, 10]
n_runs = 100 # increased to 100 runs!
# Get current time
c_time1 = time_now(); print(c_time1)
# Save RAM by appending directly to array instead of making list and then array
sub_arr_indices = [0]
trialinfo_list = []
for i in range(n_subjects):
tmp_data, trialinfo = prepare_1P_micro_arr(i, ppn2_correction, sfreq,
freq_range=freq_range0, standardize=True)
sub_arr_indices.append(len(tmp_data))
trialinfo_list.append([Subject_id[i],trialinfo])
if i == 0: # first run initiation
micro_data_all = tmp_data
else:
micro_data_all = np.append(micro_data_all, tmp_data, axis=0)
del tmp_data # clear up space
print(f"Finished preparing microstate data for pair {Subject_id[i]}")
# Use cumulative sum to determine indices for each subjects's data
subject_indices = np.cumsum(sub_arr_indices)
# Save the trialinfos from all subjects, for easier access in later steps
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}_trialinfos.pkl", "wb") as filehandle:
pickle.dump(trialinfo_list, filehandle)
# # with args parser in hpc
# n_maps = n_clusters[(args.map_idx-1)]
# print(f"Running analysis for maps: {n_maps}")
# print("Memory used by the micro data array (GB):",micro_data_all.nbytes*9.31e-10)
# Run Kmeans
for n_maps in n_clusters: # Don't use for loop on the HPC!
# Run the 100 runs in batches of 10 to save underway in case the job script terminates
best_cv_crit = 9999 # initialize unreasonably high value
for r in range(10):
microstate_results = list(kmeans_return_all(micro_data_all, n_maps,
n_runs=int(n_runs/10),maxiter=1000))
# Overwrite the maps if a lower CV criterion was found for the initiation
if microstate_results[4] < best_cv_crit:
microstate_results.append(subject_indices)
# Save results
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "wb") as filehandle:
pickle.dump(microstate_results, filehandle) # [maps, L, gfp_peaks, gev, cv_min, Subject_id]
print(f"Updated the microstates. Previous best CV: {best_cv_crit}",
f"new best CV criterion : {microstate_results[4]}")
# Update best cv criterion value
best_cv_crit = microstate_results[4]
print(f"Finished sub-run {r+1} out of 10")
print(f"Finished microstate analysis for n_maps = {n_maps}")
print("Started", c_time1, "\nCurrent",time_now())
# =========================================================================
# Evaluate microstates fitted to all data
# =========================================================================
# Get summary results
microstate_summary_results = []
for n_maps in n_clusters:
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
# Also save summary results across n_maps
microstate_summary_results.append([microstate_results[0],microstate_results[3],microstate_results[4]])
# Use CV criterion to estimate best number of microstates
cv_gev_arr = np.zeros((len(n_clusters),2))
for imap in range(len(n_clusters)):
gev = np.sum(microstate_summary_results[imap][1])
cv = microstate_summary_results[imap][2]
cv_gev_arr[imap,:] = [cv, gev]
# Convert to Pandas dataframe
col_names = ["n_Microstates", "Fit_Criteria", "Value"]
Fit_Criteria = ["CV Criterion", "Global Explained Variance"]
dtypes = [int,str,"float64"]
cv_gev_df = numpy_arr_to_pandas_df(cv_gev_arr, col_names = col_names,
col_values = [n_clusters,Fit_Criteria],
dtypes = dtypes)
# Evaluate optimal n_Microstates
h_order = Fit_Criteria
g = sns.FacetGrid(data=cv_gev_df,row=None,
margin_titles=True, height=8, aspect=1.2)
g = g.map(sns.pointplot,"n_Microstates", "Value", "Fit_Criteria",
dodge=0, capsize=0.18, errorbar=None, linestyles=["-", "-"],
markers=["o", "o"], hue_order=h_order, palette=sns.color_palette())
g.add_legend()
plt.subplots_adjust(top=0.9, right=0.85, left=0.1)
g.fig.suptitle("Mean CV Criterion and GEV", fontsize=18)
g.set_axis_labels(x_var="Number of Microstates",
y_var="GEV and CV",
fontsize=14)
# The lower CV the better. Measure of residual variance
# But the higher GEV the better.
# Save file
g.savefig(f"{fig_save_path}Microstates/Fit_all_{ff}/"+"Single_micro_fit_all_{ff}_CV_Criterion_GEV"+".png")
# Count which number of microstates have the lowest cv criterion for each subject
min_idx = np.argmin(cv_gev_df.loc[cv_gev_df["Fit_Criteria"]=="CV Criterion","Value"])
cv_gev_df.loc[cv_gev_df["Fit_Criteria"]=="CV Criterion"].iloc[min_idx]
# Visualize all microstates prior to re-ordering
for ii in range(len(n_clusters)):
plot_microstates(n_clusters[ii], microstate_summary_results[ii][0], microstate_summary_results[ii][1], epoch.info)
# =========================================================================
# # Re-order intrabrain microstates
# =========================================================================
# This is only run once, after microstates are created
# The optimal number of microstates were 5, with 56% GEV
n_maps = 5
ii = n_clusters.index(n_maps)
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv_min, sub_idx = microstate_results
plot_microstates(n_maps, maps, gev)
# Make dictionary with n_maps and new order
manual_reordering_template = {"5_alpha":[4,1,3,2,0],
"5_beta":[3,2,1,4,0],
"5_broadband":[3,2,4,1,0]}
new_order = manual_reordering_template[f"{n_maps}_{ff}"]
# Re-order the microstates
maps, gev, m_labels = reorder_microstate_results(new_order, maps, gev, m_labels)
# Plot again to check it worked
plot_microstates(n_maps, maps, gev, epoch.info)
# Since neuronal activity is often oscillating, this causes polarity inversions
# Microstates ignores the sign, and hence the polarity in the map is arbitrary
# It is only the relative difference within the plot that is interesting
# depending on initiation. We can thus freely change the sign for visualization
# For two-person microstates, each person's map is sign-changed separately
manual_sign_correction = {"5_alpha":[1,-1,1,1,1],
"5_beta":[1,1,1,-1,-1],
"5_broadband":[-1,1,-1,1,1]}
sign_swap = manual_sign_correction[f"{n_maps}_{ff}"]
for m in range(n_maps):
maps[m] *= sign_swap[m]
# Plot a final time for last confirmation
plot_microstates(n_maps, maps, gev, epoch.info)
# Close all figures
plt.close("all")
### Save reordered results
n_maps = 5
ii = n_clusters.index(n_maps)
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv, sub_indices = microstate_results
# Re-order
new_order = manual_reordering_template[str(n_maps)]
maps, gev, m_labels = reorder_microstate_results(new_order, maps, gev, m_labels)
# Sign swap
for m in range(n_maps):
maps[m] *= sign_swap[m]
# Overwrite variable
microstate_results = maps, m_labels, gfp_peaks, gev, cv, sub_indices
# Save to new file
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "wb") as filehandle:
pickle.dump(microstate_results, filehandle) # [maps, L, gfp_peaks, gev, cv_min, sub_idx]
# Save topomaps for the microstates
save_path = f"{fig_save_path}Microstates/Fit_all_{ff}/"
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv_min, sub_idx = microstate_results
fig = plot_microstates(n_maps, maps, gev, epoch.info)
fig.savefig(save_path+f"Intrabrain_fit_all_{ff}_maps{n_maps}"+".png")
# Save svg for Paper
fig.savefig(save_path+f"Intrabrain_fit_all_{ff}_maps{n_maps}"+".svg")
# =========================================================================
# # Estimate one-person microstate metrics/features
# # There might be a small error introduced due to gaps in the time series from
# # dropped segments, e.g. when calculating the transition probability as
# # the time series is discontinuous due to the gaps. But with the high sampling rate
# # only a very small fraction of the samples have discontinuous neighbors
# =========================================================================
# The observer_actor and observer_observe conditions have been separated
# So there are observer and actor conditions.
# And the same for leader and follower.
"""
Overview of common (intrabrain) microstate features:
1. Average duration a given microstate remains stable (Dur)
2. Frequency occurrence, independent of individual duration (Occ)
Average number of times a microstate becomes dominant per second
3. Ratio of total Time Covered (TCo)
4. Transition probabilities (TMx)
5. Ratio of shannon entropy relative to theoretical max chaos (Ent)
"""
# Hard-coded the optimal number of microstates based on CV criterion and GEV for dualmicro
n_maps = 5
# Load all microstate results
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
# Load all trialinfos
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}_trialinfos.pkl", "rb") as file:
trialinfo_list = pickle.load(file)
Microstate_names = [chr(ele) for ele in range(65,65+n_maps)]
m_labels = [0]*n_subjects
events = [0]*n_subjects
m_feats = [0]*n_subjects
for i in range(n_subjects):
m_labels[i], events[i], m_feats[i] = single_micro_fit_all_feature_computation(i,
n_maps, microstate_results, trialinfo_list, sfreq, event_id, single_brain_event_id)
print(f"Finished computing microstate features for Subject {Subject_id[i]}")
# Save the raw microstate features
with open(f"{microstate_save_path}/raw_features_single_micro_fit_all_{ff}_maps{n_maps}.pkl", "wb") as filehandle:
pickle.dump(m_feats, filehandle) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
# * the feature is calculated for each map, where applicable.
# Transition matrix is calculated for each map -> map transition probability
# with open(f"{microstate_save_path}/raw_features_single_micro_fit_all_{ff}_maps{n_maps}.pkl", "rb") as file:
# m_feats = pickle.load(file) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
### Convert all features to dataframes for further processing
col_names = ["Subject_ID", "Event_ID", "Microstate", "Value"]
col_values = [Subject_id,list(single_brain_event_id.keys()),Microstate_names]
dtypes = ["int64",str,str,"float64"]
# Mean duration
Dur_arr = np.stack([ele[0] for ele in m_feats]) # [Subject, event, n_map]
Dur_df = numpy_arr_to_pandas_df(Dur_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Duration"]*len(Dur_df)
Dur_df.insert(2, "Measurement", measurement_id)
# Save df
Dur_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_duration_df.pkl"))
# Frequency of occurrence per sec
Occ_arr = np.stack([ele[1] for ele in m_feats]) # [Subject, event, n_map]
Occ_df = numpy_arr_to_pandas_df(Occ_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Occurrence"]*len(Occ_df)
Occ_df.insert(2, "Measurement", measurement_id)
# Save df
Occ_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_occurrence_df.pkl"))
# Ratio total Time Covered
TCo_arr = np.stack([ele[2] for ele in m_feats]) # [Subject, event, n_map]
TCo_df = numpy_arr_to_pandas_df(TCo_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Time_covered"]*len(TCo_df)
TCo_df.insert(2, "Measurement", measurement_id)
# Save df
TCo_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_ratio_time_covered_df.pkl"))
# Transition matrix should be read as probability of row to column
xi, xj = np.meshgrid(Microstate_names,Microstate_names)
_, arrow = np.meshgrid(Microstate_names,["->"]*n_maps)
transition_info = np.char.add(np.char.add(xj,arrow),xi)
TMx_arr = np.stack([ele[3] for ele in m_feats]) # [Subject, event, n_map, n_map]
TMx_arr = TMx_arr.reshape((n_subjects,len(single_brain_event_id),n_maps*n_maps)) # Flatten the maps to 1D
col_names = ["Subject_ID", "Event_ID", "Transition", "Value"]
col_values = [Subject_id,list(single_brain_event_id.keys()),transition_info.flatten()]
TMx_df = numpy_arr_to_pandas_df(TMx_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Probability"]*len(TMx_df)
TMx_df.insert(2, "Measurement", measurement_id)
# Save df
TMx_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_transition_df.pkl"))
# Entropy
Ent_arr = np.stack([ele[4] for ele in m_feats]) # [Subject, event]
col_names = ["Subject_ID", "Event_ID", "Value"]
col_values = [Subject_id,list(single_brain_event_id.keys())]
dtypes = ["int64",str,"float64"]
Ent_df = numpy_arr_to_pandas_df(Ent_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Entropy"]*len(Ent_df)
Ent_df.insert(2, "Measurement", measurement_id)
# Save df
Ent_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_ratio_entropy_df.pkl"))
# =========================================================================
# We also did it for 8 alpha microstates to use the same number as
# the two-brain microstates
# =========================================================================
# This is only run once, after microstates are created
ff = "alpha"
n_maps = 8
ii = n_clusters.index(n_maps)
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv_min, sub_idx = microstate_results
plot_microstates(n_maps, maps, gev)
# Make dictionary with n_maps and new order
manual_reordering_template = {"8":[6,0,5,1,7,2,3,4]}
new_order = manual_reordering_template[str(n_maps)]
# Re-order the microstates
maps, gev, m_labels = reorder_microstate_results(new_order, maps, gev, m_labels)
# Plot again to check it worked
plot_microstates(n_maps, maps, gev, epoch.info)
# Since neuronal activity is often oscillating, this causes polarity inversions
# Microstates ignores the sign, and hence the polarity in the map is arbitrary
# It is only the relative difference within the plot that is interesting
# depending on initiation. We can thus freely change the sign for visualization
# For two-person microstates, each person's map is sign-changed separately
manual_sign_correction = {"8":[-1,1,-1,1,1,1,-1,-1]}
sign_swap = manual_sign_correction[str(n_maps)]
for m in range(n_maps):
maps[m] *= sign_swap[m]
# Plot a final time for last confirmation
plot_microstates(n_maps, maps, gev, epoch.info)
# Close all figures
plt.close("all")
### Save reordered results
n_maps = 8
ii = n_clusters.index(n_maps)
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv, sub_indices = microstate_results
# Re-order
new_order = manual_reordering_template[str(n_maps)]
maps, gev, m_labels = reorder_microstate_results(new_order, maps, gev, m_labels)
# Sign swap
for m in range(n_maps):
maps[m] *= sign_swap[m]
# Overwrite variable
microstate_results = maps, m_labels, gfp_peaks, gev, cv, sub_indices
# Save to new file
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "wb") as filehandle:
pickle.dump(microstate_results, filehandle) # [maps, L, gfp_peaks, gev, cv_min, sub_idx]
# Save topomaps for the microstates
save_path = f"{fig_save_path}Microstates/Fit_all_{ff}/"
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv_min, sub_idx = microstate_results
fig = plot_microstates(n_maps, maps, gev, epoch.info)
fig.savefig(save_path+f"Intrabrain_fit_all_{ff}_maps{n_maps}"+".png")
# Save svg for Paper
fig.savefig(save_path+f"Intrabrain_fit_all_{ff}_maps{n_maps}"+".svg")
# =========================================================================
# # Estimate one-person microstate metrics/features
# # There might be a small error introduced due to gaps in the time series from
# # dropped segments, e.g. when calculating the transition probability as
# # the time series is discontinuous due to the gaps. But with the high sampling rate
# # only a very small fraction of the samples have discontinuous neighbors
# =========================================================================
# The observer_actor and observer_observe conditions have been separated
# So there are observer and actor conditions.
# And the same for leader and follower.
"""
Overview of common (intrabrain) microstate features:
1. Average duration a given microstate remains stable (Dur)
2. Frequency occurrence, independent of individual duration (Occ)
Average number of times a microstate becomes dominant per second
3. Ratio of total Time Covered (TCo)
4. Transition probabilities (TMx)
5. Ratio of shannon entropy relative to theoretical max chaos (Ent)
"""
# Hard-coded the optimal number of microstates based on CV criterion and GEV for dualmicro
n_maps = 8
# Load all microstate results
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
# Load all trialinfos
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}_trialinfos.pkl", "rb") as file:
trialinfo_list = pickle.load(file)
Microstate_names = [chr(ele) for ele in range(65,65+n_maps)]
m_labels = [0]*n_subjects
events = [0]*n_subjects
m_feats = [0]*n_subjects
for i in range(n_subjects):
m_labels[i], events[i], m_feats[i] = single_micro_fit_all_feature_computation(i,
n_maps, microstate_results, trialinfo_list, sfreq, event_id, single_brain_event_id)
print(f"Finished computing microstate features for Subject {Subject_id[i]}")
# Save the raw microstate features
with open(f"{microstate_save_path}/raw_features_single_micro_fit_all_{ff}_maps{n_maps}.pkl", "wb") as filehandle:
pickle.dump(m_feats, filehandle) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
# * the feature is calculated for each map, where applicable.
# Transition matrix is calculated for each map -> map transition probability
# with open(f"{microstate_save_path}/raw_features_single_micro_fit_all_{ff}_maps{n_maps}.pkl", "rb") as file:
# m_feats = pickle.load(file) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
### Convert all features to dataframes for further processing
col_names = ["Subject_ID", "Event_ID", "Microstate", "Value"]
col_values = [Subject_id,list(single_brain_event_id.keys()),Microstate_names]
dtypes = ["int64",str,str,"float64"]
# Mean duration
Dur_arr = np.stack([ele[0] for ele in m_feats]) # [Subject, event, n_map]
Dur_df = numpy_arr_to_pandas_df(Dur_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Duration"]*len(Dur_df)
Dur_df.insert(2, "Measurement", measurement_id)
# Save df
Dur_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_duration_df.pkl"))
# Frequency of occurrence per sec
Occ_arr = np.stack([ele[1] for ele in m_feats]) # [Subject, event, n_map]
Occ_df = numpy_arr_to_pandas_df(Occ_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Occurrence"]*len(Occ_df)
Occ_df.insert(2, "Measurement", measurement_id)
# Save df
Occ_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_occurrence_df.pkl"))
# Ratio total Time Covered
TCo_arr = np.stack([ele[2] for ele in m_feats]) # [Subject, event, n_map]
TCo_df = numpy_arr_to_pandas_df(TCo_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Time_covered"]*len(TCo_df)
TCo_df.insert(2, "Measurement", measurement_id)
# Save df
TCo_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_ratio_time_covered_df.pkl"))
# Transition matrix should be read as probability of row to column
xi, xj = np.meshgrid(Microstate_names,Microstate_names)
_, arrow = np.meshgrid(Microstate_names,["->"]*n_maps)
transition_info = np.char.add(np.char.add(xj,arrow),xi)
TMx_arr = np.stack([ele[3] for ele in m_feats]) # [Subject, event, n_map, n_map]
TMx_arr = TMx_arr.reshape((n_subjects,len(single_brain_event_id),n_maps*n_maps)) # Flatten the maps to 1D
col_names = ["Subject_ID", "Event_ID", "Transition", "Value"]
col_values = [Subject_id,list(single_brain_event_id.keys()),transition_info.flatten()]
TMx_df = numpy_arr_to_pandas_df(TMx_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Probability"]*len(TMx_df)
TMx_df.insert(2, "Measurement", measurement_id)
# Save df
TMx_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_transition_df.pkl"))
# Entropy
Ent_arr = np.stack([ele[4] for ele in m_feats]) # [Subject, event]
col_names = ["Subject_ID", "Event_ID", "Value"]
col_values = [Subject_id,list(single_brain_event_id.keys())]
dtypes = ["int64",str,"float64"]
Ent_df = numpy_arr_to_pandas_df(Ent_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Entropy"]*len(Ent_df)
Ent_df.insert(2, "Measurement", measurement_id)
# Save df
Ent_df.to_pickle(os.path.join(microstate_save_path,f"Single_micro_fit_all_{ff}_maps{n_maps}_ratio_entropy_df.pkl"))
# %% Inter-brain microstates fit all data
# Based on the microstate topographies estimated on single-brian data
"""
Interbrain features:
1. Average duration of common interbrain microstates (IBDur)
2. Frequency occurrence of common interbrain microstates in the pair (IBOcc)
3. Ratio of total time covered by interbrain common microstates in the pair (IBCov)
4. Transition probability towards common interbrain microstates in the pair (IBTMx)
5. Ratio of joint shannon entropy relative to theoretical max chaos (IBEnt)
"""
for f in len(all_freq_ranges):
ff = freq_names[f]
# Hard-coded the optimal number of microstates based on CV criterion and GEV
n_maps = 5
# Load all microstate results
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
# Load all trialinfos
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}_trialinfos.pkl", "rb") as file:
trialinfo_list = pickle.load(file)
Microstate_names = [chr(ele) for ele in range(65,65+n_maps)]
# Insert Z as the symbol for non common microstate
Microstate_names.insert(0,"Z")
m_labels = [0]*(n_subjects//2)
events = [0]*(n_subjects//2)
m_feats = [0]*(n_subjects//2)
Pair_id = [0]*(n_subjects//2)
for i in range(n_subjects//2):
m_labels[i], events[i], m_feats[i] = interbrain_microstate_feature_computation(i,
n_maps, microstate_results, trialinfo_list, sfreq, event_id, collapsed_event_id)
Pair_id[i] = int(str(Subject_id[2*i])[1:-1])
print(f"Finished computing interbrain microstate features for pair {Pair_id[i]}")
Pair_id = [ele+100 for ele in Pair_id]
# Save the raw microstate features
with open(f"{microstate_save_path}/raw_interbrain_single_micro_fit_all_{ff}_maps{n_maps}.pkl", "wb") as filehandle:
pickle.dump([Pair_id, m_feats], filehandle) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
# * the feature is calculated for each map, where applicable.
# Transition matrix is calculated for each map -> map transition probability
# The first row and column correspond to the non common microstate, i.e.
# there is a different microstate in the pair
# with open(f"{microstate_save_path}/raw_interbrain_single_micro_fit_all_{ff}_maps.pkl", "rb") as file:
# Pair_id, m_feats = pickle.load(file) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
n_pairs = len(Pair_id)
### Convert all features to dataframes for further processing
col_names = ["Pair_ID", "Event_ID", "Microstate", "Value"]
col_values = [Pair_id,list(collapsed_event_id.keys()),Microstate_names]
dtypes = [int,str,str,"float64"]
# Mean duration
Dur_arr = np.stack([ele[0] for ele in m_feats]) # [Subject, event, n_map]
Dur_df = numpy_arr_to_pandas_df(Dur_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Duration"]*len(Dur_df)
Dur_df.insert(2, "Measurement", measurement_id)
# Save df
Dur_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_duration_df.pkl"))
# Frequency of occurrence per sec
Occ_arr = np.stack([ele[1] for ele in m_feats]) # [Subject, event, n_map]
Occ_df = numpy_arr_to_pandas_df(Occ_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Occurrence"]*len(Occ_df)
Occ_df.insert(2, "Measurement", measurement_id)
# Save df
Occ_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_occurrence_df.pkl"))
# Ratio total Time Covered
TCo_arr = np.stack([ele[2] for ele in m_feats]) # [Subject, event, n_map]
TCo_df = numpy_arr_to_pandas_df(TCo_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Time_covered"]*len(TCo_df)
TCo_df.insert(2, "Measurement", measurement_id)
# Save df
TCo_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_ratio_time_covered_df.pkl"))
# Transition matrix should be read as probability of row to column
xi, xj = np.meshgrid(Microstate_names,Microstate_names)
_, arrow = np.meshgrid(Microstate_names,["->"]*(n_maps+1))
transition_info = np.char.add(np.char.add(xj,arrow),xi)
TMx_arr = np.stack([ele[3] for ele in m_feats]) # [Subject, event, n_map, n_map]
TMx_arr = TMx_arr.reshape((n_pairs,len(collapsed_event_id),(n_maps+1)*(n_maps+1))) # Flatten the maps to 1D
col_names = ["Pair_ID", "Event_ID", "Transition", "Value"]
col_values = [Pair_id,list(collapsed_event_id.keys()),transition_info.flatten()]
TMx_df = numpy_arr_to_pandas_df(TMx_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Probability"]*len(TMx_df)
TMx_df.insert(2, "Measurement", measurement_id)
# Save df
TMx_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_transition_df.pkl"))
# Entropy
Ent_arr = np.stack([ele[4] for ele in m_feats]) # [Subject, event]
col_names = ["Pair_ID", "Event_ID", "Value"]
col_values = [Pair_id,list(collapsed_event_id.keys())]
dtypes = [int, str, "float64"]
Ent_df = numpy_arr_to_pandas_df(Ent_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Entropy"]*len(Ent_df)
Ent_df.insert(2, "Measurement", measurement_id)
# Save df
Ent_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_ratio_joint_entropy_df.pkl"))
# =========================================================================
# Repeat for 8 alpha microstates
# =========================================================================
ff = "alpha"
n_maps = 8
# Load all microstate results
with open(f"{microstate_save_path}Reordered/Intrabrain_microstate_fit_all_{ff}{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
# Load all trialinfos
with open(f"{microstate_save_path}Intrabrain_microstate_fit_all_{ff}_trialinfos.pkl", "rb") as file:
trialinfo_list = pickle.load(file)
Microstate_names = [chr(ele) for ele in range(65,65+n_maps)]
# Insert Z as the symbol for non common microstate
Microstate_names.insert(0,"Z")
m_labels = [0]*(n_subjects//2)
events = [0]*(n_subjects//2)
m_feats = [0]*(n_subjects//2)
Pair_id = [0]*(n_subjects//2)
for i in range(n_subjects//2):
m_labels[i], events[i], m_feats[i] = interbrain_microstate_feature_computation(i,
n_maps, microstate_results, trialinfo_list, sfreq, event_id, collapsed_event_id)
Pair_id[i] = int(str(Subject_id[2*i])[1:-1])
print(f"Finished computing interbrain microstate features for pair {Pair_id[i]}")
Pair_id = [ele+100 for ele in Pair_id]
# Save the raw microstate features
with open(f"{microstate_save_path}/raw_interbrain_single_micro_fit_all_{ff}_maps{n_maps}.pkl", "wb") as filehandle:
pickle.dump([Pair_id, m_feats], filehandle) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
# * the feature is calculated for each map, where applicable.
# Transition matrix is calculated for each map -> map transition probability
# The first row and column correspond to the non common microstate, i.e.
# there is a different microstate in the pair
# with open(f"{microstate_save_path}/raw_interbrain_single_micro_fit_all_{ff}_maps.pkl", "rb") as file:
# Pair_id, m_feats = pickle.load(file) # [Subject][Dur_arr,Occ_arr,TCo_arr,TMx_arr,Ent_arr] [Event, map*]
n_pairs = len(Pair_id)
### Convert all features to dataframes for further processing
col_names = ["Pair_ID", "Event_ID", "Microstate", "Value"]
col_values = [Pair_id,list(collapsed_event_id.keys()),Microstate_names]
dtypes = [int,str,str,"float64"]
# Mean duration
Dur_arr = np.stack([ele[0] for ele in m_feats]) # [Subject, event, n_map]
Dur_df = numpy_arr_to_pandas_df(Dur_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Duration"]*len(Dur_df)
Dur_df.insert(2, "Measurement", measurement_id)
# Save df
Dur_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_duration_df.pkl"))
# Frequency of occurrence per sec
Occ_arr = np.stack([ele[1] for ele in m_feats]) # [Subject, event, n_map]
Occ_df = numpy_arr_to_pandas_df(Occ_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Occurrence"]*len(Occ_df)
Occ_df.insert(2, "Measurement", measurement_id)
# Save df
Occ_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_occurrence_df.pkl"))
# Ratio total Time Covered
TCo_arr = np.stack([ele[2] for ele in m_feats]) # [Subject, event, n_map]
TCo_df = numpy_arr_to_pandas_df(TCo_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Time_covered"]*len(TCo_df)
TCo_df.insert(2, "Measurement", measurement_id)
# Save df
TCo_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_ratio_time_covered_df.pkl"))
# Transition matrix should be read as probability of row to column
xi, xj = np.meshgrid(Microstate_names,Microstate_names)
_, arrow = np.meshgrid(Microstate_names,["->"]*(n_maps+1))
transition_info = np.char.add(np.char.add(xj,arrow),xi)
TMx_arr = np.stack([ele[3] for ele in m_feats]) # [Subject, event, n_map, n_map]
TMx_arr = TMx_arr.reshape((n_pairs,len(collapsed_event_id),(n_maps+1)*(n_maps+1))) # Flatten the maps to 1D
col_names = ["Pair_ID", "Event_ID", "Transition", "Value"]
col_values = [Pair_id,list(collapsed_event_id.keys()),transition_info.flatten()]
TMx_df = numpy_arr_to_pandas_df(TMx_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Probability"]*len(TMx_df)
TMx_df.insert(2, "Measurement", measurement_id)
# Save df
TMx_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_transition_df.pkl"))
# Entropy
Ent_arr = np.stack([ele[4] for ele in m_feats]) # [Subject, event]
col_names = ["Pair_ID", "Event_ID", "Value"]
col_values = [Pair_id,list(collapsed_event_id.keys())]
dtypes = [int, str, "float64"]
Ent_df = numpy_arr_to_pandas_df(Ent_arr, col_names, col_values, dtypes)
# Add dummy variable to enabling combining of dataframes
measurement_id = ["Entropy"]*len(Ent_df)
Ent_df.insert(2, "Measurement", measurement_id)
# Save df
Ent_df.to_pickle(os.path.join(microstate_save_path,f"IB_Single_micro_fit_all_{ff}_maps{n_maps}_ratio_joint_entropy_df.pkl"))
# %% Two-brain microstates fit all data
"""
The two observe and imitate conditions are collapesed
Instead of having ppn1 being observer/follower in 8 trials and actor/leader
in 8 trials, we will fix the topomap from "ppn1, top row" to always be
observer and follower. This means for condition 6 and 7, ppn2 will be treated
as ppn1 so the first topomap is still being fitted to the observer/follower!
So the first microstate (top row) will always correspond to the Observer and Follower
And the 2nd paired microstate (bot row) will always correspond to Actor and Leader
Additionally we compute features for 8 trials and then take the average instead
of all 16. This is done in order to compute it for the asymmetrical trials
without flipping, as the flip itself can create artefacts.
And the same process is repeated for the symmetrical conditions to be consistent,,
although it shouldn't have a big impact for those trials
"""
# Compute two-person microstates for each pair, fitted for all data
# We will concatenate the pairs along the channel axis
# Loop over frequencies
for f in len(all_freq_ranges):
ff = freq_names[f]
freq_range0 = all_freq_ranges[f]
# =========================================================================
# First the microstate topographies are determined
# It might be an advantage to run the estimation of microstates on a HPC
# =========================================================================
# Get data from all pairs before performing kmeans
np.random.seed(1234)
n_clusters=[3, 4, 5, 6, 7, 8, 9, 10]
n_runs = 100 # increased to 100 runs!
# Get current time
c_time1 = time_now(); print(c_time1)
# Save RAM by appending directly to array instead of making list and then array
pair_arr_indices = [0]
trialinfo_list = []
events_list = []
for i in range(n_pairs):
tmp_data, tmp_trialinfo, tmp_events = prepare_2P_micro_arr_collapsed_events(i, sfreq, event_id, freq_range=freq_range0, standardize=True)
pair_arr_indices.append(len(tmp_data))
trialinfo_list.append(tmp_trialinfo)
events_list.append(tmp_events)
if i == 0: # first run initiation
micro_data_all = tmp_data
else:
micro_data_all = np.append(micro_data_all,tmp_data, axis=0)
del tmp_data # clear up space
print(f"Finished preparing microstate data for pair {Pair_id[i]}")
# Use cumulative sum to determine indices for each pair's data
pair_indices = np.cumsum(pair_arr_indices)
# Save the trialinfos and events from all pairs, for easier access in later steps
with open(f"{microstate_save_path}Dualmicro_fit_all_{ff}_trial_events_infos.pkl", "wb") as filehandle:
pickle.dump([Pair_id,trialinfo_list,events_list], filehandle) # [maps, L, gfp_peaks, gev, cv_min, pair_idx]
# # with args parser in hpc
# n_maps = n_clusters[(args.map_idx-1)]
# print(f"Running analysis for maps: {n_maps}")
# print("Memory used by the micro data array (GB):",micro_data_all.nbytes*9.31e-10)
for n_maps in n_clusters: # Don't use for loop on the HPC!
# Run the 100 runs in batches of 10 to save underway in case the job script terminates
best_cv_crit = 9999 # initialize unreasonably high value
for r in range(10):
microstate_results = list(kmeans_dualmicro(micro_data_all, n_maps,
n_runs=int(n_runs/10),maxiter=1000))
# Overwrite the maps if a lower CV criterion was found for the initiation
if microstate_results[4] < best_cv_crit:
microstate_results.append(pair_indices)
# Save results
with open(f"{microstate_save_path}Dualmicro_fit_all_{ff}_data_maps{n_maps}.pkl", "wb") as filehandle:
pickle.dump(microstate_results, filehandle) # [maps, L, gfp_peaks, gev, cv_min, pair_idx]
print(f"Updated the microstates. Previous best CV: {best_cv_crit}",
f"new best CV criterion : {microstate_results[4]}")
# Update best cv criterion value
best_cv_crit = microstate_results[4]
print(f"Finished sub-run {r+1} out of 10")
print(f"Finished microstate analysis for n_maps = {n_maps}")
print("Started", c_time1, "\nCurrent",time_now())
# =========================================================================
# # Evaluate microstates fitted to all data
# =========================================================================
# Get summary results
microstate_summary_results = []
for n_maps in n_clusters:
with open(f"{microstate_save_path}Dualmicro_fit_all_{ff}_data_maps{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
# Also save summary results across n_maps
microstate_summary_results.append([microstate_results[0],microstate_results[3],microstate_results[4]])
# Use CV criterion to estimate best number of microstates
cv_gev_arr = np.zeros((len(n_clusters),2))
for imap in range(len(n_clusters)):
gev = np.sum(microstate_summary_results[imap][1])
cv = microstate_summary_results[imap][2]
cv_gev_arr[imap,:] = [cv, gev]
# Convert to Pandas dataframe
col_names = ["n_Microstates", "Fit_Criteria", "Value"]
Fit_Criteria = ["CV Criterion", "Global Explained Variance"]
dtypes = [int,str,"float64"]
cv_gev_df = numpy_arr_to_pandas_df(cv_gev_arr, col_names = col_names, col_values = [n_clusters,Fit_Criteria],
dtypes = dtypes)
# Evaluate optimal n_Microstates
h_order = Fit_Criteria
g = sns.FacetGrid(data=cv_gev_df,row=None,
margin_titles=True, height=8, aspect=1.5)
g = g.map(sns.pointplot,"n_Microstates", "Value", "Fit_Criteria",
dodge=0, capsize=0.18, errorbar=None, linestyles=["-", "-"],
markers=["o", "o"], hue_order=h_order, palette=sns.color_palette())
g.add_legend()
plt.subplots_adjust(top=0.9, right=0.85, left=0.1)
g.fig.suptitle("Mean CV Criterion and GEV", fontsize=18)
g.set_axis_labels(x_var="Number of Microstates",
y_var="GEV and CV",
fontsize=14)
# The lower CV the better. Measure of residual variance
# But the higher GEV the better.
# Save file
g.savefig(f"{fig_save_path}Microstates/Fit_all_{ff}/"+"Dualmicro_fit_all_{ff}_CV_Criterion_GEV"+".png")
# Count which number of microstates have the lowest cv criterion for each subject
min_idx = np.argmin(cv_gev_df.loc[cv_gev_df["Fit_Criteria"]=="CV Criterion","Value"])
cv_gev_df.loc[cv_gev_df["Fit_Criteria"]=="CV Criterion"].iloc[min_idx]
# Visualize the microstates
# Prior to re-ordering
for ii in range(len(n_clusters)):
plot_dualmicro(n_clusters[ii], microstate_summary_results[ii][0], microstate_summary_results[ii][1], epoch.info)
# =========================================================================
# # Re-order two-person microstates
# # This is only run once, after microstates are created
# # We only do it for 8 microstates, which was the optimal number
# =========================================================================
n_maps = 8
ii = n_clusters.index(n_maps)
with open(f"{microstate_save_path}Dualmicro_fit_all_{ff}_data_maps{n_maps}.pkl", "rb") as file:
microstate_results = pickle.load(file)
maps, m_labels, gfp_peaks, gev, cv_min, pair_idx = microstate_results