-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvr_grid_population_level_plots.py
1894 lines (1647 loc) · 109 KB
/
vr_grid_population_level_plots.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
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from eLife_Grid_anchoring_2024.vr_grid_cells import *
from eLife_Grid_anchoring_2024.Helpers.array_manipulations import *
import eLife_Grid_anchoring_2024.Helpers.plot_utility as plot_utility
warnings.filterwarnings('ignore')
def get_hmt_color(hmt):
if hmt == "hit":
return "green"
elif hmt == "miss":
return "red"
elif hmt == "try":
return "orange"
else:
return "black"
def plot_lomb_classifiers_vs_shuffle(concantenated_dataframe, suffix="", save_path=""):
print('plotting lomb classifiers...')
distance_cells = concantenated_dataframe[concantenated_dataframe["Lomb_classifier_"+suffix] == "Distance"]
position_cells = concantenated_dataframe[concantenated_dataframe["Lomb_classifier_"+suffix] == "Position"]
null_cells = concantenated_dataframe[concantenated_dataframe["Lomb_classifier_"+suffix] == "Null"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(7,4), gridspec_kw={'width_ratios': [1, 0.3]})
ax1.set_ylabel("Peak power vs \n false alarm rate",color="black",fontsize=25, labelpad=10)
ax1.set_xlabel("Track frequency", color="black", fontsize=25, labelpad=10)
ax1.set_xticks(np.arange(0, 11, 1.0))
ax1.set_yticks([-0.1, 0, 0.1, 0.2, 0.3, 0.4])
ax2.set_xticks([0, 0.5])
ax2.set_xticklabels(["0", "0.5"])
ax2.set_yticks([])
plt.setp(ax1.get_xticklabels(), fontsize=20)
plt.setp(ax2.get_xticklabels(), fontsize=20)
plt.setp(ax1.get_yticklabels(), fontsize=20)
ax1.yaxis.set_ticks_position('left')
ax1.xaxis.set_ticks_position('bottom')
for f in range(1,6):
ax1.axvline(x=f, color="gray", linewidth=2,linestyle="solid", alpha=0.5)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
ax1.scatter(x=null_cells["ML_Freqs"+suffix], y=null_cells["ML_SNRs"+suffix]-null_cells["power_threshold"], color=Settings.null_color, marker="o", alpha=0.3)
ax1.scatter(x=distance_cells["ML_Freqs"+suffix], y=distance_cells["ML_SNRs"+suffix]-distance_cells["power_threshold"], color=Settings.egocentric_color, marker="o", alpha=0.3)
ax1.scatter(x=position_cells["ML_Freqs"+suffix], y=position_cells["ML_SNRs"+suffix]-position_cells["power_threshold"], color=Settings.allocentric_color, marker="o", alpha=0.3)
ax1.axhline(y=0, color="red", linewidth=3,linestyle="dashed")
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax1.set_xlim([0,5.02])
ax1.set_ylim([-0.1,0.4])
ax2.set_xlim([-0.05,0.55])
ax2.set_ylim([-0.1,0.4])
ax2.set_xlabel(r'$\Delta$ from Int', color="black", fontsize=25, labelpad=10)
ax2.scatter(x=distance_from_integer(null_cells["ML_Freqs"+suffix]), y=null_cells["ML_SNRs"+suffix]-null_cells["power_threshold"], color=Settings.null_color, marker="o", alpha=0.3)
ax2.scatter(x=distance_from_integer(distance_cells["ML_Freqs"+suffix]), y=distance_cells["ML_SNRs"+suffix]-distance_cells["power_threshold"], color=Settings.egocentric_color, marker="o", alpha=0.3)
ax2.scatter(x=distance_from_integer(position_cells["ML_Freqs"+suffix]), y=position_cells["ML_SNRs"+suffix]-position_cells["power_threshold"], color=Settings.allocentric_color, marker="o", alpha=0.3)
ax2.axhline(y=0, color="red", linewidth=3,linestyle="dashed")
plt.tight_layout()
plt.savefig(save_path + '/lomb_classifiers_vs_shuffle_PDN_'+suffix+'.png', dpi=200)
plt.close()
return
def plot_lomb_classifier_powers_vs_groups(concantenated_dataframe, suffix="", save_path="", fig_size=(6,6)):
grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] == "G"]
non_grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] != "G"]
g_distance_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Distance"]["ML_SNRs"])
g_position_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Position"]["ML_SNRs"])
g_null_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Null"]["ML_SNRs"])
ng_distance_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Distance"]["ML_SNRs"])
ng_position_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Position"]["ML_SNRs"])
ng_null_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Null"]["ML_SNRs"])
fig, ax = plt.subplots(figsize=fig_size)
data = [g_position_cells[~np.isnan(g_position_cells)],
g_distance_cells[~np.isnan(g_distance_cells)],
g_null_cells[~np.isnan(g_null_cells)],
ng_position_cells[~np.isnan(ng_position_cells)],
ng_distance_cells[~np.isnan(ng_distance_cells)],
ng_null_cells[~np.isnan(ng_null_cells)]]
data = add_zero_to_data_if_empty(data)
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.null_color, Settings.allocentric_color, Settings.egocentric_color, Settings.null_color]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2,3,5,6,7], boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
ax.tick_params(axis='both', which='major', labelsize=25)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.set_ylim(bottom=0, top=0.3)
ax.set_xlim(left=0.5, right=3.5)
ax.set_yticks([0, 0.1, 0.2, 0.3])
fig.tight_layout()
plt.subplots_adjust(left=0.25, bottom=0.2)
ax.set_xlabel("", fontsize=20)
ax.set_ylabel("Peak power", fontsize=20)
plt.savefig(save_path + '/lomb_classifier_powers_vs_groups'+suffix+'.png', dpi=300)
plt.close()
return
def plot_lomb_classifier_spatinfo_vs_groups(concantenated_dataframe, suffix="", save_path="", fig_size=(6,6), score="spatial_information_score_Ispike_vr"):
grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] == "G"]
non_grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] != "G"]
g_distance_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Distance"][score])
g_position_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Position"][score])
g_null_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Null"][score])
ng_distance_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Distance"][score])
ng_position_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Position"][score])
ng_null_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Null"][score])
fig, ax = plt.subplots(figsize=fig_size)
data = [g_position_cells[~np.isnan(g_position_cells)],
g_distance_cells[~np.isnan(g_distance_cells)],
g_null_cells[~np.isnan(g_null_cells)],
ng_position_cells[~np.isnan(ng_position_cells)],
ng_distance_cells[~np.isnan(ng_distance_cells)],
ng_null_cells[~np.isnan(ng_null_cells)]]
data = add_zero_to_data_if_empty(data)
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.null_color, Settings.allocentric_color, Settings.egocentric_color, Settings.null_color]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2,3,5,6,7], boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
ax.tick_params(axis='both', which='major', labelsize=25)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.set_xlim(left=0.5, right=3.5)
fig.tight_layout()
plt.subplots_adjust(left=0.25, bottom=0.2)
ax.set_xlabel("", fontsize=20)
ax.set_ylabel("Spatial info", fontsize=20)
plt.savefig(save_path + '/lomb_classifier_spatinfo_vs_groups_'+score+''+suffix+'.png', dpi=300)
plt.close()
return
def plot_lomb_classifier_mfr_vs_groups(concantenated_dataframe, suffix="", save_path="", fig_size=(6,6)):
grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] == "G"]
non_grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] != "G"]
g_distance_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Distance"]['mean_firing_rate_vr'])
g_position_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Position"]['mean_firing_rate_vr'])
g_null_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Null"]['mean_firing_rate_vr'])
ng_distance_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Distance"]['mean_firing_rate_vr'])
ng_position_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Position"]['mean_firing_rate_vr'])
ng_null_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Null"]['mean_firing_rate_vr'])
fig, ax = plt.subplots(figsize=fig_size)
data = [g_position_cells[~np.isnan(g_position_cells)],
g_distance_cells[~np.isnan(g_distance_cells)],
g_null_cells[~np.isnan(g_null_cells)],
ng_position_cells[~np.isnan(ng_position_cells)],
ng_distance_cells[~np.isnan(ng_distance_cells)],
ng_null_cells[~np.isnan(ng_null_cells)]]
data = add_zero_to_data_if_empty(data)
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.null_color, Settings.allocentric_color, Settings.egocentric_color, Settings.null_color]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2,3,5,6,7], boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
ax.tick_params(axis='both', which='major', labelsize=25)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.set_ylim(bottom=0, top=15)
ax.set_xlim(left=0.5, right=3.5)
ax.set_yticks([0, 5, 10, 15])
fig.tight_layout()
plt.subplots_adjust(left=0.25, bottom=0.2)
ax.set_xlabel("", fontsize=20)
ax.set_ylabel("Mean firing rate", fontsize=20)
plt.savefig(save_path + '/lomb_classifier_mfr_vs_groups'+suffix+'.png', dpi=300)
plt.close()
return
def plot_lomb_classifier_peak_width_vs_groups(concantenated_dataframe, suffix="", save_path="", fig_size=(6,6)):
grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] == "G"]
non_grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] != "G"]
g_distance_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Distance"]['ML_peak_width'])
g_position_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Position"]['ML_peak_width'])
g_null_cells = np.asarray(grid_cells[grid_cells["Lomb_classifier_"] == "Null"]['ML_peak_width'])
ng_distance_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Distance"]['ML_peak_width'])
ng_position_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Position"]['ML_peak_width'])
ng_null_cells = np.asarray(non_grid_cells[non_grid_cells["Lomb_classifier_"] == "Null"]['ML_peak_width'])
fig, ax = plt.subplots(figsize=fig_size)
data = [g_position_cells[~np.isnan(g_position_cells)],
g_distance_cells[~np.isnan(g_distance_cells)],
g_null_cells[~np.isnan(g_null_cells)],
ng_position_cells[~np.isnan(ng_position_cells)],
ng_distance_cells[~np.isnan(ng_distance_cells)],
ng_null_cells[~np.isnan(ng_null_cells)]]
data = add_zero_to_data_if_empty(data)
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.null_color, Settings.allocentric_color, Settings.egocentric_color, Settings.null_color]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2,3,5,6,7], boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
ax.tick_params(axis='both', which='major', labelsize=25)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.set_ylim(bottom=0, top=3)
ax.set_xlim(left=0.5, right=3.5)
ax.set_yticks([0, 0.5, 1, 1.5])
ax.set_yticks([0, 1, 2, 3])
fig.tight_layout()
plt.subplots_adjust(left=0.25, bottom=0.2)
ax.set_xlabel("", fontsize=20)
ax.set_ylabel("Peak width", fontsize=20)
plt.savefig(save_path + '/lomb_classifier_peak_width_vs_groups'+suffix+'.png', dpi=300)
plt.close()
return
def plot_percentage_encoding_by_trial_category_each_mouse_weighted(combined_df, save_path="", trial_classification_column_name="", suffix=""):
for tt in [0, 1, 2]:
fig, ax = plt.subplots(figsize=(6, 4))
for code, code_color, code_z_order in zip(["P", "D"], [Settings.allocentric_color, get_mode_color_from_classification_column_name(trial_classification_column_name, "D")], [1,2]):
for i, mouse_id in enumerate(np.unique(combined_df["mouse"])):
mouse_cells = combined_df[combined_df["mouse"] == mouse_id]
mouse_hit, hit_weights = get_percentage_from_rolling_classifier_column(mouse_cells, code=code, tt=tt, hmt="hit", column_name=trial_classification_column_name)
mouse_try, try_weights = get_percentage_from_rolling_classifier_column(mouse_cells, code=code, tt=tt, hmt="try", column_name=trial_classification_column_name)
mouse_miss, miss_weights = get_percentage_from_rolling_classifier_column(mouse_cells, code=code, tt=tt, hmt="miss", column_name=trial_classification_column_name)
mask = ~np.isnan(mouse_hit) & ~np.isnan(mouse_try) & ~np.isnan(mouse_miss)
if len(mouse_hit[mask])>0:
ax.plot([2, 6, 10], [np.average(mouse_hit[mask], weights=hit_weights[mask]),
np.average(mouse_try[mask], weights=try_weights[mask]),
np.average(mouse_miss[mask], weights=miss_weights[mask])], clip_on=False, color=code_color, linewidth=1.5, alpha=0.3, zorder=-1)
All_hit, hit_weights = get_percentage_from_rolling_classifier_column(combined_df, code=code, tt=tt, hmt="hit", column_name=trial_classification_column_name)
All_try, try_weights = get_percentage_from_rolling_classifier_column(combined_df, code=code, tt=tt, hmt="try", column_name=trial_classification_column_name)
All_miss, miss_weights = get_percentage_from_rolling_classifier_column(combined_df, code=code, tt=tt, hmt="miss", column_name=trial_classification_column_name)
mask = ~np.isnan(All_hit) & ~np.isnan(All_try) & ~np.isnan(All_miss)
ax.errorbar(x=[2, 6, 10], y=[np.average(All_hit[mask], weights=hit_weights[mask]),
np.average(All_try[mask], weights=try_weights[mask]),
np.average(All_miss[mask], weights=miss_weights[mask])],
yerr=[stats.sem(All_hit[mask], axis=0, nan_policy="omit"),
stats.sem(All_try[mask], axis=0, nan_policy="omit"),
stats.sem(All_miss[mask], axis=0, nan_policy="omit")], capsize=25, linewidth=3, color=code_color, zorder=code_z_order)
ax.tick_params(axis='both', which='major', labelsize=20)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.xticks(fontsize=25)
plt.yticks(fontsize=25)
ax.set_xticks([2,6,10])
ax.set_yticks([0,25,50,75,100])
ax.xaxis.set_tick_params(labelbottom=False)
#ax.set_xticks([2,6,10])
#ax.set_xticklabels(["Hit", "Try", "Run"])
ax.set_xlim(left=0, right=12)
ax.set_ylim(bottom=0, top=100)
plt.savefig(save_path + '/rolling_percent_encooding_for_'+str(tt)+'_for_each_mouse_'+suffix+'_weigthed.png', dpi=300)
plt.close()
return
def get_percentage_from_rolling_classifier_column(df, code, tt, hmt, column_name):
percentages = []
weights = []
for index, cell in df.iterrows():
cell = cell.to_frame().T.reset_index(drop=True)
session_id = cell["session_id_vr"].iloc[0]
behaviours = np.array(cell["behaviour_hit_try_miss"].iloc[0])
trial_types = np.array(cell["behaviour_trial_types"].iloc[0])
rolling_classifiers = np.array(cell[column_name].iloc[0])
# mask by trial type
tt_mask = trial_types == tt
trial_types = trial_types[tt_mask]
behaviours = behaviours[tt_mask]
rolling_classifiers = rolling_classifiers[tt_mask]
# mask by behaviour
beh_mask = behaviours == hmt
trial_types = trial_types[beh_mask]
hmt_behaviours = behaviours[beh_mask]
rolling_classifiers = rolling_classifiers[beh_mask]
# mask by code
code_mask = (rolling_classifiers != "") &\
(rolling_classifiers != "nan") &\
(rolling_classifiers != "N")
rolling_classifiers = rolling_classifiers[code_mask]
code_mask = rolling_classifiers == code
rolling_classifiers_masked = rolling_classifiers[code_mask]
if len(rolling_classifiers) == 0:
percentages.append(np.nan)
weights.append(0)
else:
percentage_encoding = (len(rolling_classifiers_masked)/len(rolling_classifiers))*100
percentages.append(percentage_encoding)
hmt_weight = len(hmt_behaviours)/len(behaviours)
session_weight = 1/len(df[df["session_id_vr"]==session_id])
weights.append(hmt_weight*session_weight)
return np.array(percentages), np.array(weights)
def avg_over_cells_and_then_session(array, session_ids, mouse_ids, return_nans=True):
session_ids = np.asarray(session_ids)
mouse_ids = np.asarray(mouse_ids)
avg_values = []
for mouse in np.unique(mouse_ids):
session_avg_values = []
for session_id in np.unique(session_ids[mouse_ids == mouse]):
values_for_session = array[(mouse_ids == mouse) & (session_ids == session_id)]
session_avg_values.append(np.nanmean(values_for_session, axis=0))
session_avg_values = np.array(session_avg_values)
avg_values.append(np.nanmean(session_avg_values, axis=0))
avg_values = np.array(avg_values)
if return_nans:
return avg_values
else:
return avg_values[~np.isnan(avg_values)]
def plot_percentage_hits_for_remapped_encoding_cells_averaged_over_cells(cells, save_path="", trial_classification_column_name="", suffix=""):
mouse_colors = ['darkturquoise', 'salmon', u'#2ca02c', u'#d62728', u'#9467bd', u'#8c564b', u'#e377c2', u'#7f7f7f', u'#bcbd22', u'#17becf']
p_b_hit = get_percentage_from_rolling_classification(cells, code="P", tt=0, trial_classification_column_name=trial_classification_column_name)
d_b_hit = get_percentage_from_rolling_classification(cells, code="D", tt=0, trial_classification_column_name=trial_classification_column_name)
p_nb_hit = get_percentage_from_rolling_classification(cells, code="P", tt=1, trial_classification_column_name=trial_classification_column_name)
d_nb_hit = get_percentage_from_rolling_classification(cells, code="D", tt=1, trial_classification_column_name=trial_classification_column_name)
p_p_hit = get_percentage_from_rolling_classification(cells, code="P", tt=2, trial_classification_column_name=trial_classification_column_name)
d_p_hit = get_percentage_from_rolling_classification(cells, code="D", tt=2, trial_classification_column_name=trial_classification_column_name)
b_mask = ~np.isnan(p_b_hit) & ~np.isnan(d_b_hit)
nb_mask = ~np.isnan(p_nb_hit) & ~np.isnan(d_nb_hit)
p_mask = ~np.isnan(p_p_hit) & ~np.isnan(d_p_hit)
data = [p_b_hit[~np.isnan(p_b_hit)], d_b_hit[~np.isnan(d_b_hit)], p_nb_hit[~np.isnan(p_nb_hit)],
d_nb_hit[~np.isnan(d_nb_hit)], p_p_hit[~np.isnan(p_p_hit)], d_p_hit[~np.isnan(d_p_hit)]]
colors = [Settings.allocentric_color, get_mode_color_from_classification_column_name(trial_classification_column_name, "D"),
Settings.allocentric_color, get_mode_color_from_classification_column_name(trial_classification_column_name, "D"),
Settings.allocentric_color, get_mode_color_from_classification_column_name(trial_classification_column_name, "D")]
fig, ax = plt.subplots(figsize=(8, 6))
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2,4,5,7,8], widths=1, boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False, zorder=-1)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
p_b_hit = avg_over_cells_and_then_session(p_b_hit, cells["session_id"], cells["mouse"])
d_b_hit = avg_over_cells_and_then_session(d_b_hit, cells["session_id"], cells["mouse"])
p_nb_hit = avg_over_cells_and_then_session(p_nb_hit, cells["session_id"], cells["mouse"])
d_nb_hit = avg_over_cells_and_then_session(d_nb_hit, cells["session_id"], cells["mouse"])
p_p_hit = avg_over_cells_and_then_session(p_p_hit, cells["session_id"], cells["mouse"])
d_p_hit = avg_over_cells_and_then_session(d_p_hit, cells["session_id"], cells["mouse"])
data = [p_b_hit, d_b_hit, p_nb_hit, d_nb_hit, p_p_hit, d_p_hit]
r_i = np.array([0,0])
for i in range(len(data[0])):
ax.plot([1 + r_i[0],2 + r_i[1]], [data[0][i], data[1][i]], color=mouse_colors[i], alpha=1, linewidth=2)
for i in range(len(data[2])):
ax.plot([4 + r_i[0], 5 + r_i[1]], [data[2][i], data[3][i]], color=mouse_colors[i], alpha=1, linewidth=2)
for i in range(len(data[4])):
ax.plot([7 + r_i[0], 8 + r_i[1]], [data[4][i], data[5][i]], color=mouse_colors[i], alpha=1, linewidth=2)
ax.tick_params(axis='both', which='major', labelsize=20)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='both', which='both', labelsize=25)
ax.set_yticks([0,25, 50, 75, 100])
ax.set_xticks([1,2,4,5,7,8])
ax.set_xticklabels(["B", "B", "NB", "NB", "P", "P"])
ax.set_xlim(left=0, right=9)
plt.subplots_adjust(bottom=0.2, left=0.2)
plt.savefig(save_path + '/percentage_hit_trials_in_coded_trials_' + suffix + '.png', dpi=300)
plt.close()
return
def plot_lomb_classifiers_proportions(concantenated_dataframe, suffix="", save_path=""):
print('plotting lomb classifers proportions...')
grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] == "G"]
non_grid_cells = concantenated_dataframe[concantenated_dataframe["classifier"] != "G"]
fig, ax = plt.subplots(figsize=(4,6))
groups = ["Position", "Distance", "Null"]
colors_lm = [Settings.allocentric_color, Settings.egocentric_color, Settings.null_color, "black"]
objects = ["G", "NG"]
x_pos = np.arange(len(objects))
for object, x in zip(objects, x_pos):
if object == "G":
df = grid_cells
elif object == "NG":
df = non_grid_cells
bottom=0
for color, group in zip(colors_lm, groups):
count = len(df[(df["Lomb_classifier_"+suffix] == group)])
percent = (count/len(df))*100
ax.bar(x, percent, bottom=bottom, color=color, edgecolor=color)
ax.text(x,bottom+0.5, str(count), color="k", fontsize=15, ha="center")
bottom = bottom+percent
plt.xticks(x_pos, objects, fontsize=15)
plt.ylabel("Percent of neurons", fontsize=25)
plt.xlim((-0.5, len(objects)-0.5))
plt.ylim((0,100))
ax.set_yticks([0,25,50,75,100])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.subplots_adjust(left=0.4)
ax.tick_params(axis='both', which='major', labelsize=30)
plt.savefig(save_path + '/lomb_classifiers_proportions_'+suffix+'.png', dpi=200)
plt.close()
return
def plot_regression(ax, x, y, c, y_text_pos, x_test_min=None, x_test_max=None):
# x and y are pandas collumn
try:
x = x.values
y = y.values
except Exception as ex:
print("")
x = x[~np.isnan(y)].reshape(-1, 1)
y = y[~np.isnan(y)].reshape(-1, 1)
pearson_r = stats.pearsonr(x.flatten(),y.flatten())
linear_regressor = LinearRegression() # create object for the class
linear_regressor.fit(x,y) # perform linear regression
if x_test_min is None:
x_test_min = min(x)
if x_test_max is None:
x_test_max = max(x)
x_test = np.linspace(x_test_min, x_test_max, 100)
Y_pred = linear_regressor.predict(x_test.reshape(-1, 1)) # make predictions
ax.text( # position text relative to Axes
0.05, y_text_pos, "R= "+str(np.round(pearson_r[0], decimals=2))+ ", p = "+str(np.round(pearson_r[1], decimals=4)),
ha='left', va='top', color=c,
transform=ax.transAxes, fontsize=10)
ax.plot(x_test, Y_pred, color=c)
def get_percentage_hit_column(df, tt, return_nans=False):
percentage_hits = []
for index, cluster_df in df.iterrows():
cluster_df = cluster_df.to_frame().T.reset_index(drop=True)
behaviours = np.array(cluster_df["behaviour_hit_try_miss"].iloc[0])
trial_types = np.array(cluster_df["behaviour_trial_types"].iloc[0])
valid_behaviours = behaviours[(trial_types == tt) & (behaviours != "rejected")]
if len(valid_behaviours)>0:
percentage = 100*(len(valid_behaviours[valid_behaviours == "hit"])/len(valid_behaviours))
else:
percentage = np.nan
percentage_hits.append(percentage)
percentage_hits = np.array(percentage_hits)
if return_nans:
return percentage_hits
else:
return percentage_hits[~np.isnan(percentage_hits)]
def get_percentage_from_rolling_classification(df, code, tt, trial_classification_column_name="", hmt=""):
percentages = []
for index, cluster_df in df.iterrows():
cluster_df = cluster_df.to_frame().T.reset_index(drop=True)
behaviours = np.array(cluster_df["behaviour_hit_try_miss"].iloc[0])
trial_types = np.array(cluster_df["behaviour_trial_types"].iloc[0])
rolling_classifiers = np.array(cluster_df[trial_classification_column_name].iloc[0])
valid_trials = behaviours[(rolling_classifiers == code) &
(trial_types == tt) &
(rolling_classifiers != "nan") &
(behaviours != "rejected")]
if len(valid_trials) == 0:
percentage = np.nan
else:
percentage = 100*(len(valid_trials[valid_trials==hmt])/len(valid_trials))
percentages.append(percentage)
return np.array(percentages)
def get_mode_color_from_classification_column_name(column_name, mode):
if mode == "P" and column_name == "alternative_classifications":
return Settings.allocentric_color
elif mode == "P" and column_name == "rolling:classifier_by_trial_number":
return Settings.allocentric_color
elif mode == "D" and column_name == "alternative_classifications":
return Settings.alt_egocentric_color
elif mode == "D" and column_name == "rolling:classifier_by_trial_number":
return Settings.egocentric_color
else:
print("There is an error extracting a color based on the classification column name")
def plot_stop_histogram_for_remapped_encoding_cells_averaged_over_cells(cells, save_path, suffix="", trial_classification_column_name="", lock_y_axis=True):
for tt in [0,1,2]:
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.axhline(y=0, linestyle="dashed", linewidth=2, color="black")
remapped_position_grid_cells_stop_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(cells, tt=tt, coding_scheme="P", shuffle=False, trial_classification_column_name=trial_classification_column_name)
remapped_distance_grid_cells_stop_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(cells, tt=tt, coding_scheme="D", shuffle=False, trial_classification_column_name=trial_classification_column_name)
remapped_position_grid_cells_shuffled_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(cells, tt=tt,coding_scheme="P",shuffle=True, trial_classification_column_name=trial_classification_column_name)
remapped_distance_grid_cells_shuffled_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(cells, tt=tt,coding_scheme="D",shuffle=True, trial_classification_column_name=trial_classification_column_name)
# get session weights
P_weigths = get_session_weights(cells, tt = tt, coding_scheme = "P")
D_weigths = get_session_weights(cells, tt = tt, coding_scheme = "D")
remapped_position_grid_cells_stop_histogram_tt = np.array(remapped_position_grid_cells_stop_histogram_tt)
remapped_distance_grid_cells_stop_histogram_tt = np.array(remapped_distance_grid_cells_stop_histogram_tt)
remapped_position_grid_cells_shuffled_histogram_tt = np.array(remapped_position_grid_cells_shuffled_histogram_tt)
remapped_distance_grid_cells_shuffled_histogram_tt = np.array(remapped_distance_grid_cells_shuffled_histogram_tt)
p_nan_mask = ~np.isnan(remapped_position_grid_cells_stop_histogram_tt)[:,0]
d_nan_mask = ~np.isnan(remapped_distance_grid_cells_stop_histogram_tt)[:,0]
# normalise to baseline
remapped_position_grid_cells_stop_histogram_tt = remapped_position_grid_cells_stop_histogram_tt-remapped_position_grid_cells_shuffled_histogram_tt
remapped_distance_grid_cells_stop_histogram_tt = remapped_distance_grid_cells_stop_histogram_tt-remapped_distance_grid_cells_shuffled_histogram_tt
# apply mask
remapped_position_grid_cells_stop_histogram_tt = remapped_position_grid_cells_stop_histogram_tt[p_nan_mask,:]
remapped_distance_grid_cells_stop_histogram_tt = remapped_distance_grid_cells_stop_histogram_tt[d_nan_mask,:]
P_weigths = P_weigths[p_nan_mask]
D_weigths = D_weigths[d_nan_mask]
# plot position grid cell session stop histogram
ax.plot(bin_centres, np.average(remapped_position_grid_cells_stop_histogram_tt, weights=P_weigths, axis=0), color= Settings.allocentric_color, linewidth=3)
ax.fill_between(bin_centres, np.average(remapped_position_grid_cells_stop_histogram_tt, weights=P_weigths, axis=0)-stats.sem(remapped_position_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"),
np.average(remapped_position_grid_cells_stop_histogram_tt, weights=P_weigths, axis=0)+stats.sem(remapped_position_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"), color=Settings.allocentric_color, alpha=0.3)
# plot distance grid cell session stop histogram
ax.plot(bin_centres, np.average(remapped_distance_grid_cells_stop_histogram_tt, weights=D_weigths, axis=0), color= get_mode_color_from_classification_column_name(trial_classification_column_name, "D"), linewidth=3)
ax.fill_between(bin_centres, np.average(remapped_distance_grid_cells_stop_histogram_tt, weights=D_weigths, axis=0)-stats.sem(remapped_distance_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"),
np.average(remapped_distance_grid_cells_stop_histogram_tt, weights=D_weigths, axis=0)+stats.sem(remapped_distance_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"), color=get_mode_color_from_classification_column_name(trial_classification_column_name, "D"), alpha=0.3)
if tt == 0:
style_track_plot(ax, 200)
else:
style_track_plot_no_RZ(ax, 200)
#plt.ylabel('Stops (/cm)', fontsize=20, labelpad = 20)
#plt.xlabel('Location (cm)', fontsize=20, labelpad = 20)
plt.xlim(0, 200)
tick_spacing = 100
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plot_utility.style_vr_plot(ax)
if lock_y_axis:
ax.set_ylim([-0.05,0.15])
ax.set_yticks([0, 0.1])
plt.locator_params(axis = 'y', nbins = 3)
plt.xticks(fontsize=25)
plt.yticks(fontsize=25)
plt.tight_layout()
plt.subplots_adjust(bottom = 0.2, left=0.2)
plt.savefig(save_path + '/stop_histogram_for_remapped_cells_encoding_position_and_distance_'+str(tt)+'_'+suffix+'.png', dpi=300)
plt.close()
return
def plot_stop_histogram_for_stable_cells_averaged_over_cells(cells, save_path, suffix=""):
position_cells = cells[cells["Lomb_classifier_"] == "Position"]
distance_cells = cells[cells["Lomb_classifier_"] == "Distance"]
stable_position_cells = position_cells[position_cells["rolling:proportion_encoding_position"] >= 0.85]
stable_distance_cells = distance_cells[distance_cells["rolling:proportion_encoding_distance"] >= 0.85]
stable_position_cells = drop_duplicate_sessions(stable_position_cells)
stable_distance_cells = drop_duplicate_sessions(stable_distance_cells)
for tt in [0,1,2]:
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.axhline(y=0, linestyle="dashed", linewidth=2, color="black")
stable_position_grid_cells_stop_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(stable_position_cells, tt=tt, coding_scheme=None, shuffle=False)
stable_distance_grid_cells_stop_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(stable_distance_cells, tt=tt, coding_scheme=None, shuffle=False)
stable_position_grid_cells_shuffled_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(stable_position_cells, tt=tt, coding_scheme=None, shuffle=True)
stable_distance_grid_cells_shuffled_histogram_tt, _, bin_centres, _, _, _ = get_stop_histogram(stable_distance_cells, tt=tt, coding_scheme=None, shuffle=True)
stable_position_grid_cells_stop_histogram_tt = np.array(stable_position_grid_cells_stop_histogram_tt)
stable_distance_grid_cells_stop_histogram_tt = np.array(stable_distance_grid_cells_stop_histogram_tt)
stable_position_grid_cells_shuffled_histogram_tt = np.array(stable_position_grid_cells_shuffled_histogram_tt)
stable_distance_grid_cells_shuffled_histogram_tt = np.array(stable_distance_grid_cells_shuffled_histogram_tt)
# apply normalisation with baseline
stable_position_grid_cells_stop_histogram_tt = stable_position_grid_cells_stop_histogram_tt-stable_position_grid_cells_shuffled_histogram_tt
stable_distance_grid_cells_stop_histogram_tt = stable_distance_grid_cells_stop_histogram_tt-stable_distance_grid_cells_shuffled_histogram_tt
# plot position grid cell session stop histogram
ax.plot(bin_centres, np.nanmean(stable_position_grid_cells_stop_histogram_tt, axis=0), color= Settings.allocentric_color,linewidth=3)
ax.fill_between(bin_centres, np.nanmean(stable_position_grid_cells_stop_histogram_tt, axis=0)-stats.sem(stable_position_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"),
np.nanmean(stable_position_grid_cells_stop_histogram_tt, axis=0)+stats.sem(stable_position_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"), color=Settings.allocentric_color, alpha=0.3)
# plot distance grid cell session stop histogram
ax.plot(bin_centres, np.nanmean(stable_distance_grid_cells_stop_histogram_tt, axis=0), color= Settings.egocentric_color,linewidth=3)
ax.fill_between(bin_centres, np.nanmean(stable_distance_grid_cells_stop_histogram_tt, axis=0)-stats.sem(stable_distance_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"),
np.nanmean(stable_distance_grid_cells_stop_histogram_tt, axis=0)+stats.sem(stable_distance_grid_cells_stop_histogram_tt, axis=0, nan_policy="omit"), color=Settings.egocentric_color, alpha=0.3)
if tt == 0:
style_track_plot(ax, 200)
else:
style_track_plot_no_RZ(ax, 200)
#plt.ylabel('Stops (/cm)', fontsize=20, labelpad = 20)
#plt.xlabel('Location (cm)', fontsize=20, labelpad = 20)
plt.xlim(0, 200)
tick_spacing = 100
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plot_utility.style_vr_plot(ax)
ax.set_ylim([-0.05,0.15])
ax.set_yticks([0, 0.1])
#ax.set_ylim([-0.05,0.05])
#ax.set_yticks([0, 0.05])
plt.locator_params(axis = 'y', nbins = 3)
plt.xticks(fontsize=25)
plt.yticks(fontsize=25)
plt.tight_layout()
plt.subplots_adjust(bottom = 0.2, left=0.2)
plt.savefig(save_path + '/stop_histogram_for_stable_cells_encoding_position_and_distance_'+str(tt)+'_'+suffix+'_averaged_over_cells.png', dpi=300)
plt.close()
return
def drop_duplicate_sessions(cells_df):
sessions = []
new_df = pd.DataFrame()
for index, cluster_df in cells_df.iterrows():
cluster_df = cluster_df.to_frame().T.reset_index(drop=True)
session_id = cluster_df["session_id"].iloc[0]
if session_id not in sessions:
new_df = pd.concat([new_df, cluster_df], ignore_index=True)
sessions.append(session_id)
return new_df
def get_mouse_colors(cells, mouse_colors, all_mouse_ids):
mouse_ids_from_data_frame = np.asarray(cells["mouse"])
mouse_colors_for_dataframe = []
for i in range(len(mouse_ids_from_data_frame)):
mouse_colors_for_dataframe.append(mouse_colors[np.argwhere(all_mouse_ids == mouse_ids_from_data_frame[i])[0][0]])
return np.array(mouse_colors_for_dataframe)
def plot_percentage_hits_for_stable_encoding_cells_averaged_over_cells(cells, save_path, suffix=""):
mouse_colors = ['darkturquoise', 'salmon', u'#2ca02c', u'#d62728', u'#9467bd', u'#8c564b', u'#e377c2', u'#7f7f7f',u'#bcbd22', u'#17becf']
mouse_ids = np.unique(cells["mouse"])[:len(mouse_colors)]
position_cells = cells[cells["Lomb_classifier_"] == "Position"]
distance_cells = cells[cells["Lomb_classifier_"] == "Distance"]
stable_position_cells = position_cells[position_cells["rolling:proportion_encoding_position"] >= 0.85]
stable_distance_cells = distance_cells[distance_cells["rolling:proportion_encoding_distance"] >= 0.85]
stable_position_cells = drop_duplicate_sessions(stable_position_cells)
stable_distance_cells = drop_duplicate_sessions(stable_distance_cells)
stable_position_colors = get_mouse_colors(stable_position_cells, mouse_colors, mouse_ids)
stable_distance_colors = get_mouse_colors(stable_distance_cells, mouse_colors, mouse_ids)
print("n session for stable position grid cells, n = ", str(len(stable_position_cells)))
print("n session for stable distance grid cells, n = ", str(len(stable_distance_cells)))
fig, ax = plt.subplots(1,1, figsize=(8,6))
beaconed_percentage_hits_stable_position_grid_cells = get_percentage_hit_column(stable_position_cells, tt=0, return_nans=True)
non_beaconed_percentage_hits_stable_position_grid_cells = get_percentage_hit_column(stable_position_cells, tt=1, return_nans=True)
beaconed_percentage_hits_stable_distance_grid_cells = get_percentage_hit_column(stable_distance_cells, tt=0, return_nans=True)
non_beaconed_percentage_hits_stable_distance_grid_cells = get_percentage_hit_column(stable_distance_cells, tt=1, return_nans=True)
probe_percentage_hits_stable_position_grid_cells = get_percentage_hit_column(stable_position_cells, tt=2, return_nans=True)
probe_percentage_hits_stable_distance_grid_cells = get_percentage_hit_column(stable_distance_cells, tt=2, return_nans=True)
beaconed_percentage_hits_stable_position_colors = stable_position_colors[~np.isnan(beaconed_percentage_hits_stable_position_grid_cells)]
non_beaconed_percentage_hits_stable_position_colors = stable_position_colors[~np.isnan(non_beaconed_percentage_hits_stable_position_grid_cells)]
beaconed_percentage_hits_stable_distance_colors = stable_distance_colors[~np.isnan(beaconed_percentage_hits_stable_distance_grid_cells)]
non_beaconed_percentage_hits_stable_distance_colors = stable_distance_colors[~np.isnan(non_beaconed_percentage_hits_stable_distance_grid_cells)]
probe_percentage_hits_stable_position_colors = stable_position_colors[~np.isnan(probe_percentage_hits_stable_position_grid_cells)]
probe_percentage_hits_stable_distance_colors = stable_distance_colors[~np.isnan(probe_percentage_hits_stable_distance_grid_cells)]
colors = [Settings.allocentric_color, Settings.egocentric_color, Settings.allocentric_color,
Settings.egocentric_color, Settings.allocentric_color, Settings.egocentric_color]
data = [beaconed_percentage_hits_stable_position_grid_cells[~np.isnan(beaconed_percentage_hits_stable_position_grid_cells)],
beaconed_percentage_hits_stable_distance_grid_cells[~np.isnan(beaconed_percentage_hits_stable_distance_grid_cells)],
non_beaconed_percentage_hits_stable_position_grid_cells[~np.isnan(non_beaconed_percentage_hits_stable_position_grid_cells)],
non_beaconed_percentage_hits_stable_distance_grid_cells[~np.isnan(non_beaconed_percentage_hits_stable_distance_grid_cells)],
probe_percentage_hits_stable_position_grid_cells[~np.isnan(probe_percentage_hits_stable_position_grid_cells)],
probe_percentage_hits_stable_distance_grid_cells[~np.isnan(probe_percentage_hits_stable_distance_grid_cells)]]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1, 2, 4, 5, 7, 8], widths=1, boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False, zorder=-1)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
data_colors = [beaconed_percentage_hits_stable_position_colors, beaconed_percentage_hits_stable_distance_colors,
non_beaconed_percentage_hits_stable_position_colors, non_beaconed_percentage_hits_stable_distance_colors,
probe_percentage_hits_stable_position_colors, probe_percentage_hits_stable_distance_colors]
for i, x in enumerate([1, 2, 4, 5, 7, 8]):
ax.scatter((np.ones(len(data[i])) * x) + np.random.uniform(low=-0.1, high=+0.1, size=len(data[i])), data[i],
color=data_colors[i], alpha=1, zorder=1)
ax.tick_params(axis='both', which='major', labelsize=20)
ax.set_xticks([1, 2, 4, 5, 7, 8])
ax.set_xticklabels(["B", "B", "NB", "NB", "P", "P"])
ax.set_yticks([0, 25, 50, 75, 100])
# ax.set_ylim([0, 100])
ax.set_xlim([0, 9])
# ax.set_xlabel("Encoding grid cells", fontsize=20)
# ax.set_ylabel("Percentage hits", fontsize=20, labelpad=10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_tick_params(length=0)
ax.tick_params(axis='both', which='both', labelsize=25)
# plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.3, right = 0.87, top = 0.92)
plt.subplots_adjust(bottom=0.2, left=0.2)
plt.savefig(save_path + '/percentage_hits_for_stable_cells_'+suffix+'.png', dpi=300)
plt.close()
return
def plot_rolling_lomb_block_sizes(combined_df, save_path, suffix=""):
grid_cells = combined_df[combined_df["classifier"] == "G"]
non_grid_cells = combined_df[combined_df["classifier"] != "G"]
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.set_xticks([0,1])
ax.set_ylim([0, 1])
ax.set_xlim([0, 1])
_, _, patches0 = ax.hist(pandas_collumn_to_numpy_array(grid_cells["rolling:proportion_encoding_position"]), density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color=(255 / 255, 127 / 255, 14 / 255),linewidth=2)
_, _, patches1 = ax.hist(pandas_collumn_to_numpy_array(non_grid_cells["rolling:proportion_encoding_position"]), density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color=(0 / 255, 154 / 255, 255 / 255),linewidth=2)
patches0[0].set_xy(patches0[0].get_xy()[:-1])
patches1[0].set_xy(patches1[0].get_xy()[:-1])
ks, p = stats.ks_2samp(pandas_collumn_to_numpy_array(grid_cells["rolling:proportion_encoding_position"]),
pandas_collumn_to_numpy_array(non_grid_cells["rolling:proportion_encoding_position"]))
print("position, ks=", str(ks), " , p=", str(p), " , Ng= ", str(len(grid_cells)), ", Nng= ", str(len(non_grid_cells)))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_tick_params(length=0)
ax.tick_params(axis='both', which='both', labelsize=30)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.2, right = 0.87, top = 0.92)
plt.savefig(save_path + '/block_length_encoding_position_cumsum'+suffix+'.png', dpi=300)
plt.close()
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.set_xticks([0,1])
ax.set_ylim([0, 1])
ax.set_xlim([0, 1])
_, _, patches0 = ax.hist(pandas_collumn_to_numpy_array(grid_cells["rolling:proportion_encoding_distance"]), density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color=(255 / 255, 127 / 255, 14 / 255),linewidth=2)
_, _, patches1 = ax.hist(pandas_collumn_to_numpy_array(non_grid_cells["rolling:proportion_encoding_distance"]), density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color=(0 / 255, 154 / 255, 255 / 255),linewidth=2)
patches0[0].set_xy(patches0[0].get_xy()[:-1])
patches1[0].set_xy(patches1[0].get_xy()[:-1])
ks, p = stats.ks_2samp(pandas_collumn_to_numpy_array(grid_cells["rolling:proportion_encoding_distance"]),
pandas_collumn_to_numpy_array(non_grid_cells["rolling:proportion_encoding_distance"]))
print("distance, ks=", str(ks), " , p=", str(p), " , Ng= ", str(len(grid_cells)), ", Nng= ", str(len(non_grid_cells)))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_tick_params(length=0)
ax.tick_params(axis='both', which='both', labelsize=30)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.2, right = 0.87, top = 0.92)
plt.savefig(save_path + '/block_length_encoding_distance_cumsum'+suffix+'.png', dpi=300)
plt.close()
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.set_xticks([0,1])
ax.set_ylim([0, 1])
ax.set_xlim([0, 1])
_, _, patches0 = ax.hist(pandas_collumn_to_numpy_array(grid_cells["rolling:proportion_encoding_null"]), density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color=(255 / 255, 127 / 255, 14 / 255),linewidth=2)
_, _, patches1 = ax.hist(pandas_collumn_to_numpy_array(non_grid_cells["rolling:proportion_encoding_null"]), density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color=(0 / 255, 154 / 255, 255 / 255),linewidth=2)
patches0[0].set_xy(patches0[0].get_xy()[:-1])
patches1[0].set_xy(patches1[0].get_xy()[:-1])
ks, p = stats.ks_2samp(pandas_collumn_to_numpy_array(grid_cells["rolling:proportion_encoding_null"]),
pandas_collumn_to_numpy_array(non_grid_cells["rolling:proportion_encoding_null"]))
print("null, ks=", str(ks), " , p=", str(p), " , Ng= ", str(len(grid_cells)), ", Nng= ", str(len(non_grid_cells)))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_tick_params(length=0)
ax.tick_params(axis='both', which='both', labelsize=30)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.2, right = 0.87, top = 0.92)
plt.savefig(save_path + '/block_length_encoding_null_cumsum'+suffix+'.png', dpi=300)
plt.close()
return
def plot_proportion_of_session_encoding_mode(combined_df, save_path, suffix=""):
Position_cells = combined_df[combined_df["Lomb_classifier_"] == "Position"]
Distance_cells = combined_df[combined_df["Lomb_classifier_"] == "Distance"]
Null_cells = combined_df[combined_df["Lomb_classifier_"] == "Null"]
for encoding_name in ["position", "distance", "null"]:
encoding_column_name = "rolling:proportion_encoding_"+encoding_name
fig, ax = plt.subplots(1,1, figsize=(6,4))
ax.set_xticks([0,1])
ax.set_ylim([0, 20]) # change the y limit if out of bounds
if suffix=="_nongrid_cells":
ax.set_ylim([0, 600])
ax.set_xlim([0, 1])
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.null_color]
ax.hist([pandas_collumn_to_numpy_array(Position_cells[encoding_column_name]),
pandas_collumn_to_numpy_array(Distance_cells[encoding_column_name]),
pandas_collumn_to_numpy_array(Null_cells[encoding_column_name])], bins=20, range=(0,1), color=colors, stacked=True)
#ax.set_xlabel("frac. session", fontsize=20)
#ax.set_ylabel("Number of cells", fontsize=20, labelpad=10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_tick_params(length=0)
ax.tick_params(axis='both', which='both', labelsize=30)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.2, right = 0.87, top = 0.92)
plt.savefig(save_path + '/block_length_encoding_'+encoding_name+suffix+'.png', dpi=300)
plt.close()
return
def plot_rolling_lomb_block_lengths_vs_shuffled(combined_df, save_path):
combined_df = combined_df[combined_df["Lomb_classifier_"] != "Unclassified"]
grid_cells = combined_df[combined_df["classifier"] == "G"]
fig, ax = plt.subplots(1,1, figsize=(4,4))
block_lengths = pandas_collumn_to_numpy_array(grid_cells["rolling:block_lengths"])
block_lengths_shuffled = pandas_collumn_to_numpy_array(grid_cells["rolling:block_lengths_shuffled"])
_, _, patches0 = ax.hist(block_lengths, density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color="red",linewidth=2)
_, _, patches1 = ax.hist(block_lengths_shuffled, density=True, bins=1000, cumulative=True, range=(0,1), histtype="step", color="grey",linewidth=2)
patches0[0].set_xy(patches0[0].get_xy()[:-1])
patches1[0].set_xy(patches1[0].get_xy()[:-1])
#ax.set_xlabel("Frac. session", fontsize=20)
#ax.set_ylabel("Density", fontsize=20, labelpad=10)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.set_xscale('log')
ax.xaxis.set_tick_params(length=0)
ax.tick_params(axis='both', which='both', labelsize=20)
plt.savefig(save_path + '/block_lengths_vs_shuffled_trials.png', dpi=300)
plt.close()
ks, p = stats.ks_2samp(block_lengths, block_lengths_shuffled)
return
def add_peak_width(combined_df):
peak_widths = []
for index, row in combined_df.iterrows():
avg_powers = row["MOVING_LOMB_avg_power"]
if np.sum(np.isnan(avg_powers))==0:
width, _, _, _ = signal.peak_widths(avg_powers, np.array([np.nanargmax(avg_powers)]))
width = width[0]*Settings.frequency_step
peak_index = np.nanargmax(avg_powers)
trough_indices = get_peak_indices(avg_powers, [peak_index])
# in cases where only 1 trough can be located, a trough indices will be at 0 or -1 (i.e. len(avg_powers))
if trough_indices[0][0] == 0:
# ignore this index and use only valid trough index and multiple this peak-to-trough x2
width_according_to_peak_indices = (trough_indices[0][1] - peak_index) * Settings.frequency_step * 2
elif trough_indices[0][1] == len(avg_powers):
# ignore this index and use only valid trough index and multiple this peak-to-trough x2
width_according_to_peak_indices = (peak_index - trough_indices[0][0]) * Settings.frequency_step * 2
else:
width_according_to_peak_indices = (trough_indices[0][1] - trough_indices[0][0]) * Settings.frequency_step
width = width_according_to_peak_indices
if width == 0:
print("stop here")
else:
width = np.nan
peak_widths.append(width)
combined_df["ML_peak_width"] = peak_widths
return combined_df
def plot_mean_firing_rates_on_position_and_distance_trials(combined_df, save_path, fig_size, suffix="", unlock_y=False):
grid_cells = combined_df[combined_df["classifier"] == "G"]
position_scores = grid_cells["rolling:position_mean_firing_rate"]
distance_scores = grid_cells["rolling:distance_mean_firing_rate"]
nan_mask = ~np.isnan(position_scores) & ~np.isnan(distance_scores)
position_scores = position_scores[nan_mask]
distance_scores = distance_scores[nan_mask]
fig, ax = plt.subplots(figsize=fig_size)
data = [position_scores, distance_scores, position_scores, distance_scores, position_scores, distance_scores, position_scores]
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2, 4,4,5,6,7], boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
ax.tick_params(axis='both', which='major', labelsize=25)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
if unlock_y:
ax.set_ylim(bottom=0)
else:
ax.set_ylim(bottom=0, top=15)
ax.set_yticks([0,5,10,15])
ax.set_xlim(left=0.5, right=3.5)
ax.set_xticks([1,2])
plt.xticks(rotation = 30)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.set_ylabel("Mean firing rate", fontsize=20)
ax.tick_params(axis='both', which='major', labelsize=25)
fig.tight_layout()
plt.savefig(save_path + '/' +'position_vs_distance_trials_mfr_'+suffix+'.png', dpi=300)
plt.close()
def plot_spatial_information_on_position_and_distance_trials(combined_df, save_path, fig_size, suffix="", unlock_y=False):
grid_cells = combined_df[combined_df["classifier"] == "G"]
position_scores = grid_cells["rolling:position_spatial_information_scores_Isec"]
distance_scores = grid_cells["rolling:distance_spatial_information_scores_Isec"]
nan_mask = ~np.isnan(position_scores) & ~np.isnan(distance_scores)
position_scores = position_scores[nan_mask]
distance_scores = distance_scores[nan_mask]
fig, ax = plt.subplots(figsize=fig_size)
data = [position_scores, distance_scores, position_scores, distance_scores, position_scores, distance_scores, position_scores]
colors=[Settings.allocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color, Settings.egocentric_color]
boxprops = dict(linewidth=3, color='k')
medianprops = dict(linewidth=3, color='k')
capprops = dict(linewidth=3, color='k')
whiskerprops = dict(linewidth=3, color='k')
box = ax.boxplot(data, positions=[1,2, 4,4,5,6,7], boxprops=boxprops, medianprops=medianprops,
whiskerprops=whiskerprops, capprops=capprops, patch_artist=True, showfliers=False)
for patch, color in zip(box['boxes'], colors):
patch.set_facecolor(color)
ax.tick_params(axis='both', which='major', labelsize=20)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
if unlock_y:
ax.set_ylim(bottom=0)
else:
ax.set_ylim(bottom=0, top=3)
ax.set_xlim(left=0.5, right=3.5)
ax.set_xticks([1,2])
ax.set_yticks([0,1, 2, 3])
ax.set_yticklabels(["00", "01", "02", "03"])
plt.xticks(rotation = 30)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#ax.set_ylabel("Spatial info bits/s", fontsize=20)
ax.tick_params(axis='both', which='major', labelsize=25)
fig.tight_layout()
plt.savefig(save_path + '/' +'position_vs_distance_trials_spatial_scores_'+suffix+'.png', dpi=300)
plt.close()
def behaviours_classification_to_numeric(behaviours_classifications):
numeric_classifications = []
for i in range(len(behaviours_classifications)):
if behaviours_classifications[i] == "hit":
numeric_classifications.append(1)