-
Notifications
You must be signed in to change notification settings - Fork 1
/
latent_analysis.py
1651 lines (1313 loc) · 66.9 KB
/
latent_analysis.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 sys
import pickle
import math
import numpy as np
from numpy.random import RandomState
from scipy.io import loadmat, savemat
from configparser import *
from matplotlib import use
from pylab import *
import matplotlib.pyplot as plt
from matplotlib import gridspec
import matplotlib.colors
import matplotlib.patches as mpatches
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.stats import ttest_ind
from sklearn import manifold
from sklearn.metrics import DistanceMetric
import sys;
from data_preproc import DataPreproc
class StatesAnalysis(object):
'''
Object performing the analysis of the observed latent states in terms
of sleep physiology.
'''
def __init__(self, refDir, expConfigFilename, epochID, threshold, multi, norm, features, groupNames):
# directory containing all the configuration files for the experiment
self.refDir = refDir
# file with configuration details for the launched experiment
self.expConfigFilename = expConfigFilename
# data pre-processing object
self.dpp = DataPreproc()
# loading details from configuration files
self.loadExpConfig()
# id of the epoch to be analysed
self.epochID = int(epochID)
# threshold for latent states to be kept : latent states with
# population smaller than this threshold, are not used for most
# of the produced graphs
self.threshold = int(threshold)
# true if multi-subject experiment
self.multi = multi
# normalization technique to be used for scaling the histogram
# over the observed latent states
self.norm = norm
# which features were used for the analysis : EEG/EMG bands,
# EEG ratios - EMG, pca
self.features = features
if self.multi:
print("A multi-subject experiment is being analyzed..")
# in case of multi subject analysis, the names of mouse groups
# need to be given in the same order as they have been stored
# in the dataset
self.groupNames = [k for k in groupNames.split(',')]
#print(self.groupNames)
np.random.seed(124)
self.prng = RandomState(123)
def loadExpConfig(self):
'''
Method loading the configuration details of the current experiment.
'''
config = ConfigParser()
config.read(self.refDir + "configuration_files/" + self.expConfigFilename)
#-- Experiment details:
self.dataDir = config.get('EXP_DETAILS','dsetDir')
self.expsDir = config.get('EXP_DETAILS','expsDir')
self.expName = config.get('EXP_DETAILS','expID')
self.dSetName = config.get('EXP_DETAILS','dSetName')
self.logFlag = config.getboolean('EXP_DETAILS','logFlag')
self.meanSubtructionFlag = config.getboolean('EXP_DETAILS','meanSubtructionFlag')
self.scaleFlag = config.getboolean('EXP_DETAILS','scaleFlag')
self.scaling = config.get('EXP_DETAILS','scaling')
self.doPCA = config.getboolean('EXP_DETAILS','doPCA')
self.whitenFlag = config.getboolean('EXP_DETAILS','whitenFlag')
self.rescaleFlag = config.getboolean('EXP_DETAILS','rescaleFlag')
self.rescaling = config.get('EXP_DETAILS','rescaling')
self.saveDir = self.refDir + "sample_data/mcRBManalysisMay"
#-- Data Loading function:
def loadData(self):
'''
Method loading the visible data.
'''
os.chdir(self.saveDir)
# Get current path:
print(("Analysing experiment : ", os.getcwd()))
"""
Load visible data
"""
visData = 'visData.npz'
dataFile = np.load(visData)
self.d = dataFile['data']
obsKeys = dataFile['obsKeys'].astype(int)
self.epochTime = dataFile['epochTime']
self.sleepStages = ['Wake', 'NREM', 'REM']
"""
Back-project data to the log space for visualization
"""
print("Backprojecting the data to the log space..")
self.dinit = self.backProjection(self.d)
np.savez('backProjectedData.npz', d=self.dinit, obsKeys=obsKeys, epochTime=self.epochTime)
del obsKeys, dataFile
#-- Function for projecting back the pre-processed data:
def backProjection(self, d):
'''
Method projecting the pre-processed data back to the log-space.
'''
if self.doPCA:
with open('./dataDetails/pca_obj.save') as pcaPklFile:
pca = pickle.load(pcaPklFile)
if self.rescaleFlag:
print("Scaling back to PCA data..")
minMax = np.load('./dataDetails/minmaxFilePCA.npz')
d = self.backProjectionScaling(self.rescaling, d, minMax['dMaxRowPCA'], minMax['dMinRowPCA'],
minMax['dMinPCA'], minMax['dMaxPCA'], minMax['dMeanPCA'], minMax['dStdPCA'])
print("Inverting PCA data..")
d = pca.inverse_transform(d)
if self.scaleFlag:
print("Scaling back to Log data..")
minMax = np.load('./dataDetails/minmaxFileInit.npz')
d = self.backProjectionScaling(self.scaling, d, minMax['dMaxRow'], minMax['dMinRow'], minMax['dMin'],
minMax['dMax'], minMax['dMean'], minMax['dStd'])
return d
def backProjectionScaling(self, scaling, d, dMaxRow, dMinRow, dMin, dMax, dMean, dStd):
'''
Method for projecting back the scaled data.
'''
if 'single' in scaling:
d = ( (d+5.) * (dMaxRow - dMinRow) ) /10. + dMinRow
elif 'global' in scaling:
d = ( (d+5.) * (dMax - dMin) ) /10. + dMin
elif 'baseZeroG' in scaling:
d = d * (dMax - dMin) + dMin
elif 'baseZeroS' in scaling:
d = ( d * (dMaxRow - dMinRow) ) / 10. + dMinRow
elif 'baseZeroCol' in scaling:
d = d * (dMaxRow - dMinRow) + dMinRow
elif 'stdz' in scaling:
d = d * dStd + dMean
elif 'minZero' in scaling:
d = d + dMinRow
return d
#-- Latent States Analysis --#
def analyzeStates(self):
'''
Method performing basic visualization of the input data
associated with the observed latent states.
'''
# Move in the current training epoch's folder
os.chdir('analysis/epoch%d' %self.epochID)
# Get current path:
os.getcwd()
if not os.path.isdir('boxPlotsBackProjectedData'):
os.makedirs('boxPlotsBackProjectedData')
# Load unique latent activations
fileName = 'uniqueStates.npz'
fload = np.load(fileName)
self.uniqueStates = fload['uniqueStates']
# Load obsKeys
fileName = 'obsKeys.npz'
fload = np.load(fileName)
self.obsKeys = fload['obsKeys']
del fload
"""
In case of multi-subject analysis:
insert a column to give to each epoch the label of the strain (e.g. 1,2,3)
it belongs to.
"""
if self.multi:
self.obsKeys = np.insert(self.obsKeys, self.obsKeys.shape[1], 0, axis=1)
for i in range(self.obsKeys.shape[0]):
self.obsKeys[i, self.obsKeys.shape[1]-1] = int(str(self.obsKeys[i, self.obsKeys.shape[1]-2])[0])
self.mouseGroups = np.unique(self.obsKeys[:, self.obsKeys.shape[1]-1])
self.subjects = np.unique(self.obsKeys[:, self.obsKeys.shape[1]-2])
print(("mouseGroups: ", self.mouseGroups))
print(("subjects: ", self.subjects))
for strain in np.unique(self.obsKeys[:, self.obsKeys.shape[1]-1]):
print(("Strain %d: of shape: %d" %(strain, self.obsKeys[self.obsKeys[:, self.obsKeys.shape[1]-1]==strain, :].shape[0])))
#labels = ['f%s' %i for i in range(self.d.shape[1])]
# EEG_labels = ['Theta', 'Delta', 'Ratio', 'Slope', 'Complexity']
EEG_labels = ['IndexW', 'IndexR', 'IndexN', 'Index1', 'Index2', 'Index3', 'Index4', '0-0.5hz', 'Theta', 'Delta']
# EEG_labels = ['IndexW', 'IndexR', 'IndexN', 'Index1', 'Index2', 'Index3', 'Index4', 'Theta', 'Delta']
EMG_labels = ['EMG']
# if self.features=='bands':
# EEG_labels = ['Delta', 'Theta', 'Alpha', 'Beta', 'Gamma']
# elif self.features=='ratios':
# Bands = [r'$\delta$', r'$\theta$', r'$\alpha$', r'$\beta$', r'$\gamma$']
# EEG_labels = []
# for i in range(5):
# for j in range(i+1, 5):
# EEG_labels.append(Bands[i] + '$/$' + Bands[j])
# else:
# EEG_labels = ['f%d' %(i+1) for i in range( self.dinit.shape[1] -1 )]
EEG_range = [math.floor(self.dinit[:,:self.dinit.shape[1]-1].min()), math.ceil(self.dinit[:,:self.dinit.shape[1]-1].max())]
EMG_range = [math.floor(self.dinit[:,self.dinit.shape[1]-1].min()), math.ceil(self.dinit[:,self.dinit.shape[1]-1].max())]
for i in self.uniqueStates[:, 0]:
idx = np.where( self.obsKeys[:, 1] == i )[0]
latent_frames = self.obsKeys[idx, :]
length_awake = round((len(np.where((latent_frames[:,3]==1))[0])/float(len(latent_frames))),3)
length_nrem = round((len(np.where((latent_frames[:,3]==3))[0])/float(len(latent_frames))),3)
length_rem = round((len(np.where((latent_frames[:,3]==5))[0])/float(len(latent_frames))),3)
#dPlot = [self.d[idx, j] for j in range(self.d.shape[1])]
# print(f"self.dinit: {self.dinit}")
print(f"self.dinit.shape[1]: {self.dinit.shape[1]}")
dPlotEEG = [self.dinit[idx, j] for j in range(self.dinit.shape[1]-1)]
dPlotEMG = [self.dinit[idx, self.dinit.shape[1]-1]]
# print(f"dPlotEEG: {dPlotEEG}")
# print(f"dPlotEMG: {dPlotEMG}")
# visualize boxplots per latent state
self.BoxPlotsDouble(dPlotEEG, dPlotEMG, './boxPlotsBackProjectedData/', len(idx), i, EEG_labels,
EMG_labels, length_awake, length_nrem, length_rem, EEG_range, EMG_range)
def groupStatistics(self):
'''
Method performing some statistical analysis over the
under analysis mouse groups.
1: bar plot per latent state displaying the number of epochs
each latent state falls in each subject.
2: visualization of the p-values of the 2-sample independent t-test.
This test aims at helping us find the mouse group specific latent
states.
'''
"""
Create output directory
"""
self.groupStatistics = 'groupStatistics'
if not os.path.isdir(self.groupStatistics):
os.makedirs(self.groupStatistics)
os.chdir(self.groupStatistics)
os.getcwd()
if not os.path.isdir('groupBoxPlots'):
os.makedirs('groupBoxPlots')
if not os.path.isdir('ttest'):
os.makedirs('ttest')
if not os.path.isdir('barPlots'):
os.makedirs('barPlots')
"""
Find the unique latent-states' IDs
"""
self.lstatesIDs = np.unique(self.obsKeys[:, 1])
self.lstatesPopulation = np.bincount(self.obsKeys[:, 1])
subjectsIDs = np.unique(self.obsKeys[:, self.obsKeys.shape[1]-2])
self.strainIDs = np.unique(self.obsKeys[:, self.obsKeys.shape[1]-1])
'''
Sort subject IDs so that we have the strains in order:
'''
self.subjectsIDs_ordered = []
'''
and create a dictionary : the strainID and the number of animals it contains:
'''
self.num_subjs_per_strain = {}
for str_ID in self.strainIDs:
self.num_subjs_per_strain[str_ID] = 0
for subject in subjectsIDs:
if subject not in self.subjectsIDs_ordered:
if int(str(subject)[0])==str_ID:
self.subjectsIDs_ordered.append(subject)
self.num_subjs_per_strain[str_ID] = self.num_subjs_per_strain[str_ID]+1
"""
Compute the per subject distribution: a discrete distribution per subject
(i.e., number of frames each subject appers in each latent state)
"""
#--- Create Array : (M_animals * N_lstates)
self.subjectsDistr = np.zeros((len(self.subjectsIDs_ordered), len(self.lstatesIDs)), dtype=np.int32)
#-- Insert a labels column : label = MouseID
self.subjectsDistr = np.insert(self.subjectsDistr, self.subjectsDistr.shape[1], self.subjectsIDs_ordered, axis=1)
#-- Insert a strain column :
self.subjectsDistr = np.insert(self.subjectsDistr, self.subjectsDistr.shape[1], 0, axis=1)
#-- Iterate through columns==animals and define the strainID :
for i in range(self.subjectsDistr.shape[0]):
self.subjectsDistr[i, self.subjectsDistr.shape[1]-1] = int(str(self.subjectsDistr[i, self.subjectsDistr.shape[1]-2])[0])
#-- Create Subjects' Distribution : for how many epochs each subject appears in each latent-state
for i in range(self.subjectsDistr.shape[0]):
subjectFrames = self.obsKeys[self.obsKeys[:,4]==self.subjectsDistr[i, self.subjectsDistr.shape[1]-2],:]
print(("Subject:", self.subjectsDistr[i, self.subjectsDistr.shape[1]-2], "of latent size:", subjectFrames.shape))
for lstate in self.lstatesIDs:
self.subjectsDistr[i, lstate] = len(np.where(subjectFrames[:, 1]==lstate)[0])
self.strainIDs1 = self.strainIDs
savemat('subjectsDistribution.mat', mdict={'subjectsDistribution':self.subjectsDistr})
'''
Computing and visualizing statistics
'''
'''
Split subjectsDistr into strains:
'''
strainsDistr_dict = {}
for strainID in self.strainIDs:
strainsDistr_dict[strainID] = self.subjectsDistr[np.where(self.subjectsDistr[:, self.subjectsDistr.shape[1]-1]==strainID)[0], :self.subjectsDistr.shape[1]-2]
print(("Strain: ", strainID, " of shape: ", strainsDistr_dict[strainID].shape))
'''
Create a dictionary to save for each latent-state the t-test scores:
'''
latentDict = {}
latentDict_pvalues = {}
latentDict_statistics = {}
'''
Create dictionary : Latent - Counts
'''
LatentCounts = {}
'''
Iterate through latent states:
########## TO DO: simplify loop! ##########
'''
for lstate in self.lstatesIDs:
##########################################################
"""
Bar-plot part: how many times each subject appears in the current latent-state
"""
latent_frames = self.obsKeys[np.where(self.obsKeys[:, 1] == lstate)[0], :]
length_awake = round((len(np.where((latent_frames[:, latent_frames.shape[1]-3]==1))[0])/float(len(latent_frames))),3)
length_nrem = round((len(np.where((latent_frames[:, latent_frames.shape[1]-3]==3))[0])/float(len(latent_frames))),3)
length_rem = round((len(np.where((latent_frames[:, latent_frames.shape[1]-3]==5))[0])/float(len(latent_frames))),3)
'''
Initialize subjects' counts to 0:
'''
subjects_counts = {}
for subject in self.subjectsIDs_ordered:
#print subject
subjects_counts[subject] = 0
'''
Iterate through frames in the current latent state &
count how many times each subject appears in:
'''
for l_frame in range(latent_frames.shape[0]):
subjects_counts[latent_frames[l_frame, latent_frames.shape[1]-2]] = subjects_counts[latent_frames[l_frame, latent_frames.shape[1]-2]] + 1
'''
Bar plot
'''
N = len(self.subjectsIDs_ordered)
ind = np.arange(N)
C_matrix = np.zeros((len(subjects_counts),2), dtype=np.int32)
i = 0
for k in list(subjects_counts.keys()):
C_matrix[i, 0] = k
C_matrix[i, 1] = subjects_counts[k]
i = i+1
C_matrix = C_matrix[C_matrix[:, 0].argsort()]
#-- Sort subject IDs so that we have the strains in order:
Counts = []
Lb = []
for str_ID in self.strainIDs1:
for subject in C_matrix[:,0]:
idx_posit = np.where(C_matrix[:,0]==subject)[0][0]
if subject not in Lb:
if int(str(subject)[0])==str_ID:
Lb.append(subject)
Counts.append(C_matrix[idx_posit,1])
LatentCounts['l_state_' + str(lstate)] = {}
LatentCounts['l_state_' + str(lstate)]['counts'] = np.asarray(Counts)
LatentCounts['l_state_' + str(lstate)]['subjects'] = np.asarray(Lb)
"""
Statistical test part: Indipendent 2 sample ttest
"""
'''
Create a square array (Number_of_strains * Number_of_strains)
'''
tt_statistic = np.zeros((len(self.strainIDs), len(self.strainIDs)), dtype=float32)
tt_pvalues = np.zeros((len(self.strainIDs), len(self.strainIDs)), dtype=float32)
'''
Iterate through strains & compute the pairwise tests:
'''
for i in range(len(self.strainIDs)-1):
for j in range(i+1,len(self.strainIDs)):
strain_i = strainsDistr_dict[self.strainIDs[i]]
strain_j = strainsDistr_dict[self.strainIDs[j]]
[tt_statist, tt_p] = ttest_ind(strain_i[:,lstate], strain_j[:,lstate], equal_var = True)
tt_statistic[i,j] = tt_statist
tt_statistic[j,i] = tt_statist
tt_pvalues[i,j] = tt_p
tt_pvalues[j,i] = tt_p
for i_el in range(tt_pvalues.shape[0]):
tt_pvalues[i_el, i_el] = 1.
"""
Visualization part
"""
# Bar plot
fig = plt.figure(figsize=(20,15))
ax1 = fig.add_subplot(111)
#fig.suptitle('Number of epochs associated with this latent state: ' + str(len(latent_frames)) + '\nAwake: ' + str(length_awake*100) + '%, Nrem: ' + str(length_nrem*100) + '%, Rem: ' + str(length_rem*100) + '%', fontsize=30, fontweight='bold')
fig.suptitle('Latent State ' + str(lstate) + '\nWakefulness: ' + str(round(length_awake,3)*100) + '%, NREM Sleep: ' + str(round(length_nrem,3)*100) + '%, REM Sleep: ' + str(round(length_rem,3)*100) + '%' + '\nTotal number of epochs: ' + str(len(latent_frames)), fontsize=30, fontweight='bold')
ax1.spines['top'].set_visible(False)
#ax.spines['top'].set_color('none')
ax1.spines['right'].set_visible(False)
#ax.spines['right'].set_color('none')
ax1.spines['bottom'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax1.yaxis.set_ticks_position('left')
ax1.xaxis.set_ticks_position('bottom')
width = 0.35
#id_start = 0
strain_bar = {}
colors = ['#b2182b', '#238b45', '#238b45', '#3690c0', '#3690c0', '#023858']
idx_start = 0
idx_end = self.num_subjs_per_strain[self.strainIDs1[0]]
strain_bar[0] = ax1.bar(ind[idx_start:idx_end], Counts[idx_start:idx_end]/self.lstatesPopulation[lstate], width, color=colors[0], edgecolor = "none")
for i in range(len(self.num_subjs_per_strain)-1):
idx_start = idx_start+self.num_subjs_per_strain[self.strainIDs1[i]]
idx_end = idx_end+self.num_subjs_per_strain[self.strainIDs1[i+1]]
strain_bar[i+1] = ax1.bar(ind[idx_start:idx_end], Counts[idx_start:idx_end]/self.lstatesPopulation[lstate], width, color=colors[i+1], edgecolor = "none")
ax1.set_ylabel('Count', fontweight='bold', fontsize=30)
ax1.set_xlabel('Subjects', fontweight='bold', fontsize=30)
xTickMarks = ['s%s' %str(j) for j in Lb]
ax1.set_xticks(ind+width/2)
xtickNames = ax1.set_xticklabels(xTickMarks, fontweight='bold')
ax1.xaxis.set_ticks_position('none')
ax1.yaxis.set_ticks_position('none')
legend_properties = {'weight':'bold', 'size':25}
if len(self.strainIDs)>2:
ax1.legend((strain_bar[0], strain_bar[1], strain_bar[3]), self.groupNames, bbox_to_anchor=(.9, .9), loc=2, borderaxespad=0., prop=legend_properties)
else:
ax1.legend((strain_bar[0], strain_bar[1]), self.groupNames, bbox_to_anchor=(.9, .9), loc=2, borderaxespad=0., prop=legend_properties)
plt.setp(xtickNames, rotation=45, fontsize=20)
yint = []
locs, l = plt.yticks()
for each in locs:
yint.append( round(each, 2) )
plt.yticks(yint)
ax1.set_yticklabels(ax1.get_yticks(), fontweight='bold', fontsize=20)
fname = 'lState_' + str(lstate) + '.png'
fname = os.path.join('./barPlots/', fname)
fig.savefig(fname, transparent=True, dpi=100)
plt.close(fig)
"""
T-test visualization
"""
fig = plt.figure(figsize=(33, 33))
ax4 = fig.add_subplot(111)
fig.suptitle('Independent two-sample t-test: p-values', fontsize=60, fontweight='bold')
#hmat = ax4.pcolor(tt_pvalues, cmap='RdYlGn_r', vmin=0., vmax=1.)
hmat = ax4.pcolor(tt_pvalues, cmap='gray_r', vmin=0., vmax=1.)
#ax4.set_title('Independent two-sample t-test: p-values', fontsize=25, fontweight='bold')
# text portion
if len(self.strainIDs)>2:
ind_array = np.arange(0., 3., 1.)
else:
ind_array = np.arange(0., 2., 1.)
x, y = np.meshgrid(ind_array, ind_array)
for x_val, y_val in zip(x.flatten(), y.flatten()):
c = tt_pvalues[x_val.astype(np.int32), y_val.astype(np.int32)]
if c==1.0 :
ax4.text(x_val+0.5, y_val+0.5, c, va='center', ha='center', color='w', fontweight='bold', fontsize=50)
else:
ax4.text(x_val+0.5, y_val+0.5, round(c, 3), va='center', ha='center', color='k', fontweight='bold', fontsize=50)
ax4.set_xticks(np.arange(tt_pvalues.shape[0])+0.5, minor=False)
ax4.set_yticks(np.arange(tt_pvalues.shape[1])+0.5, minor=False)
# want a more natural, table-like display
ax4.invert_yaxis()
ax4.xaxis.tick_top()
ax4.set_xticklabels(self.groupNames, minor=False, fontweight='bold', fontsize=50)
ax4.set_yticklabels(self.groupNames, minor=False, fontweight='bold', fontsize=50)
divider4 = make_axes_locatable(ax4)
cax4 = divider4.append_axes("right", size="5%", pad=0.1)
cb = plt.colorbar(hmat, cax=cax4)
for l in cb.ax.yaxis.get_ticklabels():
l.set_weight("bold")
l.set_fontsize(40)
fname = 'lState_' + str(lstate) + '.png'
fname = os.path.join('./ttest/', fname)
fig.savefig(fname, transparent=True, dpi=100)
plt.close(fig)
"""
Group-boxPlot
"""
data_to_plot = []
for k in list(strainsDistr_dict.keys()):
data_to_plot.append(strainsDistr_dict[k][:, lstate]/self.lstatesPopulation[lstate])
fig = plt.figure(figsize=(15,12))
fig.suptitle('LS ' + str(lstate) + ' - Total: ' + str(len(latent_frames)) + ' epochs' + '\nWAKE: ' + str(length_awake*100) + '%, NREM: ' + str(length_nrem*100) + '%, REM: ' + str(length_rem*100) + '%', fontsize=35, fontweight='bold')
ax = fig.add_subplot(111)
ax.grid(False)
ax.patch.set_facecolor('0.85')
ax.patch.set_alpha(0.5)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_linewidth(5)
ax.spines['bottom'].set_color('k')
ax.spines['left'].set_linewidth(5)
ax.spines['left'].set_color('k')
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticks_position('none')
ax.set_ylabel('Frequency', fontweight='bold', fontsize=35)
bp = plt.boxplot(data_to_plot, patch_artist=True)
plt.setp(bp['boxes'], # customise box appearance
edgecolor='k', # outline colour
linewidth=5., # outline line width
facecolor='None') # fill box with colour
plt.setp(bp['whiskers'], color='k', linestyle='--', linewidth=4.5)
plt.setp(bp['medians'], # customize median lines
color='k', # line colour
linewidth=5.) # line thickness
xtickNames = ax.set_xticklabels(self.groupNames)
plt.setp(xtickNames, fontsize=35, fontweight='bold')
yint = []
locs, labels = plt.yticks()
for each in locs:
yint.append(round(each, 2))
plt.yticks(yint)
ax.set_yticklabels(ax.get_yticks(), fontweight='bold', fontsize=30)
fname = 'lstate%d.jpeg' %lstate
fname = os.path.join('./groupBoxPlots/', fname)
fig.savefig(fname, format='jpeg', transparent=True, dpi=100)
plt.close(fig)
def visibleDistributions(self):
'''
Method computing & visualizing the input data distributions
associated with the observed latent states.
'''
if not os.path.isdir('distributions'):
os.makedirs('distributions')
"""
Set features' labels for visualization part
"""
self.visibleFeatures = ['v%d' %(i+1) for i in range(self.d.shape[1])]
self.initFeatures = ['IndexW', 'IndexR', 'IndexN', 'Index1', 'Index2', 'Index3', 'Index4', '0-0.5hz', 'Theta', 'Delta']
# if self.features=='bands':
# self.initFeatures = ['Delta', 'Theta', 'Delta/Theta', 'EMG']
# elif self.features=='ratios':
# Bands = [r'$\delta$', r'$\theta$', r'$\alpha$', r'$\beta$', r'$\gamma$']
# self.initFeatures = []
# for i in range(5):
# for j in range(i+1, 5):
# self.initFeatures.append(Bands[i] + '$/$' + Bands[j])
# self.initFeatures.append('EMG')
# else:
# self.initFeatures = ['f%d' %(i+1) for i in range( self.dinit.shape[1] )]
"""
Iterate through centroids/latent states and infer the visible
data distributions
"""
visibleDistributions = {}
backProjectedDistributions = {}
minCovVis = 1.
maxCovVis = -1.
minCovBack = 1.
maxCovBack = -1.
for lstate in self.uniqueStates[:, 0]:
if not os.path.isdir('./distributions/lState%d' %lstate):
os.makedirs('./distributions/lState%d' %lstate)
idx = np.where( self.obsKeys[:, 1]==lstate )[0]
d_visible = self.d[idx, :]
d_back = self.dinit[idx, :]
visibleDistributions['lstate%d' %lstate] = {}
backProjectedDistributions['lstate%d' %lstate] = {}
visibleDistributions['lstate%d' %lstate]['mean'] = d_visible.mean(axis=0)
visibleDistributions['lstate%d' %lstate]['cov'] = np.cov(d_visible.T)
visibleDistributions['lstate%d' %lstate]['data'] = d_visible
backProjectedDistributions['lstate%d' %lstate]['mean'] = d_back.mean(axis=0)
backProjectedDistributions['lstate%d' %lstate]['cov'] = np.cov(d_back.T)
backProjectedDistributions['lstate%d' %lstate]['data'] = d_back
"""
Look for min/max values of all covariance matrices for scaling matrices
for visualization if wished
"""
if np.cov(d_back.T).min() < minCovBack:
minCovBack = np.cov(d_back.T).min()
if np.cov(d_back.T).max() > maxCovBack:
maxCovBack = np.cov(d_back.T).max()
if np.cov(d_visible.T).min() < minCovVis:
minCovVis = np.cov(d_visible.T).min()
if np.cov(d_visible.T).max() > maxCovVis:
maxCovVis = np.cov(d_visible.T).max()
"""
Visualize distributions
"""
self.visualizeDistribution(d_visible, minCovVis, maxCovVis, self.visibleFeatures, './distributions/lState%d/' %lstate, 'visible')
self.visualizeDistribution(d_back, minCovVis, maxCovVis, self.initFeatures, './distributions/lState%d/' %lstate, 'backProjected')
savemat('./distributions/visibleDistributions.mat', mdict={'visibleDistributions':visibleDistributions})
savemat('./distributions/projecteddBackLogDistr.mat', mdict={'projecteddBackLogDistr':backProjectedDistributions})
# Function for visualizing the distribution of each latent state over
# the three sleep stages as a colorMat
def stageDistribution(self):
'''
Method computing the distribution of each latent state over
the three sleep stages & visualizing it as a colorMat.
'''
nonSingle = self.uniqueStates[self.uniqueStates[:, 1] > self.threshold, :]
ids_NonSingle = np.unique(nonSingle[:, 0])
#--- Create save folder :
if not os.path.isdir('heatMap'):
os.makedirs('heatMap')
"""
Compute each latent state's PDF according to how many epochs
were manually labeled as Wakefulness, NREM, REM. This can be
visualized with an RGB color shade.
"""
self.lstateColor, self.lstateCount = self.lstateStageDistribution(self.obsKeys, 1, 3)
np.savez_compressed('./heatMap/lstateColor.npz', lstateColor=self.lstateColor, lstateCount=self.lstateCount)
#-- Re-order matrix for Visualization:
self.C1 = self.reorderMat(self.lstateColor)
#-- Visualize array:
column_labels = ['Wakefulness', 'NREM', 'REM']
self.displayMat(self.lstateColor[self.C1, :], column_labels, './heatMap/heatMap')
#--- Remove the singleton Latent-states:
self.idxFramesKeep = []
for i in range(self.obsKeys.shape[0]):
if self.obsKeys[i, 1] in ids_NonSingle:
self.idxFramesKeep.append(i)
self.lstateColorThresh, lstateCount2 = self.lstateStageDistribution(self.obsKeys[self.idxFramesKeep, :], 1, 3)
# savemat:
#savemat('./heatMap/thresholdedlstatesColor.mat', mdict={'lstateColor':lstateColor2})
np.savez('./heatMap/thresholdedlstatesColor.npz', lstateColor=self.lstateColorThresh, lstateCount=lstateCount2)
#-- Re-order matrix for Visualization:
self.C2 = self.reorderMat(self.lstateColorThresh)
#-- Visualize array:
self.displayMat(self.lstateColorThresh[self.C2,:], column_labels, './heatMap/heatMapThresholded')
del nonSingle, ids_NonSingle, lstateCount2
def computeTransitions(self):
'''
Method computing the transition probabilities array
'''
if not os.path.isdir('transMatrices'):
os.makedirs('transMatrices')
""" Compute overall experiment transitions """
self.obsKeysGroup = self.obsKeys
self.transitionsMatrix('./transMatrices/')
del self.obsKeysGroup
""" Iterate through videoIDs if mulit-videos experiment """
if self.multi:
for self.group in self.mouseGroups:
self.obsKeysGroup = self.obsKeys[self.obsKeys[:, self.obsKeys.shape[1]-1] == self.group, :]
self.transitionsMatrix('./transMatrices/')
# del self.obsKeysGroup
def transitionsMatrix(self, saveDir):
'''
Method computing the transition probabilities from each
latent state to the rest and putting them to a square matrix.
'''
"""
Find the unique centroids & their occurence
"""
centroidsOccurence = np.bincount( self.obsKeys[:, 1] )
"""
Create the transitions matrix : according to the frame by frame transition
"""
transMat = np.zeros(( len(self.uniqueStates), len(self.uniqueStates) ), dtype=float32)
for i in range(0, len( self.obsKeysGroup )-1):
if ( self.obsKeysGroup[i+1, 0] - self.obsKeysGroup[i, 0] ) == 1:
a = self.obsKeysGroup[i, 1]
b = self.obsKeysGroup[i+1, 1]
transMat[a,b] = transMat[a,b] + 1
if self.multi:
#savemat(saveDir + 'countTransMat%d.mat' %self.group, mdict={'countTransMat':transMat})
np.savez(saveDir + 'countTransMat%d.npz' %self.group, countTransMat=transMat)
else:
#savemat(saveDir + 'countTransMat.mat', mdict={'countTransMat':transMat})
np.savez(saveDir + 'countTransMat.npz', countTransMat=transMat)
transMat = transMat/transMat.sum(axis=1)[:,None]
where_are_NaNs = np.isnan(transMat)
transMat[where_are_NaNs] = 0
if self.multi:
#savemat(saveDir + 'transitionsMat%d.mat' %self.group, mdict={'transitionsMat':transMat})
np.savez(saveDir + 'transitionsMat%d.npz' %self.group, transitionsMat=transMat)
else:
#savemat(saveDir + 'transitionsMat.mat', mdict={'transitionsMat':transMat})
np.savez(saveDir + 'transitionsMat.npz', transitionsMat=transMat)
"""
Matrix visualization
"""
if self.multi:
self.displayTransitionsArray(transMat, './transMatrices/transitionsMat%d' %self.group)
else:
self.displayTransitionsArray(transMat, './transMatrices/transitionsMat')
"""
Detect & remove singletons
"""
idx = np.where( centroidsOccurence <= self.threshold )[0]
transMat = np.delete(transMat, idx, 0)
transMat = np.delete(transMat, idx, 1)
#savemat(saveDir + 'thresholdedStatesOnMatrix.mat', mdict={'thresholdedStatesOnMatrix': np.delete(self.uniqueStates[:, 0], idx)})
np.savez(saveDir + 'thresholdedStatesOnMatrix.npz', thresholdedStatesOnMatrix=np.delete(self.uniqueStates[:, 0], idx))
if self.multi:
#savemat(saveDir + 'transitionsMatThresholded%d.mat' %self.group, mdict={'transitionsMat':transMat})
np.savez(saveDir + 'transitionsMatThresholded%d.npz' %self.group, transitionsMat=transMat)
else:
#savemat(saveDir + 'transitionsMatThresholded.mat', mdict={'transitionsMat':transMat})
np.savez(saveDir + 'transitionsMatThresholded.npz', transitionsMat=transMat)
if self.multi:
self.displayTransitionsArray(transMat, './transMatrices/transitionsMatThresholded%d' %self.group)
else:
self.displayTransitionsArray(transMat, './transMatrices/transitionsMatThresholded')
del transMat, idx, centroidsOccurence, where_are_NaNs
# Function for computing and visualizing entropy & Mutual Information
def entropyMIcontrol(self):
'''
Method computing the entropy and mutual information of the
observed latent states.
'''
if not os.path.isdir('entropyMI'):
os.makedirs('entropyMI')
""" Latent states' PDF:
lstatePDF = p(stage | lstate) """
lstatePDF = np.concatenate((self.uniqueStates[:, :2], self.lstateColor), axis=1)
countsArray = np.concatenate((self.uniqueStates[:, :2], self.lstateCount), axis=1)
""" Compute the Marginal of each Stage (class marginal)
..where stagePDF = p(lstate | stage) """
stagePDF = self.lstateCount
stagePDF = stagePDF.astype(float32)
stagePDF = stagePDF/stagePDF.sum(axis=0)
stagePDF = np.concatenate((self.uniqueStates[:, :2], stagePDF), axis=1)
np.savez_compressed('./entropyMI/lstatePDF.npz', lstatePDF=lstatePDF, lstateCount=countsArray)
np.savez('./entropyMI/stagePDF.npz', stagePDF=stagePDF)
#savemat('./entropy/lstatePDF.mat', mdict={'lstatePDF':lstatePDF})
#savemat('./entropy/lstateCount.mat', mdict={'lstateCount':countsArray})
#savemat('./entropy/stagePDF.mat', mdict={'stagePDF':stagePDF})
"""
Remove latent states smaller than the desired threshold
"""
idx = np.where( self.uniqueStates[:, 1] <= self.threshold )[0]
np.savez('./entropyMI/removedStates.npz', removedStates=self.uniqueStates[idx, 0])
#savemat('./entropy/removedStates.mat', mdict={'removedStates':self.uniqueStates[idx, 0]})
lstatePDF = np.delete(lstatePDF, idx, 0)
countsArray = np.delete(countsArray, idx, 0)
stagePDF = np.delete(stagePDF, idx, 0)
""" Compute the Mutual-Information : I(lstates; stages) """
MI = self.mutualInformation(countsArray[:, 2:])
with open ('./entropyMI/mutualInformation.txt','w') as f:
f.write("\n The mutual information is : %s bits" %MI)
f.close()
""" Compute the Entropy of each latent state """
lstateEntropy = self.variableEntropy(lstatePDF[:, 2:])
lstateEntropy = np.concatenate((lstatePDF[:, :2], lstateEntropy), axis=1)
np.savez('./entropyMI/lstatesEntropy.npz', lstateEntropy=lstateEntropy)
#savemat('./entropy/lstateEntropy.mat', mdict={'lstateEntropy':lstateEntropy})
self.entropiesHistogram(lstateEntropy[:, lstateEntropy.shape[1]-1], 'entropyMI')
""" Compute the Entropy of each stage """
stagesH, Hx = self.stageEntropy(countsArray[:, 2:], './entropyMI/mutualInformation.txt')
np.savez('./entropyMI/stageEntropy.npz', stageEntropy=stagesH)
#savemat('./entropy/stageEntropy.mat', mdict={'stageEntropy':stagesH})
""" Compute the mutual information for each stage """
MI_stage = self.mutualInformation_perStage(countsArray[:, 2:])
with open ('./entropyMI/mutualInformation.txt','a') as f:
f.write("\n Stage Entropy:")
f.write("\n Wakefulness = %s" %stagesH[0])
f.write("\n NREM = %s" %stagesH[1])
f.write("\n REM = %s\n" %stagesH[2])
f.write("\n Stage Normalized MI:")
f.write("\n The MI/H(wake) = %s" %(MI_stage[0]/stagesH[0]))
f.write("\n The MI/H(nrem) = %s" %(MI_stage[1]/stagesH[1]))
f.write("\n The MI/H(rem) = %s\n" %(MI_stage[2]/stagesH[2]))
f.write("\n Overall Normalized MI:")
f.write("\n The MI/H(Stage) = %s" %(MI/Hx))
f.close()
self.MI_stimulusH_barPlot(MI_stage, stagesH, MI/Hx, 'entropyMI')
def mutualInformation(self, Count):
'''
Computes the mutual information
MI(lstates; stages) =
sum( p(lstate, stage) * log2 ( p(lstate, stage) / ( p(lstate)*p*(stage) ) )
'''
Count = Count.astype(float32)
""" total population """
Total_sum = Count.sum()
""" p(latent_state) = sum_over_lstate / total_population """
p_latent = Count.sum(axis=1)/Total_sum
""" p(latent_stage) = sum_over_stage / total_population """
p_stage = Count.sum(axis=0)/Total_sum
MI = 0
""" Iterate through latent states """
for i in range(Count.shape[0]):
for j in range(Count.shape[1]):
if Count[i,j] != 0.:
""" Compute p(lstate, stage) """
p_li_sj = Count[i,j]/Total_sum
denominator = p_latent[i]*p_stage[j]
MI += p_li_sj*np.log2(p_li_sj/denominator)
return MI
def mutualInformation_perStage(self, Count):
'''
Computes the mutual information
MI(lstates; stages) =
sum( p(lstate, stage) * log2 ( p(lstate, stage) / ( p(lstate)*p*(stage) ) )
'''
Count = Count.astype(float32)
""" total population """
Total_sum = Count.sum()
""" p(latent_state) = sum_over_lstate / total_population """
p_latent = Count.sum(axis=1)/Total_sum
""" p(latent_stage) = sum_over_stage / total_population """
p_stage = Count.sum(axis=0)/Total_sum
MI = []
""" Iterate through stages """
for j in range(Count.shape[1]):
MI_j = 0
""" Iterate through latent states """
for i in range(Count.shape[0]):
if Count[i,j] != 0.:
""" Compute p(lstate, stage) """
p_li_sj = Count[i,j]/Total_sum
denominator = p_latent[i]*p_stage[j]
MI_j += p_li_sj*np.log2(p_li_sj/denominator)
MI.append(MI_j)
return np.asarray(MI)
def variableEntropy(self, latent_PDF):
'''
Computes the entropy of a discrete random variable in bits.
H(X) = -sum( p(x)*log2(p(x)), for x in X.
'''
latent_PDF = np.insert(latent_PDF, latent_PDF.shape[1], 0, axis=1)
"""
Iterate through latent states
"""
for p in range(latent_PDF.shape[0]):
Hx = 0.
for i in range(latent_PDF.shape[1]):