-
Notifications
You must be signed in to change notification settings - Fork 1
/
makefigures.py
8492 lines (5367 loc) · 325 KB
/
makefigures.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/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 9 16:36:50 2019
@author: mahajnal
"""
from sklearn.semi_supervised import LabelSpreading
from run import *
import numpy as np
import scipy as sp
import imageio
import quantities as pq
import pandas as pd
import os
import pickle
import h5py
#import matplotlib.image as mimg
import matplotlib.colors as mcs
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.colors as clrs
import matplotlib.lines
import matplotlib.patches as patches
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import mpl_toolkits.mplot3d.art3d as art3d
#import seaborn as sns
import neo
import neurophysiology as neph
import neurodiscover as nedi
import neurobayesian as neba
import preprocess
from physiology import getmovementpctimecourses # movementpcslist dimensions are (trials,timecourse,pcs)
import figs
plt.rcParams.update({'font.size': 24})
plt.rcParams.update({'legend.fontsize': 20})
plt.rcParams.update({'lines.linewidth': 1})
# plt.rcParams.update({'savefig.dpi': 600})
# info about figure absolute sizes and nice fonts: https://jwalton.info/Embed-Publication-Matplotlib-Latex/
globalsave = 1
# continuous_method = 'instfr' # JRC spike sorting
continuous_method = 'ks2ifr' # kilosort2 spike sorting, with no drift
# _____________
# publications:
conference = False
resultpath = 'figures/'
ext = '.pdf'
# ext = '.png'
# resultpathprefix = '../results_ks/'
# resultpathseries = 'tribe/'
# resultpath = resultpathprefix + resultpathseries
def drawschematics(ax,wix=None,what=''):
whatlist = ['decoderscheme legend','decoderscheme intime','decoderscheme crosstime',\
'decoderscheme crossblock','decoderscheme intime preonly',\
'decoderscheme crosstime prepre','decoderscheme crosstime preon',\
'decoderscheme crossblock aa+ai','decoderscheme withinblock aa+ii',\
'decoderscheme crossblock ii+ia','decoderscheme PCA space']
if wix!=None:
what = whatlist[wix]
# helper aliases:
trp = [0,0,0,0] # transparent color
lw = 3 # linewidth
#these lines help when designing the plots; comment them out for production
# fig = plt.figure(figsize=(12,12))
# ax = fig.gca()
# what = 'decoderscheme crossblock'
# ax.plot([0,0],[-0.5,0.5],'o')
# ax.set_xlim(0,1)
# ax.set_ylim(0,1)
# ax.grid('on')
# plot each schematics
if what=='decoderscheme legend': # 0
ax.add_patch(plt.Rectangle((0.25,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.65,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.35,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.75,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.35,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.75,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.4,0.6,0.26,-0.22, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.7,0.6,-0.26,-0.22, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.01,0.68, 'training\ndata', transform=ax.transAxes )
ax.text(0.01,0.28, 'testing\ndata', transform=ax.transAxes )
ax.text(0.35,0.85, 'condition 1', ha='center', transform=ax.transAxes )
ax.text(0.75,0.85, 'condition 2', ha='center', transform=ax.transAxes )
# ax.text(0.55,0.95, 'decoding paradigms' , ha='center', transform=ax.transAxes )
elif what=='decoderscheme intime': # 1
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.7,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.8,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.2,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.5,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.8,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.2,0.85, 'PRE', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, 'ON', ha='center', transform=ax.transAxes )
ax.text(0.8,0.85, 'POST', ha='center', transform=ax.transAxes )
elif what=='decoderscheme intime preonly': # 2
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.2,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.2,0.85, 'PRE', ha='center', transform=ax.transAxes )
elif what=='decoderscheme crosstime': # 3
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.7,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.8,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.2,0.6,0.215,-0.215, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.5,0.6,0.215,-0.215, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.2,0.85, 'PRE', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, 'PRE', ha='center', transform=ax.transAxes )
ax.text(0.8,0.85, 'ON', ha='center', transform=ax.transAxes )
elif what=='decoderscheme crossblock': # 4
ax.add_patch(plt.Rectangle((0.2,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.6,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.3,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.7,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.65,0.6,-0.26,-0.22, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.3,0.85, 'initital,\ntransition', ha='center', transform=ax.transAxes )
ax.text(0.7,0.85, 'multi-\nmodal', ha='center', transform=ax.transAxes )
elif what=='decoderscheme crosstime prepre': # 5
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.2,0.6,0.215,-0.215, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.2,0.85, 'PRE', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, 'PRE', ha='center', transform=ax.transAxes )
elif what=='decoderscheme crosstime preon': # 6
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.arrow(0.2,0.6,0.215,-0.215, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.2,0.85, 'PRE', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, 'ON', ha='center', transform=ax.transAxes )
elif what=='decoderscheme crossblock aa+ai': # 7
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
c1,c2 = ['dodgerblue','navy']
ax.arrow(0.2,0.6,0,-0.18, head_width=0.02, ec=c1, fc=c1, lw=lw, length_includes_head=True, transform=ax.transAxes, zorder=0 )
ax.arrow(0.2,0.6,0.215,-0.215, head_width=0.02, ec=c2, fc=c2, lw=lw, length_includes_head=True, transform=ax.transAxes, zorder=0 )
ax.text(0.2,0.85, 'attend ', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, ' ignore', ha='center', transform=ax.transAxes )
cc = 'slategrey' # comparator color
ax.plot([0.2,0.2],[0.19,0.15],color=cc,lw=lw,transform=ax.transAxes)
ax.add_patch(patches.Arc( (0.3,0.15),0.2,0.2,0,180,270, color=cc, lw=lw, transform=ax.transAxes))
ax.arrow(0.3,0.05,0.14,0, head_width=0.02, ec=cc, fc=cc, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.5,0.19,0,-0.08, head_width=0.02, ec=cc, fc=cc, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.5,0.05,'-',color=cc, fontsize='x-large', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
ax.add_patch(plt.Circle((0.5,0.05),0.04, ec=cc, fc=trp, lw=int(lw/2), transform=ax.transAxes))
elif what=='decoderscheme withinblock aa+ii': # 8
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
c1,c2 = ['dodgerblue','navy']
ax.arrow(0.2,0.6,0,-0.18, head_width=0.02, ec=c1, fc=c1, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.5,0.6,0,-0.18, head_width=0.02, ec=c2, fc=c2, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.2,0.85, 'attend ', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, ' ignore', ha='center', transform=ax.transAxes )
cc = 'slategrey' # comparator color
ax.plot([0.2,0.2],[0.19,0.15],color=cc,lw=lw,transform=ax.transAxes)
ax.add_patch(patches.Arc( (0.3,0.15),0.2,0.2,0,180,270, color=cc, lw=lw, transform=ax.transAxes))
ax.arrow(0.3,0.05,0.14,0, head_width=0.02, ec=cc, fc=cc, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.5,0.19,0,-0.08, head_width=0.02, ec=cc, fc=cc, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.5,0.05,'-',color=cc, fontsize='x-large', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
ax.add_patch(plt.Circle((0.5,0.05),0.04, ec=cc, fc=trp, lw=int(lw/2), transform=ax.transAxes))
elif what=='decoderscheme crossblock ii+ia': # 9
ax.add_patch(plt.Rectangle((0.1,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.2,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc=trp, lw=lw, transform=ax.transAxes))
c1,c2 = ['dodgerblue','navy']
ax.arrow(0.5,0.6,-0.215,-0.215, head_width=0.02, ec=c1, fc=c1, lw=lw, length_includes_head=True, transform=ax.transAxes, zorder=0 )
ax.arrow(0.5,0.6,0,-0.18, head_width=0.02, ec=c2, fc=c2, lw=lw, length_includes_head=True, transform=ax.transAxes, zorder=0 )
ax.text(0.2,0.85, 'attend ', ha='center', transform=ax.transAxes )
ax.text(0.5,0.85, ' ignore', ha='center', transform=ax.transAxes )
cc = 'slategrey' # comparator color
ax.plot([0.2,0.2],[0.19,0.15],color=cc,lw=lw,transform=ax.transAxes)
ax.add_patch(patches.Arc( (0.3,0.15),0.2,0.2,0,180,270, color=cc, lw=lw, transform=ax.transAxes))
ax.arrow(0.3,0.05,0.14,0, head_width=0.02, ec=cc, fc=cc, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.arrow(0.5,0.19,0,-0.08, head_width=0.02, ec=cc, fc=cc, lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.5,0.05,'-',color=cc, fontsize='x-large', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
ax.add_patch(plt.Circle((0.5,0.05),0.04, ec=cc, fc=trp, lw=int(lw/2), transform=ax.transAxes))
elif what=='decoderscheme PCA space': # 10 !!! (changed after crosscontext attends put in)
ax.add_patch(plt.Rectangle((0.4,0.6),0.2,0.2, ec='k', fc='lightgrey', lw=lw, transform=ax.transAxes))
ax.add_patch(plt.Circle((0.5,0.3),0.1, ec='k', fc='lightgrey', lw=lw, transform=ax.transAxes))
ax.arrow(0.5,0.6,0,-0.18, head_width=0.02, ec='k', fc='k', lw=lw, length_includes_head=True, transform=ax.transAxes )
ax.text(0.5,0.85, 'ON', ha='center', transform=ax.transAxes )
def drawsubspaces(axs,wix=None,what=None):
# fig,axs = plt.subplots(1,1,figsize=(12,12))
whats = ['dbnv','2dsubspace','pcasubspace','pcafullcomparedbnv','2dsubspacechoice','nullspace']
if wix!=None:
what = whats[wix]
if what == 'dbnv':
axs.view_init(elev=25,azim=45)
cl = 2
lm = 1
axs.plot([0,cl],[0,0],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,cl],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,0],[0,cl],color='black',linewidth=3,alpha=0.9)
# rotate onto position in 3D
ax = -30 # -15
az = +40 # +15
M = nedi.rotationmatrix3d(ax,0,az)
# initialize plane object in 2D
R = np.array([[-1,-1,1,1],[1,-1,-1,1],[0,0,0,0]])*1.3
R = M @ R
Rs = R
# draw object
r = [list(zip(R[0],R[1],R[2]))]
p = art3d.Poly3DCollection(r,alpha=0.3,edgecolor='teal',facecolor='teal')
axs.add_collection3d(p)
# points
N = 14
pd = 1
s = 0.1
R1 = np.array([np.random.randn(N)*s, np.random.randn(N)*s, np.random.randn(N)*s-pd])
R2 = np.array([np.random.randn(N)*s, np.random.randn(N)*s, np.random.randn(N)*s+pd])
# colors = ['mediumturquoise','darkcyan']
colors = ['dodgerblue','red']
for rx,Raux in enumerate([R1, R2]):
R = M @ Raux
axs.plot(R[0],R[1],R[2],'o',color=colors[rx],alpha=0.7)
axs.text(R[0].mean()-0.15,R[1].mean()+0.2,R[2].mean()+0.3-(1-rx)*0.7,'class %d'%(1-rx+1),(-1,1,0),color=colors[rx])
# arrow
# R = np.array([[0],[0],[0.7071]])
R = np.array([0,0,0.9])
R = M @ R
Ra = R
axs.quiver(0,0,0,R[0],R[1],R[2], color='teal', linewidth=4)
sp = 0.7
axs.plot([0, -R[0]], [0, -R[1]], [0, -R[2]],'--k',alpha=0.4,lw=1)
axs.plot([-R[0]*sp, -R[0]], [-R[1]*sp, -R[1]], [-R[2]*sp,-R[2]],'--',color='grey',lw=2)
# annotations
axs.text(2.2,0,-0.15,'neuron #1','x')
axs.text(0.04,1,-0.45,'neuron #2','y')
axs.text(0,0,1.2,'neuron #3','z')
axs.text2D(0.25,1,'activity\nspace',transform=axs.transAxes)
axs.text(Rs[0,2]+0.35,Rs[1,2]-0.3,Rs[2,2]+0.1,'decision\nboundary',Rs[:,1]-Rs[:,2],color='teal',verticalalignment='bottom')
axs.text(-0.1,0.1,0.1,'DV',Ra,color='teal')
axs.set_xlabel('x')
axs.set_ylabel('y')
axs.set_zlabel('z')
axs.set_xticks([])
axs.set_yticks([])
axs.set_zticks([])
axs.set_xlim(-lm,lm)
axs.set_ylim(-lm,lm)
axs.set_zlim(-lm,lm)
axs.axis('off')
elif what=='2dsubspace' or what=='2dsubspacechoice':
if what=='2dsubspace': cx_pool=[0,1]
elif what=='2dsubspacechoice': cx_pool=[2,1]
axs.view_init(elev=25,azim=45)
cl = 2
lm = 1
axs.plot([0,cl],[0,0],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,cl],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,0],[0,cl],color='black',linewidth=3,alpha=0.9)
colors = ['mediumvioletred','navy','darkorange']
taskaspects = ['context','visual','choice']
# rotate onto position in 3D
ax = +45
az = +105
M = nedi.rotationmatrix3d(ax,0,az)
for cx in [0,1]:
# arrows
ml = 1/0.7071
R = np.array([[0.7071*(cx)],[0.7071*(1-cx)+0.7071/5*(1-cx)],[0]])
L = np.array([[0.7071*(cx)],[0.7071*(1-cx)],[0]]) * ml
R = M @ R
L = M @ L
# axs.plot([0,L[0]],[0,L[1]],[0,L[2]],'--',color='darkgrey')
axs.quiver(0,0,0,R[0],R[1],R[2], color=colors[cx_pool[cx]], linewidth=4)
axs.text(0,0.3+0.1*(1-cx),-0.2+0.7*(1-cx),'%s DV'%taskaspects[cx_pool[cx]],R[:,0],color=colors[cx_pool[cx]])
# subspace plane
R = np.array([[-1,-1,1,1],[1,-1,-1,1],[0,0,0,0]])
R = M @ R
Rs = R
r = [list(zip(R[0],R[1],R[2]))]
p = art3d.Poly3DCollection(r,alpha=0.4,edgecolor='grey',facecolor='grey')
axs.add_collection3d(p)
axs.text2D(0.25,1,'activity\nspace',transform=axs.transAxes)
axs.text(Rs[0,1]+0.3,Rs[1,1],Rs[2,1]+0.1+0.2*(1-cx),'DVs\' subspace',Rs[:,0]-Rs[:,1],color='grey',verticalalignment='bottom')
l = 0.3
# axs.text((1-l)*Rs[0,2]+l*R[0,3],(1-l)*Rs[1,2]+l*R[1,3]+0.3,(1-l)*Rs[2,2]+l*R[2,3],\
# 'orthogonal\nbasis',Rs[:,2]-Rs[:,1],color='grey',verticalalignment='bottom')
axs.set_xlim(-lm,lm)
axs.set_ylim(-lm,lm)
axs.set_zlim(-lm,lm)
axs.axis('off')
elif what=='pcasubspaces':
axs.set_xlim(-lm,lm)
axs.set_ylim(-lm,lm)
axs.set_zlim(-lm,lm)
axs.axis('off')
elif what=='pcafullcomparedbnv':
axs.view_init(elev=25,azim=45)
cl = 2
lm = 1
axs.plot([0,cl],[0,0],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,cl],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,0],[0,cl],color='black',linewidth=3,alpha=0.9)
colors = ['mediumvioletred','navy']
color = colors[0]
taskaspects = ['context','visual']
# original decision boundary normal vector
# rotate onto position in 3D
ax = +45
az = +105
M = nedi.rotationmatrix3d(ax,0,az)
ml = 1/0.7071
R = np.array([[0],[0.7071],[0]])
L = R * ml
R = M @ R
Ra = R
L = M @ L
axs.plot([0,L[0]],[0,L[1]],[0,L[2]],'--',color='darkgrey') # show the full subspace spanned
axs.quiver(0,0,0,R[0],R[1],R[2], color=color, linewidth=4)
# define pca subspace
ax = +10
ay = +0
az = -20
M_p = nedi.rotationmatrix3d(ax,ay,az)
# get the plane
R = np.array([[-1,-1,1,1],[1,-1,-1,1],[0,0,0,0]])
R = M_p @ R
Rs = R
r = [list(zip(R[0],R[1],R[2]))]
p = art3d.Poly3DCollection(r,alpha=0.4,edgecolor='grey',facecolor='grey')
axs.add_collection3d(p)
# get the ellipse:
C = plt.Circle((0,0),0.7071).get_verts()
C = np.c_[C, np.zeros(len(C))]
C[:,1] = C[:,1]/2
C = C.T
R = M_p @ C
r = [list(zip(R[0],R[1],R[2]))]
p = art3d.Poly3DCollection(r,edgecolor='grey',facecolor=(0,0,0,0),linestyle='--')
axs.add_collection3d(p)
# get the PCA defined decision boundary normal vector
Rx = np.array([[-0.7071],[-0.1],[0]])
Rx = M_p @ Rx
R = Rx
axs.quiver(0,0,0,R[0],R[1],R[2], color=color, linewidth=1)
# get the x and y coordinate of the pca subspace
# we need to get the unit vectors in the columns of Rb
Rb = np.array([[1,0],[0,1],[0,0]])
Rb = M_p @ Rb
# get the shadow of the original dv to the pca subspace
# we need the
# Rp = np.dot(Rb.T,L)
# axs.plot([0,Rp[0]],[0,Rp[1]],[0,Rp[2]],'--',color=color)
axs.text2D(0.25,1,'activity\nspace',transform=axs.transAxes)
axs.text2D(0,0.58,'PCA$_{ON}$ subspace',transform=axs.transAxes,color='grey')
axs.text(Rs[0,3],Rs[1,3]+0.4,Rs[2,3],'pc #1',Rs[:,0]-Rs[:,3],color='grey',verticalalignment='bottom')
axs.text(Rs[0,3]+0.66,Rs[1,3]-0.2,Rs[2,3],'pc #2',Rs[:,2]-Rs[:,3],color='grey',verticalalignment='bottom')
dm = 1.25
axs.text(Ra[0,0]*dm+0.1,Ra[1,0]*dm-0.4,Ra[2,0]*dm,'%s DV\nin activity space'%taskaspects[0],Ra[:,0],color=color)
axs.text(Rx[0,0]*dm,Rx[1,0]*dm+0.1,Rx[2,0]*dm-0.1,'%s DV\nin PCA$_{ON}$ subspace'%taskaspects[0],Rx[:,0],color=color)
axs.set_xlim(-lm,lm)
axs.set_ylim(-lm,lm)
axs.set_zlim(-lm,lm)
axs.axis('off')
if what == 'nullspace':
axs.view_init(elev=25,azim=45)
cl = 2
lm = 1
axs.plot([0,cl],[0,0],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,cl],[0,0],color='black',linewidth=3,alpha=0.9)
axs.plot([0,0],[0,0],[0,cl],color='black',linewidth=3,alpha=0.9)
# rotate onto position in 3D
ax = -30 # -15
az = +40 # +15
M = nedi.rotationmatrix3d(ax,0,az)
# initialize plane object in 2D
R = np.array([[-1,-1,1,1],[1,-1,-1,1],[0,0,0,0]])*1.3
R = M @ R
Rs = R
# draw object
r = [list(zip(R[0],R[1],R[2]))]
p = art3d.Poly3DCollection(r,alpha=0.3,edgecolor='red',facecolor='red')
axs.add_collection3d(p)
# # points
# N = 14
# pd = 1
# s = 0.1
# R1 = np.array([np.random.randn(N)*s, np.random.randn(N)*s, np.random.randn(N)*s-pd])
# R2 = np.array([np.random.randn(N)*s, np.random.randn(N)*s, np.random.randn(N)*s+pd])
# # colors = ['mediumturquoise','darkcyan']
# colors = ['dodgerblue','red']
# for rx,Raux in enumerate([R1, R2]):
# R = M @ Raux
# axs.plot(R[0],R[1],R[2],'o',color=colors[rx],alpha=0.7)
# axs.text(R[0].mean()-0.15,R[1].mean()+0.2,R[2].mean()+0.3-(1-rx)*0.7,'class %d'%(1-rx+1),(-1,1,0),color=colors[rx])
# arrow
# R = np.array([[0],[0],[0.7071]])
R = np.array([0,0,0.9*1.618])
R = M @ R
Ra = R
axs.quiver(0,0,0,R[0],R[1],R[2], color='teal', linewidth=4)
sp = 0.7
axs.plot([0, -R[0]], [0, -R[1]], [0, -R[2]],'--k',alpha=0.4,lw=1)
axs.plot([-R[0]*sp, -R[0]], [-R[1]*sp, -R[1]], [-R[2]*sp,-R[2]],'--',color='grey',lw=2)
# annotations
axs.text(2.2,0,-0.15,'neuron #1','x')
axs.text(0.04,1,-0.45,'neuron #2','y')
axs.text(0,0,1.2,'neuron #3','z')
axs.text2D(0.25,1,'activity\nspace',transform=axs.transAxes)
axs.text(Rs[0,2]+0.35,Rs[1,2]-0.3,Rs[2,2]+0.1,'nullspace\nof DV',Rs[:,1]-Rs[:,2],color='red',verticalalignment='bottom')
axs.text(-0.1,0.1,0.1,'DV',Ra,color='teal')
axs.set_xlabel('x')
axs.set_ylabel('y')
axs.set_zlabel('z')
axs.set_xticks([])
axs.set_yticks([])
axs.set_zticks([])
axs.set_xlim(-lm,lm)
axs.set_ylim(-lm,lm)
axs.set_zlim(-lm,lm)
axs.axis('off')
return
def statshelper():
recalculate = 1 # calucate and save stats if 1, load if 0
skip = 20
# datanames = ['ME103','ME110','ME113','DT008','DT009','DT014','DT017','DT018','DT019','DT020','DT021','DT022','DT030','DT031','DT032','MT020_2'] # with ks2 spike sorting
datanames = ['ME110','ME113','DT009','DT014','DT017','DT021','DT022','MT020_2']
n_mice = len(datanames)
taskaspects = ['visual','audio','context','choice']
times = np.arange(601)[skip:-skip]
if recalculate:
# ( mice, taskaspects, trajectories, classes,{mean,s.e.m.} )
trajectory_matrix = np.zeros( (n_mice,4,len(times),2,3) )
# ( taskaspects, all_neurons, classes,{mean,s.e.m.} )
stats_matrix = np.zeros( (4,0,5) )
stats_matrix_celltypes = [ np.zeros( (4,0,5) ), np.zeros( (4,0,5) ) ]
# firing rate stats:
for n,dn in enumerate(datanames):
block = preprocess.loaddatamouse(dn,T,continuous_method=continuous_method,normalize=False) # use raw firing rates: normalzie=False
n_neuron = block.segments[0].analogsignals[0].shape[1]
blv,bla = preprocess.getorderattended(dn)
comparisongroups = [ \
[ [ [2,4],[45], [] ], [ [2,4],[135], [] ] ],\
[ [ [2,4], [],[5000] ], [ [2,4], [],[10000] ]],\
[ [ blv, [],[] ], [ bla, [], [] ] ],\
[ [] ] ]
local_stats = np.zeros((4,n_neuron,5)) # mean, variance, mean and var of trial-to-trial variance amongst neurons during stimulus
local_stats_celltypes = [ np.zeros((4,np.sum(0==block.annotations['celltypes']),5)),
np.zeros((4,np.sum(1==block.annotations['celltypes']),5)) ]
for cx,comparison in enumerate(taskaspects):
# collect neural responses
if not comparison=='choice': # visual, audio, context:
acrossresponses = preprocess.collect_stimulusspecificresponses(block,comparisongroups[cx])
else: # choice:
acrossresponses = preprocess.collect_stimulusspecificresponses_choice(block,dn)
# trajectory_matrix[n,cx,:,cidx,:,0] = np.array(acrossresponses[cidx])[:,:,:].mean(axis=0)
# trajectory_matrix[n,cx,:,cidx,:,1] = 2*np.array(acrossresponses[cidx])[:,:,:].std(axis=0)/\
# np.sqrt(len(acrossresponses[cidx]))
for cidx in range(2): # two classes
trajectory_matrix[n,cx,:,cidx,0] = np.array(acrossresponses[cidx])[:,skip:-skip,:].mean(axis=(0,2))
trajectory_matrix[n,cx,:,cidx,1] = 2*np.array(acrossresponses[cidx])[:,skip:-skip,:].var(axis=(0,2))
trajectory_matrix[n,cx,:,cidx,2] = 2*trajectory_matrix[n,cx,:,cidx,1]/\
np.sqrt(len(acrossresponses[cidx])*n_neuron)
local_stats[cx,:,0] = np.concatenate((np.array(acrossresponses[0])[:,skip:-skip,:],\
np.array(acrossresponses[1])[:,skip:-skip,:]),axis=0).mean(axis=(0,1))
local_stats[cx,:,1] = np.concatenate((np.array(acrossresponses[0])[:,skip:-skip,:],\
np.array(acrossresponses[1])[:,skip:-skip,:]),axis=0).var(axis=(0,1))
# mean firing rate of neurons, neural variance; average over time and trials; pres stim and during stim
local_stats[cx,:,2] = np.concatenate((np.array(acrossresponses[0])[:,:T['stimstart_idx'],:],\
np.array(acrossresponses[1])[:,:T['stimstart_idx'],:]),axis=(0)).mean(axis=(0,1))
local_stats[cx,:,3] = np.concatenate((np.array(acrossresponses[0])[:,T['stimstart_idx']:T['stimend_idx'],:],\
np.array(acrossresponses[1])[:,T['stimstart_idx']:T['stimend_idx'],:]),axis=(0)).mean(axis=(0,1))
# trial to trial variance of all neurons individually during stimulus:
local_stats[cx,:,4] = np.concatenate((np.array(acrossresponses[0])[:,T['stimstart_idx']:T['stimend_idx'],:],\
np.array(acrossresponses[1])[:,T['stimstart_idx']:T['stimend_idx'],:]),axis=0).mean(axis=1).var(axis=0)
for ct in [0,1]:
mask = ct==block.annotations['celltypes']
local_stats_celltypes[ct][cx,:,0] = np.concatenate((np.array(acrossresponses[0])[:,skip:-skip,mask],\
np.array(acrossresponses[1])[:,skip:-skip,mask]),axis=0).mean(axis=(0,1))
local_stats_celltypes[ct][cx,:,1] = np.concatenate((np.array(acrossresponses[0])[:,skip:-skip,mask],\
np.array(acrossresponses[1])[:,skip:-skip,mask]),axis=0).var(axis=(0,1))
# mean firing rate of neurons, neural variance; average over time and trials; pres stim and during stim
local_stats_celltypes[ct][cx,:,2] = np.concatenate((np.array(acrossresponses[0])[:,:T['stimstart_idx'],mask],\
np.array(acrossresponses[1])[:,:T['stimstart_idx'],mask]),axis=(0)).mean(axis=(0,1))
local_stats_celltypes[ct][cx,:,3] = np.concatenate((np.array(acrossresponses[0])[:,T['stimstart_idx']:T['stimend_idx'],mask],\
np.array(acrossresponses[1])[:,T['stimstart_idx']:T['stimend_idx'],mask]),axis=(0)).mean(axis=(0,1))
# trial to trial variance of all neurons individually during stimulus:
local_stats_celltypes[ct][cx,:,4] = np.concatenate((np.array(acrossresponses[0])[:,T['stimstart_idx']:T['stimend_idx'],mask],\
np.array(acrossresponses[1])[:,T['stimstart_idx']:T['stimend_idx'],mask]),axis=0).mean(axis=1).var(axis=0)
stats_matrix = np.concatenate( (stats_matrix, local_stats), axis=1)
for ct in [0,1]:
if local_stats_celltypes[ct].shape[1]>0:
stats_matrix_celltypes[ct] = np.concatenate( (stats_matrix_celltypes[ct], local_stats_celltypes[ct]), axis=1)
pickle.dump((trajectory_matrix,stats_matrix,stats_matrix_celltypes),open('../cache/phys/stats,trajectory_matrix-%s.pck'%(continuous_method),'wb'))
else:
trajectory_matrix,stats_matrix,stats_matrix_celltypes = pickle.load(open('../cache/phys/stats,trajectory_matrix-%s.pck'%(continuous_method),'rb'))
# STATS for publication:
cx = 0 # visual
n_all_neurons = stats_matrix.shape[1]
print('visual stim. mean firing rate from %4.2f +/- %4.2f to %4.2f +/- %4.2f and trial to trial variance on stimulus: %4.2f +/- %4.2f, n neurons %d'%(\
stats_matrix[cx,:,2].mean(), stats_matrix[cx,:,2].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[cx,:,3].mean(), stats_matrix[cx,:,3].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[cx,:,4].mean(),stats_matrix[cx,:,4].std()*1/np.sqrt(n_all_neurons),\
stats_matrix.shape[1]) )
for ct in [0,1]:
n_all_neurons_type = stats_matrix_celltypes[ct].shape[1]
print('visual stim. %s neurons, mean firing rate from %4.2f +/- %4.2f to %4.2f +/- %4.2f and trial to trial variance on stimulus: %4.2f +/- %4.2f, n neurons %d'%(\
['inhibitory','excitatory'][ct],
stats_matrix_celltypes[ct][cx,:,2].mean(), stats_matrix_celltypes[ct][cx,:,2].std()*1/np.sqrt(n_all_neurons_type),\
stats_matrix_celltypes[ct][cx,:,3].mean(), stats_matrix_celltypes[ct][cx,:,3].std()*1/np.sqrt(n_all_neurons_type),\
stats_matrix_celltypes[ct][cx,:,4].mean(),stats_matrix_celltypes[ct][cx,:,4].std()*1/np.sqrt(n_all_neurons_type),\
stats_matrix_celltypes[ct].shape[1]) )
mask = ((stats_matrix[cx,:,3]-stats_matrix[cx,:,2])>0) # choose cells that are with positive firing rate change
print('+ cells FR: visual stim. mean firing rate from %4.2f +/- %4.2f to %4.2f +/- %4.2f and trial to trial variance on stimulus: %4.2f +/- %4.2f, n neurons %d'%(\
stats_matrix[cx,mask,2].mean(), stats_matrix[cx,mask,2].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[cx,mask,3].mean(), stats_matrix[cx,mask,3].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[cx,mask,4].mean(),stats_matrix[cx,mask,4].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[:,mask,:].shape[1]) )
mask = np.logical_not(mask)
print('- cells FR: visual stim. mean firing rate from %4.2f +/- %4.2f to %4.2f +/- %4.2f and trial to trial variance on stimulus: %4.2f +/- %4.2f, n neurons %d'%(\
stats_matrix[cx,mask,2].mean(), stats_matrix[cx,mask,2].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[cx,mask,3].mean(), stats_matrix[cx,mask,3].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[cx,mask,4].mean(),stats_matrix[cx,mask,4].std()*1/np.sqrt(n_all_neurons),\
stats_matrix[:,mask,:].shape[1]) )
if 0: # display to check
fig, ax = plt.subplots(2,4,figsize=(4*6,2*6))
for cx,comparison in enumerate(taskaspects):
for cidx in range(2): # two classes
axs = ax[0,cx]
axs.plot(times,trajectory_matrix[4,cx,:,cidx,0].T)
axs.set_title(comparison)
if cx==0: axs.set_ylabel('mean'); axs.legend(['class 1','class2'])
axs = ax[1,cx]
axs.plot(times,trajectory_matrix[4,cx,:,cidx,1].T)
if cx==0: axs.set_ylabel('variance')
fig.suptitle('across neurons variance')
fig, ax = plt.subplots(3,4,figsize=(4*6,3*6))
for cx,comparison in enumerate(taskaspects):
axs = ax[0,cx]
# axs.bar(np.arange(stats_matrix.shape[1]),stats_matrix[cx,:,0])
axs.hist(stats_matrix[cx,:,0],bins=20)
axs.set_title(comparison)
axs.set_xlabel('mean')
axs = ax[1,cx]
# axs.bar(np.arange(stats_matrix.shape[1]),stats_matrix[cx,:,1])
axs.hist(stats_matrix[cx,:,1],bins=20)
axs.set_xlabel('variance')
axs = ax[2,cx]
axs.hist(stats_matrix[cx,:,0]/stats_matrix[cx,:,1],bins=20)
axs.set_xlabel('variance/mean')
fig.suptitle('across trial trajectory variance')
return
# FIGURES
def figure1():
# this will be only D-G holding the behavioural sessions
# datanamesall = ['ME103', 'ME110','ME113','DT008','DT009','DT014','DT017','DT018','DT019','DT020','DT021','DT022','DT030','DT031','DT032','MT020_2']
# datanamestrainings = ['ME113','DT008','DT009','DT014','DT017','DT018','DT019','DT020','DT021','DT022','DT030','DT031','DT032']
datanamestrainings = ['ME110','ME113','DT009','DT014','DT017','DT021','DT022','MT020_2']
# skipdict = {'ME110':['a03'],'MT020_2':['va28','va29','va30','va31','va32','va33','va34','va35','va36','va37','va38']}
skipdict = {'ME110':['a03'],'MT020_2':['v01','v02','v03','v04']}
datanames = ['ME110','ME113','DT009','DT014','DT017','DT021','DT022','MT020_2']
dprimes_all = []
L_max_sessiontypes = [0,0,0,0,0]
for n,dn in enumerate(datanamestrainings):
print(pathdatamouse + 'trainingbehaviour/' + dn + '.mat')
# hf = h5py.File(pathdatamouse + 'trainingbehaviour/' + dn + '_hdf5.mat','r') # we'have resaved in matlab for hdf5 format -v7.3
# data = hf['BehavStruct'] # data contains all the sessions, visual, audio, then mixed combined...; if h5py loading: use ...'][0,0] at the end
data = sp.io.loadmat(pathdatamouse + 'trainingbehaviour/' + dn + '.mat')['BehavStruct'] # this method preservs the order unfortunately unlike hdf5
# print(data.size)
# print(data.shape)
# print(data.dtype.names)
sessionids = np.array(data.dtype.names)
# collect session index list
vidx = [ s for sx,s in enumerate(sessionids) if s[0]=='v' and s[:2]!='va']
aidx = [ s for sx,s in enumerate(sessionids) if s[0]=='a' and s[:2]!='av']
vaidx = [ s for sx,s in enumerate(sessionids) if s[:2]=='va' ]
avidx = [ s for sx,s in enumerate(sessionids) if s[:2]=='av' ]
# collect recording session behaviour
fullpath = pathdatamouse+trialsfolder+'trials-start-good-C'+dn+'data.csv'
finalsession = pd.read_csv(fullpath,sep=',', usecols=['block','degree','freq','water','action','punish'])
# finalsession = finalsession.loc[finalsession['block']%2==1] # multimodal only
# finalsession.reset_index(inplace=True)
sessiontypelabellist = [vidx,aidx,vaidx,avidx]
dprime_sessiontypes = []
for sllx,sll in enumerate(sessiontypelabellist): # go through each session type (2 single and 2 multimodal)
dprime_sessions = []
L_max_sessiontypes[sllx] = np.max((L_max_sessiontypes[sllx],len(sll)+1)) # plus one for recording session
for sx,sl in enumerate(sll):
if (dn in skipdict.keys()) and (sl in skipdict[dn]): print('skipping',dn,sl); continue
# exclude all "NaN" trials (use valididx)
if sl[0]=='v':
valididx = np.logical_not( np.isnan(data[sl][0][0].squeeze()[0][:,0]) )
go = (data[sl][0][0].squeeze()[0][valididx,0] == 45).astype('int')
elif sl[0]=='a':
valididx = np.logical_not( np.isnan(data[sl][0][0].squeeze()[1][:,0]) )
go = (data[sl][0][0].squeeze()[1][valididx,0] == 5).astype('int')
else:
print('error',sll)
L = go.shape[0]
# print('this is go: ', go)
lick = np.zeros( L, dtype='int16' ) # lick data contains each trial empty array or an array with lick timings; "0" is no lick
aux = data[sl][0][0].squeeze()[2][valididx]
for l in range(L):
# print(aux)
# print(aux.shape)
# print(type(aux[l]), aux[l])
# if np.isnan(aux[l]): print(l, np.nan)
# print(l, aux[l][0])
# aux = sessiongroups[sx][2][0][l][0].ravel()
if len(aux[l][0])>0:
# print(l, aux[l][0][0,:])
if len(aux[l][0][0,:])>0:
lick[l] = aux[l][0][0,-1]>=2. # if the animals licks at least once after 2 seconds, it is considered a licked trial, and recorded as "1"
# else: print(l,' no lick')
# else: print(l,' NaN')
if len(lick)!=L: print('missing data'); continue # if there are some issues with the data, then skip
# d′ = Z(hit rate) − Z(false alarm rate),
# where function Z(p), p ∈ [0,1], is the inverse of the cumulative distribution function of the Gaussian distribution.
n_go = np.sum(go)
n_nogo = np.sum(1-go)
hit,miss,corrrej,fal = np.array([ np.sum(go & lick) / n_go, np.sum( go & (1-lick) ) / n_go,\
np.sum( (1-go) & (1-lick) ) / n_nogo, np.sum( (1-go) & lick ) / n_nogo ])
# also one needs to be careful, because if rate is exactly 1 or 0, the cdf is infinite
h = sp.stats.norm.ppf( hit )
if hit==1: h = sp.stats.norm.ppf( 0.99 )
elif hit==0: h = sp.stats.norm.ppf( 0.01 )
f = sp.stats.norm.ppf( fal )
if fal==0: f = sp.stats.norm.ppf( 0.01 )
elif fal==1: f = sp.stats.norm.ppf( 0.99 )
dprime = h - f
# if dprime==-np.inf or dprime==np.inf:
# print(dn,sl,h,f,' <> ',hit,fal,dprime)
dprime_sessions.append(dprime)
# print(hit,miss,corrrej,fal,' <> ', h,f,' <> ', dprime)
# print(np.sum(go),np.sum(np.isnan(go)),np.sum(lick),np.sum(np.isnan(go)))
# return
# add the recording session as last dprime
if sllx>1:
sessiontypemask = (finalsession['block']==sllx) & finalsession['action'] # go within blocks
n_gotrialsinblock = np.sum(sessiontypemask)
hit = np.sum(1-finalsession.loc[sessiontypemask,'punish'])/n_gotrialsinblock
fal = np.sum(finalsession.loc[sessiontypemask,'punish'])/n_gotrialsinblock
h = sp.stats.norm.ppf( hit )
if hit==1: h = sp.stats.norm.ppf( 0.99 )
elif hit==0: h = sp.stats.norm.ppf( 0.01 )
f = sp.stats.norm.ppf( fal )
if fal==0: f = sp.stats.norm.ppf( 0.01 )
elif fal==1: f = sp.stats.norm.ppf( 0.99 )
dprime = h - f
dprime_sessions.append(dprime)
# print(len(dprime_sessions))
dprime_sessiontypes.append(dprime_sessions)
# print(len(dprime_sessiontypes))
dprimes_all.append(dprime_sessiontypes)
# plot the figures
fig,ax = plt.subplots(2,2,figsize=(2*1.4*8,2*8))
# constrained_layout=False,
# training history dprimes
panel = 'd'
colors = ['dodgerblue','olivedrab','navy','darkgreen']
taskcontextlabels = ['visual only','audio only','visual context','audio context']
mincomplex = [9,1,0,0] #[9,1,12+11,12]
xc = 0
xt = []
xl = []
# create a pandas dataframe with columns: type, session number, each string in datanamestrainings
colnames = ['sessiontype','sessionnumber']
colnames.extend(datanamestrainings)
sourcedata = pd.DataFrame(columns=colnames)
for stx in [0,1,2,3]: # 5th column is for the combined d-prime of va and av
print(taskcontextlabels[stx], stx)
lm = L_max_sessiontypes[stx]
container = np.nan*np.ones((lm,len(datanamestrainings)))
# axs = ax[min(stx,2)]
axs = ax[0,0]
for n,dn in enumerate(datanamestrainings):
ls = len(dprimes_all[n][stx]) # +1 for recording session
container[-ls:,n] = dprimes_all[n][stx]
if stx==2: print(dn, 'container', container[-ls:,n])
print('container shape', container.shape, 'mincomplex', mincomplex[stx])
container = container[mincomplex[stx]:,:]
print('container mincomplex shape', container.shape)
# means = means[mincomplex[stx]:]
means = np.nanmean(container,axis=1)
if stx==2: containercombined = container/2
if stx==3: containercombined += container/2
if stx==2: ltotal = len(means)
x = xc + np.arange(len(means)) + 1
xt.append(x)
if stx<2: xc = x[-1]
if stx<3: xl.extend( np.arange(len(means)) + 1 )
print('means:',means)
if stx<2:
axs.plot( x, container,'-o', lw=0.3,color=colors[stx], alpha=0.6,markersize=5)
axs.plot( x, means, lw=4, color=colors[stx],label=taskcontextlabels[stx],markersize=5)
axs.text(x[0]+(stx>=2)*1,4.4+(stx==2)/4,taskcontextlabels[stx],color=colors[stx],fontsize='x-small')
if stx==2: axs.text(x[0]+1,4.4+1/2,'multimodal',color='black',fontsize='x-small')
contdf = pd.DataFrame(np.c_[np.tile(taskcontextlabels[stx],len(x)),x,container], columns=colnames)
sourcedata = pd.concat([sourcedata,contdf], ignore_index=True, sort=False)
sourcedata.to_csv(resultpath+'sourcedata/'+'sourcedata_Fig_1'+panel+'.csv',index=False)
# this is the average of av and va
axs.plot( x, containercombined,'-o', lw=0.3,color='black', alpha=0.6, markersize=5)
axs.plot( x[-1], containercombined[-1,:][np.newaxis,:],'o', lw=0.3,color='white', alpha=1, markersize=4)
xl.extend( [1] )