-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvr_grid_cells.py
1979 lines (1656 loc) · 101 KB
/
vr_grid_cells.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import traceback
import warnings
import sys
import settings
import matplotlib.pylab as plt
import matplotlib.ticker as ticker
import pandas as pd
from scipy import stats
from scipy import signal
from astropy.timeseries import LombScargle
from astropy.convolution import convolve, Gaussian1DKernel
from astropy.nddata import block_reduce
import control_sorting_analysis
import PostSorting.post_process_sorted_data_vr
import PostSorting.parameters
import PostSorting.vr_stop_analysis
import PostSorting.vr_time_analysis
import PostSorting.vr_make_plots
import PostSorting.vr_cued
import PostSorting.theta_modulation
import PostSorting.vr_spatial_data
from PostSorting.vr_spatial_firing import bin_fr_in_space, bin_fr_in_time, add_position_x, add_trial_number, add_trial_type
from eLife_Grid_anchoring_2024.Helpers.remake_position_data import syncronise_position_data
from eLife_Grid_anchoring_2024.Helpers.array_manipulations import *
import eLife_Grid_anchoring_2024.Helpers.plot_utility as plot_utility
import eLife_Grid_anchoring_2024.analysis_settings as Settings
warnings.filterwarnings('ignore')
plt.rc('axes', linewidth=3)
def add_avg_trial_speed(processed_position_data):
avg_trial_speeds = []
for trial_number in np.unique(processed_position_data["trial_number"]):
trial_processed_position_data = processed_position_data[processed_position_data["trial_number"] == trial_number]
speeds = np.asarray(trial_processed_position_data['speeds_binned_in_time'])[0]
avg_speed = np.nanmean(speeds)
avg_trial_speeds.append(avg_speed)
processed_position_data["avg_trial_speed"] = avg_trial_speeds
return processed_position_data
def add_avg_track_speed(processed_position_data, position_data, track_length):
reward_zone_start = track_length-60-30-20
reward_zone_end = track_length-60-30
track_start = 30
track_end = track_length-30
avg_speed_on_tracks = []
avg_speed_in_RZs = []
for i, trial_number in enumerate(processed_position_data.trial_number):
trial_processed_position_data = processed_position_data[processed_position_data["trial_number"] == trial_number]
trial_position_data = position_data[position_data["trial_number"] == trial_number]
speeds_in_time = np.array(trial_position_data["speed_per_100ms"])
pos_in_time = np.array(trial_position_data["x_position_cm"])
in_rz_mask = (pos_in_time > reward_zone_start) & (pos_in_time <= reward_zone_end)
speeds_in_time_outside_RZ = speeds_in_time[~in_rz_mask]
speeds_in_time_inside_RZ = speeds_in_time[in_rz_mask]
if len(speeds_in_time_outside_RZ)==0:
avg_speed_on_track = np.nan
else:
avg_speed_on_track = np.nanmean(speeds_in_time_outside_RZ)
if len(speeds_in_time_inside_RZ) == 0:
avg_speed_in_RZ = np.nan
else:
avg_speed_in_RZ= np.nanmean(speeds_in_time_inside_RZ)
avg_speed_on_tracks.append(avg_speed_on_track)
avg_speed_in_RZs.append(avg_speed_in_RZ)
processed_position_data["avg_speed_on_track"] = avg_speed_on_tracks
processed_position_data["avg_speed_in_RZ"] = avg_speed_in_RZs
return processed_position_data
def add_hit_miss_try(processed_position_data):
# first get the avg speeds in the reward zone for all hit trials
rewarded_processed_position_data = processed_position_data[processed_position_data["hit_blender"] == True]
speeds_in_rz = np.array(rewarded_processed_position_data["avg_speed_in_RZ"])
mean, sigma = np.nanmean(speeds_in_rz), np.nanstd(speeds_in_rz)
interval = stats.norm.interval(0.95, loc=mean, scale=sigma)
upper = interval[1]
lower = interval[0]
hit_miss_try =[]
for i, trial_number in enumerate(processed_position_data.trial_number):
trial_process_position_data = processed_position_data[(processed_position_data.trial_number == trial_number)]
track_speed = trial_process_position_data["avg_speed_on_track"].iloc[0]
speed_in_rz = trial_process_position_data["avg_speed_in_RZ"].iloc[0]
if (trial_process_position_data["hit_blender"].iloc[0] == True) and (track_speed>Settings.track_speed_threshold):
hit_miss_try.append("hit")
elif (speed_in_rz >= lower) and (speed_in_rz <= upper) and (track_speed>Settings.track_speed_threshold):
hit_miss_try.append("try")
elif (speed_in_rz < lower) or (speed_in_rz > upper) and (track_speed>Settings.track_speed_threshold):
hit_miss_try.append("miss")
else:
hit_miss_try.append("rejected")
processed_position_data["hit_miss_try"] = hit_miss_try
return processed_position_data, upper
def find_paired_recording(recording_path, of_recording_path_list):
mouse=recording_path.split("/")[-1].split("_")[0]
training_day=recording_path.split("/")[-1].split("_")[1]
for paired_recording in of_recording_path_list:
paired_mouse=paired_recording.split("/")[-1].split("_")[0]
paired_training_day=paired_recording.split("/")[-1].split("_")[1]
if (mouse == paired_mouse) and (training_day == paired_training_day):
return paired_recording, True
return None, False
def plot_spatial_autocorrelogram_fr(spike_data, save_path, track_length, suffix=""):
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_spike_data = spike_data[spike_data["cluster_id"] == cluster_id]
firing_rates = np.array(cluster_spike_data['fr_binned_in_space_smoothed'].iloc[0])
firing_times_cluster = np.array(cluster_spike_data["firing_times_vr"].iloc[0])
if len(firing_times_cluster)>1:
fr = firing_rates.flatten()
fr[np.isnan(fr)] = 0; fr[np.isinf(fr)] = 0
autocorr_window_size = track_length*10
lags = np.arange(0, autocorr_window_size, 1) # were looking at 10 timesteps back and 10 forward
autocorrelogram = []
for i in range(len(lags)):
fr_lagged = fr[i:]
corr = stats.pearsonr(fr_lagged, fr[:len(fr_lagged)])[0]
autocorrelogram.append(corr)
autocorrelogram= np.array(autocorrelogram)
fig = plt.figure(figsize=(5,2.5))
ax = fig.add_subplot(1, 1, 1) # specify (nrows, ncols, axnum)
for f in range(1,11):
ax.axvline(x=track_length*f, color="gray", linewidth=2,linestyle="solid", alpha=0.5)
ax.axhline(y=0, color="black", linewidth=2,linestyle="dashed")
ax.plot(lags, autocorrelogram, color="black", linewidth=3)
plt.ylabel('Spatial Autocorr', fontsize=25, labelpad = 10)
plt.xlabel('Lag (cm)', fontsize=25, labelpad = 10)
plt.xlim(0,(track_length*2)+3)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.set_ylim([np.floor(min(autocorrelogram[5:])*10)/10,np.ceil(max(autocorrelogram[5:])*10)/10])
if np.floor(min(autocorrelogram[5:])*10)/10 < 0:
ax.set_yticks([np.floor(min(autocorrelogram[5:])*10)/10, 0, np.ceil(max(autocorrelogram[5:])*10)/10])
else:
ax.set_yticks([-0.1, 0, np.ceil(max(autocorrelogram[5:])*10)/10])
tick_spacing = track_length
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
fig.tight_layout(pad=2.0)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.3, right = 0.87, top = 0.92)
plt.savefig(save_path + '/spatial_autocorrelogram_' + spike_data.session_id.iloc[cluster_index] + '_' + str(int(cluster_id)) + suffix + '.png', dpi=200)
plt.close()
def calculate_moving_lomb_scargle_periodogram(spike_data, processed_position_data, track_length, shuffled_trials=False):
print('calculating moving lomb_scargle periodogram...')
if shuffled_trials:
suffix="_shuffled_trials"
else:
suffix=""
n_trials = len(processed_position_data)
elapsed_distance_bins = np.arange(0, (track_length*n_trials)+1, 1)
elapsed_distance = 0.5*(elapsed_distance_bins[1:]+elapsed_distance_bins[:-1])/track_length
shuffled_rate_maps = []
freqs = []
SNRs = []
avg_powers = []
all_powers = []
all_centre_trials=[]
all_centre_distances=[]
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_spike_data = spike_data[spike_data["cluster_id"] == cluster_id]
firing_rates = np.array(cluster_spike_data["fr_binned_in_space_smoothed"].iloc[0])
firing_times_cluster = np.array(cluster_spike_data["firing_times"].iloc[0])
if len(firing_times_cluster)>1:
if shuffled_trials:
np.random.shuffle(firing_rates)
fr = firing_rates.flatten()
# construct the lomb-scargle periodogram
frequency = Settings.frequency
sliding_window_size=track_length*Settings.window_length_in_laps
powers = []
centre_distances = []
indices_to_test = np.arange(0, len(fr)-sliding_window_size, 1, dtype=np.int64)[::Settings.power_estimate_step]
for m in indices_to_test:
ls = LombScargle(elapsed_distance[m:m+sliding_window_size], fr[m:m+sliding_window_size])
power = ls.power(frequency)
powers.append(power.tolist())
centre_distances.append(np.nanmean(elapsed_distance[m:m+sliding_window_size]))
powers = np.array(powers)
centre_trials = np.round(np.array(centre_distances)).astype(np.int64)
centre_distances = np.array(centre_distances)
avg_power = np.nanmean(powers, axis=0)
max_SNR, max_SNR_freq = get_max_SNR(frequency, avg_power)
freqs.append(max_SNR_freq)
SNRs.append(max_SNR)
avg_powers.append(avg_power)
all_powers.append(powers)
all_centre_trials.append(centre_trials)
shuffled_rate_maps.append(firing_rates)
all_centre_distances.append(centre_distances)
else:
freqs.append(np.nan)
SNRs.append(np.nan)
avg_powers.append(np.nan)
all_powers.append(np.nan)
all_centre_trials.append(np.nan)
shuffled_rate_maps.append(np.nan)
all_centre_distances.append(np.nan)
spike_data["MOVING_LOMB_freqs"+suffix] = freqs
spike_data["MOVING_LOMB_avg_power"+suffix] = avg_powers
spike_data["MOVING_LOMB_SNR"+suffix] = SNRs
spike_data["MOVING_LOMB_all_powers"+suffix] = all_powers
spike_data["MOVING_LOMB_all_centre_trials"+suffix] = all_centre_trials
spike_data["MOVING_LOMB_all_centre_distances"+suffix] = all_centre_distances
if shuffled_trials:
spike_data["rate_maps"+suffix] = shuffled_rate_maps
return spike_data
def analyse_lomb_powers(spike_data):
frequency = Settings.frequency
SNRs = [];
Freqs = []
for index, spike_row in spike_data.iterrows():
cluster_spike_data = spike_row.to_frame().T.reset_index(drop=True)
powers = np.array(cluster_spike_data["MOVING_LOMB_all_powers"].iloc[0])
firing_times_cluster = np.array(cluster_spike_data["firing_times"].iloc[0])
if len(firing_times_cluster)>1:
avg_powers = np.nanmean(powers, axis=0)
max_SNR, max_SNR_freq = get_max_SNR(frequency, avg_powers)
SNRs.append(max_SNR)
Freqs.append(max_SNR_freq)
spike_data["ML_SNRs"] = SNRs
spike_data["ML_Freqs"] = Freqs
return spike_data
def get_tt_color(tt):
if tt == 0:
return "black"
elif tt==1:
return "red"
elif tt ==2:
return "blue"
def get_hmt_linestyle(hmt):
if hmt == "hit":
return "solid"
elif hmt=="miss":
return "dashed"
elif hmt =="try":
return "dotted"
def get_numeric_lomb_classifer(lomb_classifier_str):
if lomb_classifier_str == "Position":
return 0
elif lomb_classifier_str == "Distance":
return 1
elif lomb_classifier_str == "Null":
return 2
elif lomb_classifier_str == "P":
return 0.5
elif lomb_classifier_str == "D":
return 1.5
elif lomb_classifier_str == "N":
return 2.5
else:
return 3.5
def get_lomb_classifier(lomb_SNR, lomb_freq, lomb_SNR_thres, lomb_freq_thres, numeric=False):
lomb_distance_from_int = distance_from_integer(lomb_freq)[0]
if lomb_SNR>lomb_SNR_thres:
if lomb_distance_from_int<lomb_freq_thres:
lomb_classifier = "Position"
else:
lomb_classifier = "Distance"
else:
if np.isnan(lomb_distance_from_int):
lomb_classifier = "Unclassified"
else:
lomb_classifier = "Null"
if numeric:
return get_numeric_lomb_classifer(lomb_classifier)
else:
return lomb_classifier
def add_lomb_classifier(spatial_firing, suffix=""):
"""
:param spatial_firing:
:param suffix: specific set string for subsets of results
:return: spatial_firing with classifier collumn of type ["Lomb_classifer_"+suffix] with either "Distance", "Position" or "Null"
"""
lomb_classifiers = []
for index, row in spatial_firing.iterrows():
lomb_SNR_threshold = row["power_threshold"]
lomb_SNR = row["ML_SNRs"+suffix]
lomb_freq = row["ML_Freqs"+suffix]
lomb_classifier = get_lomb_classifier(lomb_SNR, lomb_freq, lomb_SNR_threshold, 0.05, numeric=False)
lomb_classifiers.append(lomb_classifier)
spatial_firing["Lomb_classifier_"+suffix] = lomb_classifiers
return spatial_firing
def distance_from_integer(frequencies):
distance_from_zero = np.asarray(frequencies)%1
distance_from_one = 1-(np.asarray(frequencies)%1)
tmp = np.vstack((distance_from_zero, distance_from_one))
return np.min(tmp, axis=0)
def style_track_plot_no_RZ(ax, track_length):
ax.axvline(x=track_length-60-30-20, color="black", linestyle="dotted", linewidth=1)
ax.axvline(x=track_length-60-30, color="black", linestyle="dotted", linewidth=1)
ax.axvspan(0, 30, facecolor='k', linewidth =0, alpha=.25) # black box
ax.axvspan(track_length-30, track_length, facecolor='k', linewidth =0, alpha=.25)# black box
def style_track_plot(ax, track_length):
ax.axvspan(0, 30, facecolor='k', linewidth =0, alpha=.25) # black box
ax.axvspan(track_length-110, track_length-90, facecolor='DarkGreen', alpha=.25, linewidth =0)
ax.axvspan(track_length-30, track_length, facecolor='k', linewidth =0, alpha=.25)# black box
def plot_spikes_on_track(spike_data, processed_position_data, output_path, track_length=200,
plot_trials=["beaconed", "non_beaconed", "probe"]):
print('plotting spike rastas...')
save_path = output_path + '/Figures/spike_trajectories'
if os.path.exists(save_path) is False:
os.makedirs(save_path)
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_spike_data = spike_data[spike_data["cluster_id"] == cluster_id]
if "firing_times_vr" in list(spike_data):
firing_times_cluster = spike_data["firing_times_vr"].iloc[cluster_index]
else:
firing_times_cluster = spike_data["firing_times"].iloc[cluster_index]
if len(firing_times_cluster)>1:
x_max = len(processed_position_data)
spikes_on_track = plt.figure()
spikes_on_track.set_size_inches(5, 5, forward=True)
ax = spikes_on_track.add_subplot(1, 1, 1)
if "beaconed" in plot_trials:
ax.plot(cluster_spike_data.iloc[0].beaconed_position_cm, cluster_spike_data.iloc[0].beaconed_trial_number, '|', color='Black', markersize=4)
if "non_beaconed" in plot_trials:
ax.plot(cluster_spike_data.iloc[0].nonbeaconed_position_cm, cluster_spike_data.iloc[0].nonbeaconed_trial_number, '|', color='Black', markersize=4)
if "probe" in plot_trials:
ax.plot(cluster_spike_data.iloc[0].probe_position_cm, cluster_spike_data.iloc[0].probe_trial_number, '|', color='Black', markersize=4)
plt.ylabel('Spikes on trials', fontsize=20, labelpad = 10)
plt.xlabel('Location (cm)', fontsize=20, labelpad = 10)
plt.xlim(0,track_length)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
style_track_plot(ax, track_length)
tick_spacing = 100
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plot_utility.style_vr_plot(ax, x_max)
plt.locator_params(axis = 'y', nbins = 4)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.tight_layout()
if len(plot_trials)<3:
plt.savefig(save_path + '/' + spike_data.session_id.iloc[cluster_index] + '_track_firing_Cluster_' + str(cluster_id) + "_" + str("_".join(plot_trials)) + '.png', dpi=200)
else:
plt.savefig(save_path + '/' + spike_data.session_id.iloc[cluster_index] + '_track_firing_Cluster_' + str(cluster_id) + '.png', dpi=200)
plt.close()
def plot_avg_spatial_periodograms_with_rolling_classifications(spike_data, processed_position_data, save_path, track_length, plot_for_all_trials=True, plot_avg = True):
power_step = Settings.power_estimate_step
step = Settings.frequency_step
frequency = Settings.frequency
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_spike_data = spike_data[spike_data["cluster_id"] == cluster_id]
firing_times_cluster = np.array(cluster_spike_data["firing_times_vr"].iloc[0])#
rolling_power_threshold = cluster_spike_data["rolling_threshold"].iloc[0]
power_threshold = cluster_spike_data["power_threshold"].iloc[0]
if len(firing_times_cluster)>1:
powers = np.array(cluster_spike_data["MOVING_LOMB_all_powers"].iloc[0])
centre_trials = np.array(cluster_spike_data["MOVING_LOMB_all_centre_trials"].iloc[0])
centre_trials = np.round(centre_trials).astype(np.int64)
rolling_lomb_classifier, rolling_lomb_classifier_numeric, rolling_lomb_classifier_colors, rolling_frequencies, rolling_points = \
get_rolling_lomb_classifier_for_centre_trial(centre_trials=centre_trials, powers=powers, power_threshold=rolling_power_threshold, power_step=power_step, track_length=track_length)
spikes_on_track = plt.figure()
spikes_on_track.set_size_inches(5, 5/3, forward=True)
ax = spikes_on_track.add_subplot(1, 1, 1)
for f in range(1,6):
ax.axvline(x=f, color="gray", linewidth=2,linestyle="solid", alpha=0.5)
# add avg periodograms for position and distance coded trials
for code, c in zip(["D", "P"], [Settings.egocentric_color, Settings.allocentric_color]):
subset_trial_numbers = np.unique(rolling_points[rolling_lomb_classifier==code])
# only plot if there if this is at least 15% of total trials
if (len(subset_trial_numbers)/len(processed_position_data["trial_number"])>=0.15) or (plot_for_all_trials==True):
subset_mask = np.isin(centre_trials, subset_trial_numbers)
subset_mask = np.vstack([subset_mask]*len(powers[0])).T
subset_powers = powers.copy()
subset_powers[subset_mask == False] = np.nan
avg_subset_powers = np.nanmean(subset_powers, axis=0)
sem_subset_powers = stats.sem(subset_powers, axis=0, nan_policy="omit")
ax.fill_between(frequency, avg_subset_powers-sem_subset_powers, avg_subset_powers+sem_subset_powers, color=c, alpha=0.3)
ax.plot(frequency, avg_subset_powers, color=c, linewidth=3)
if plot_avg:
subset_trial_numbers = np.asarray(processed_position_data["trial_number"])
subset_mask = np.isin(centre_trials, subset_trial_numbers)
subset_mask = np.vstack([subset_mask]*len(powers[0])).T
subset_powers = powers.copy()
subset_powers[subset_mask == False] = np.nan
avg_subset_powers = np.nanmean(subset_powers, axis=0)
sem_subset_powers = stats.sem(subset_powers, axis=0, nan_policy="omit")
ax.fill_between(frequency, avg_subset_powers-sem_subset_powers, avg_subset_powers+sem_subset_powers, color="black", alpha=0.3, zorder=-1)
ax.plot(frequency, avg_subset_powers, color="black", linewidth=3, zorder=-1)
ax.axhline(y=power_threshold, color="red", linewidth=3, linestyle="dashed")
ax.set_ylabel('Periodic power', fontsize=30, labelpad = 10)
#ax.set_xlabel("Spatial frequency", fontsize=25, labelpad = 10)
ax.set_xlim([0.1,5.05])
ax.set_xticks([1,2,3,4, 5])
ax.set_yticks([0, np.round(ax.get_ylim()[1], 2)])
ax.set_ylim(bottom=0)
ax.yaxis.set_tick_params(labelsize=20)
ax.xaxis.set_tick_params(labelsize=20)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.3, right = 0.87, top = 0.92)
plt.savefig(save_path + '/avg_spatial_periodograms_with_rolling_classifications_' + cluster_spike_data.session_id.iloc[0] + '' + str(int(cluster_id)) + '.png', dpi=300)
plt.close()
return
def find_neighbouring_minima(firing_rate_map, local_maximum_idx):
# walk right
local_min_right = local_maximum_idx
local_min_right_found = False
for i in np.arange(local_maximum_idx, len(firing_rate_map)): #local max to end
if local_min_right_found == False:
if np.isnan(firing_rate_map[i]):
continue
elif firing_rate_map[i] < firing_rate_map[local_min_right]:
local_min_right = i
elif firing_rate_map[i] > firing_rate_map[local_min_right]:
local_min_right_found = True
# walk left
local_min_left = local_maximum_idx
local_min_left_found = False
for i in np.arange(0, local_maximum_idx)[::-1]: # local max to start
if local_min_left_found == False:
if np.isnan(firing_rate_map[i]):
continue
elif firing_rate_map[i] < firing_rate_map[local_min_left]:
local_min_left = i
elif firing_rate_map[i] > firing_rate_map[local_min_left]:
local_min_left_found = True
return (local_min_left, local_min_right)
def make_field_array(firing_rate_map_by_trial, peaks_indices):
field_array = np.zeros(len(firing_rate_map_by_trial))
for i in range(len(peaks_indices)):
field_array[peaks_indices[i][0]:peaks_indices[i][1]] = i+1
return field_array.astype(np.int64)
def get_peak_indices(firing_rate_map, peaks_i):
peak_indices =[]
for j in range(len(peaks_i)):
peak_index_tuple = find_neighbouring_minima(firing_rate_map, peaks_i[j])
peak_indices.append(peak_index_tuple)
return peak_indices
def plot_firing_rate_maps_short_with_rolling_classifications(spike_data, save_path, track_length, plot_avg=True, plot_codes=True):
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_df = spike_data[(spike_data.cluster_id == cluster_id)] # dataframe for that cluster
firing_times_cluster = spike_data.firing_times_vr.iloc[cluster_index]
if len(firing_times_cluster)>1:
cluster_firing_maps = np.array(spike_data['fr_binned_in_space_smoothed'].iloc[cluster_index])
rolling_centre_trials = np.array(spike_data["rolling:rolling_centre_trials"].iloc[cluster_index])
rolling_classifiers = np.array(spike_data["rolling:rolling_classifiers"].iloc[cluster_index])
cluster_firing_maps[np.isnan(cluster_firing_maps)] = np.nan
cluster_firing_maps[np.isinf(cluster_firing_maps)] = np.nan
spikes_on_track = plt.figure()
spikes_on_track.set_size_inches(5, 5/3, forward=True)
ax = spikes_on_track.add_subplot(1, 1, 1)
locations = np.arange(0, len(cluster_firing_maps[0]))
if plot_avg:
ax.fill_between(locations, np.nanmean(cluster_firing_maps, axis=0)-stats.sem(cluster_firing_maps, axis=0, nan_policy="omit"), np.nanmean(cluster_firing_maps, axis=0)+stats.sem(cluster_firing_maps, axis=0, nan_policy="omit"), color="black", alpha=0.3)
ax.plot(locations, np.nanmean(cluster_firing_maps, axis=0), color="black", linewidth=3)
if plot_codes:
for code, code_color in zip(["D", "P"], [Settings.egocentric_color, Settings.allocentric_color]):
trial_numbers = rolling_centre_trials[rolling_classifiers==code]
code_cluster_firing_maps = cluster_firing_maps[trial_numbers-1]
ax.fill_between(locations, np.nanmean(code_cluster_firing_maps, axis=0)-stats.sem(code_cluster_firing_maps, axis=0, nan_policy="omit"), np.nanmean(code_cluster_firing_maps, axis=0)+stats.sem(code_cluster_firing_maps, axis=0, nan_policy="omit"), color=code_color, alpha=0.3)
ax.plot(locations, np.nanmean(code_cluster_firing_maps, axis=0), color=code_color, linewidth=3)
plt.ylabel('FR (Hz)', fontsize=25, labelpad = 10)
plt.xlabel('Location (cm)', fontsize=25, labelpad = 10)
plt.xlim(0, track_length)
ax.tick_params(axis='both', which='both', labelsize=20)
ax.set_xlim([0, track_length])
ax.set_yticks([0, np.round(ax.get_ylim()[1], 1)])
ax.set_ylim(bottom=0)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_major_locator(ticker.MultipleLocator(100))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.3, right = 0.87, top = 0.92)
plt.savefig(save_path + '/firing_rate_maps_short_with_rolling_classifications_' + spike_data.session_id.iloc[cluster_index] + '_' + str(int(cluster_id)) + '.png', dpi=300)
plt.close()
return
def get_spatial_information_score_for_trials(track_length, position_data, cluster_df, trial_ids):
spikes_locations = np.array(cluster_df["x_position_cm"].iloc[0])
spike_trial_numbers = np.array(cluster_df["trial_number"].iloc[0])
spikes_locations = spikes_locations[np.isin(spike_trial_numbers, trial_ids)]
spike_trial_numbers = spike_trial_numbers[np.isin(spike_trial_numbers, trial_ids)]
number_of_spikes = len(spikes_locations)
if number_of_spikes == 0:
return np.nan
position_data = position_data[position_data["trial_number"].isin(spike_trial_numbers)]
position_heatmap = np.zeros(track_length)
for x in np.arange(track_length):
bin_occupancy = len(position_data[(position_data["x_position_cm"] > x) &
(position_data["x_position_cm"] <= x+1)])
position_heatmap[x] = bin_occupancy
position_heatmap = position_heatmap*np.diff(position_data["time_seconds"])[-1] # convert to real time in seconds
occupancy_probability_map = position_heatmap/np.sum(position_heatmap) # Pj
vr_bin_size_cm = settings.vr_bin_size_cm
gauss_kernel = Gaussian1DKernel(settings.guassian_std_for_smoothing_in_space_cm/vr_bin_size_cm)
mean_firing_rate = number_of_spikes/np.sum(len(position_data)*np.diff(position_data["time_seconds"])[-1]) # λ
spikes, _ = np.histogram(spikes_locations, bins=track_length, range=(0,track_length))
rates = spikes/position_heatmap
#rates = convolve(rates, gauss_kernel)
mrate = mean_firing_rate
Isec = np.sum(occupancy_probability_map * rates * np.log2((rates / mrate) + 0.0001))
Ispike = Isec / mrate
if np.isnan(Ispike):
Ispike = 0
if Ispike < 0:
print("hello")
return Isec
def plot_of_rate_map(spike_data, save_path):
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_df = spike_data[(spike_data.cluster_id == cluster_id)] # dataframe for that cluster
firing_rate_map_original = cluster_df['firing_maps_of'].iloc[0]
occupancy_map = cluster_df['occupancy_maps_of'].iloc[0]
firing_rate_map_original[occupancy_map == 0] = np.nan
firing_rate_map = np.rot90(firing_rate_map_original)
firing_rate_map_fig = plt.figure()
firing_rate_map_fig.set_size_inches(5, 5, forward=True)
ax = firing_rate_map_fig.add_subplot(1, 1, 1) # specify (nrows, ncols, axnum)
ax = plot_utility.style_open_field_plot(ax)
cmap = plt.get_cmap('jet')
cmap.set_bad("white")
rate_map_img = ax.imshow(firing_rate_map, cmap=cmap, interpolation='nearest')
firing_rate_map_fig.colorbar(rate_map_img)
plt.savefig(save_path + '/open_field_rate_map_' + spike_data.session_id.iloc[cluster_index] + '_' + str(int(cluster_id)) + '.png', dpi=300)
plt.close()
def plot_of_autocorrelogram(spike_data, save_path):
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_df = spike_data[(spike_data.cluster_id == cluster_id)] # dataframe for that cluster
rate_map_autocorr_fig = plt.figure()
rate_map_autocorr_fig.set_size_inches(5, 5, forward=True)
ax = rate_map_autocorr_fig.add_subplot(1, 1, 1) # specify (nrows, ncols, axnum)
rate_map_autocorr = cluster_df['rate_map_autocorrelogram_of'].iloc[0]
if rate_map_autocorr.size:
ax = plt.subplot(1, 1, 1)
ax = plot_utility.style_open_field_plot(ax)
autocorr_img = ax.imshow(rate_map_autocorr, cmap='jet', interpolation='nearest')
rate_map_autocorr_fig.colorbar(autocorr_img)
plt.tight_layout()
plt.title('Autocorrelogram \n grid score: ' + str(round(cluster_df['grid_score'].iloc[0], 2)), fontsize=24)
plt.savefig(save_path + '/open_field_rate_map_autocorrelogram_' + spike_data.session_id.iloc[cluster_index] + '_' + str(
int(cluster_id)) + '.png', dpi=300)
plt.close()
def plot_firing_rate_maps_short(spike_data, processed_position_data, save_path, track_length, by_trial_type=False, save_path_folder=True):
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
if "firing_times_vr" in list(spike_data):
firing_times_cluster = spike_data["firing_times_vr"].iloc[cluster_index]
else:
firing_times_cluster = spike_data["firing_times"].iloc[cluster_index]
if len(firing_times_cluster)>1:
cluster_firing_maps = np.array(spike_data['fr_binned_in_space_smoothed'].iloc[cluster_index])
cluster_firing_maps[np.isnan(cluster_firing_maps)] = np.nan
cluster_firing_maps[np.isinf(cluster_firing_maps)] = np.nan
spikes_on_track = plt.figure()
spikes_on_track.set_size_inches(5, 5/3, forward=True)
ax = spikes_on_track.add_subplot(1, 1, 1)
locations = np.arange(0, len(cluster_firing_maps[0]))
if by_trial_type:
for tt in [0,1,2]:
tt_trial_numbers = np.array(processed_position_data[processed_position_data["trial_type"] == tt]["trial_number"])
ax.fill_between(locations, np.nanmean(cluster_firing_maps[tt_trial_numbers-1], axis=0) - stats.sem(cluster_firing_maps[tt_trial_numbers-1], axis=0,nan_policy="omit"),
np.nanmean(cluster_firing_maps[tt_trial_numbers-1], axis=0) + stats.sem(cluster_firing_maps[tt_trial_numbers-1], axis=0,nan_policy="omit"),
color=get_trial_color(tt), alpha=0.2)
ax.plot(locations, np.nanmean(cluster_firing_maps[tt_trial_numbers-1], axis=0), color=get_trial_color(tt), linewidth=1)
else:
ax.fill_between(locations, np.nanmean(cluster_firing_maps, axis=0) - stats.sem(cluster_firing_maps, axis=0,nan_policy="omit"),
np.nanmean(cluster_firing_maps, axis=0) + stats.sem(cluster_firing_maps, axis=0,nan_policy="omit"), color="black",alpha=0.2)
ax.plot(locations, np.nanmean(cluster_firing_maps, axis=0), color="black", linewidth=1)
plt.ylabel('FR (Hz)', fontsize=25, labelpad = 10)
plt.xlabel('Location (cm)', fontsize=25, labelpad = 10)
plt.xlim(0, track_length)
ax.tick_params(axis='both', which='both', labelsize=20)
ax.set_xlim([0, track_length])
max_fr = max(np.nanmean(cluster_firing_maps, axis=0)+stats.sem(cluster_firing_maps, axis=0))
max_fr = max_fr+(0.1*(max_fr))
#ax.set_ylim([0, max_fr])
ax.set_yticks([0, np.round(ax.get_ylim()[1], 1)])
ax.set_ylim(bottom=0)
#plot_utility.style_track_plot(ax, track_length, alpha=0.25)
plot_utility.style_track_plot(ax, track_length, alpha=0.15)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.xaxis.set_major_locator(ticker.MultipleLocator(100))
#ax.yaxis.set_major_locator(ticker.MultipleLocator(50))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.3, right = 0.87, top = 0.92)
#plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
#cbar = spikes_on_track.colorbar(c, ax=ax, fraction=0.046, pad=0.04)
#cbar.set_label('Firing Rate (Hz)', rotation=270, fontsize=20)
#cbar.set_ticks([0,vmax])
#cbar.set_ticklabels(["0", "Max"])
#cbar.outline.set_visible(False)
#cbar.ax.tick_params(labelsize=20)
plt.savefig(save_path + '/avg_firing_rate_maps_short_' + spike_data.session_id.iloc[cluster_index] + '_' + str(int(cluster_id)) + '.png', dpi=300)
plt.close()
return
def plot_firing_rate_maps_per_trial(spike_data, processed_position_data, save_path, track_length, save_path_folder=False):
if save_path_folder:
save_path = save_path + '/Figures/rate_maps_by_trial'
if os.path.exists(save_path) is False:
os.makedirs(save_path)
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
if "firing_times_vr" in list(spike_data):
firing_times_cluster = spike_data["firing_times_vr"].iloc[cluster_index]
else:
firing_times_cluster = spike_data["firing_times"].iloc[cluster_index]
if len(firing_times_cluster)>1:
cluster_firing_maps = np.array(spike_data['fr_binned_in_space_smoothed'].iloc[cluster_index])
cluster_firing_maps[np.isnan(cluster_firing_maps)] = 0
cluster_firing_maps[np.isinf(cluster_firing_maps)] = 0
percentile_99th_display = np.nanpercentile(cluster_firing_maps, 99);
cluster_firing_maps = min_max_normalize(cluster_firing_maps)
percentile_99th = np.nanpercentile(cluster_firing_maps, 99); cluster_firing_maps = np.clip(cluster_firing_maps, a_min=0, a_max=percentile_99th)
vmin, vmax = plot_utility.get_vmin_vmax(cluster_firing_maps)
spikes_on_track = plt.figure()
spikes_on_track.set_size_inches(5, 5, forward=True)
ax = spikes_on_track.add_subplot(1, 1, 1)
locations = np.arange(0, len(cluster_firing_maps[0]))
ordered = np.arange(0, len(processed_position_data), 1)
X, Y = np.meshgrid(locations, ordered)
cmap = plt.cm.get_cmap(Settings.rate_map_cmap)
ax.pcolormesh(X, Y, cluster_firing_maps, cmap=cmap, shading="auto", vmin=vmin, vmax=vmax)
plt.title(str(np.round(percentile_99th_display, decimals=1))+" Hz", fontsize=20)
#plt.ylabel('Trial Number', fontsize=20, labelpad = 20)
#plt.xlabel('Location (cm)', fontsize=20, labelpad = 20)
plt.xlim(0, track_length)
ax.tick_params(axis='both', which='both', labelsize=20)
ax.set_xlim([0, track_length])
ax.set_ylim([0, len(processed_position_data)-1])
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
tick_spacing = 100
plt.locator_params(axis='y', nbins=3)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
spikes_on_track.tight_layout(pad=2.0)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.3, right = 0.87, top = 0.92)
#cbar = spikes_on_track.colorbar(c, ax=ax, fraction=0.046, pad=0.04)
#cbar.set_label('Firing Rate (Hz)', rotation=270, fontsize=20)
#cbar.set_ticks([0,np.max(cluster_firing_maps)])
#cbar.set_ticklabels(["0", "Max"])
#cbar.ax.tick_params(labelsize=20)
plt.savefig(save_path + '/firing_rate_map_trials_' + spike_data.session_id.iloc[cluster_index] + '_' + str(int(cluster_id)) + '.png', dpi=300)
plt.close()
return
def get_track_length(recording_path):
parameter_file_path = control_sorting_analysis.get_tags_parameter_file(recording_path)
stop_threshold, track_length, cue_conditioned_goal = PostSorting.post_process_sorted_data_vr.process_running_parameter_tag(parameter_file_path)
return track_length
def plot_firing_rate_maps(spike_data, processed_position_data, output_path, track_length=200):
gauss_kernel = Gaussian1DKernel(2)
print('I am plotting firing rate maps...')
save_path = output_path + '/Figures/spike_rate'
if os.path.exists(save_path) is False:
os.makedirs(save_path)
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_spike_data = spike_data[(spike_data["cluster_id"] == cluster_id)]
avg_beaconed_spike_rate = np.array(cluster_spike_data["beaconed_firing_rate_map"].to_list()[0])
avg_nonbeaconed_spike_rate = np.array(cluster_spike_data["non_beaconed_firing_rate_map"].to_list()[0])
avg_probe_spike_rate = np.array(cluster_spike_data["probe_firing_rate_map"].to_list()[0])
beaconed_firing_rate_map_sem = np.array(cluster_spike_data["beaconed_firing_rate_map_sem"].to_list()[0])
non_beaconed_firing_rate_map_sem = np.array(cluster_spike_data["non_beaconed_firing_rate_map_sem"].to_list()[0])
probe_firing_rate_map_sem = np.array(cluster_spike_data["probe_firing_rate_map_sem"].to_list()[0])
avg_beaconed_spike_rate = convolve(avg_beaconed_spike_rate, gauss_kernel) # convolve and smooth beaconed
beaconed_firing_rate_map_sem = convolve(beaconed_firing_rate_map_sem, gauss_kernel)
if len(avg_nonbeaconed_spike_rate)>0:
avg_nonbeaconed_spike_rate = convolve(avg_nonbeaconed_spike_rate, gauss_kernel) # convolve and smooth non beaconed
non_beaconed_firing_rate_map_sem = convolve(non_beaconed_firing_rate_map_sem, gauss_kernel)
if len(avg_probe_spike_rate)>0:
avg_probe_spike_rate = convolve(avg_probe_spike_rate, gauss_kernel) # convolve and smooth probe
probe_firing_rate_map_sem = convolve(probe_firing_rate_map_sem, gauss_kernel)
avg_spikes_on_track = plt.figure()
avg_spikes_on_track.set_size_inches(5, 5, forward=True)
ax = avg_spikes_on_track.add_subplot(1, 1, 1)
bin_centres = np.array(processed_position_data["position_bin_centres"].iloc[0])
#plotting the rates are filling with the standard error around the mean
ax.plot(bin_centres, avg_beaconed_spike_rate, '-', color='Black')
ax.fill_between(bin_centres, avg_beaconed_spike_rate-beaconed_firing_rate_map_sem,
avg_beaconed_spike_rate+beaconed_firing_rate_map_sem, color="Black", alpha=0.5)
if len(avg_nonbeaconed_spike_rate)>0:
ax.plot(bin_centres, avg_nonbeaconed_spike_rate, '-', color='Red')
ax.fill_between(bin_centres, avg_nonbeaconed_spike_rate-non_beaconed_firing_rate_map_sem,
avg_nonbeaconed_spike_rate+non_beaconed_firing_rate_map_sem, color="Red", alpha=0.5)
if len(avg_probe_spike_rate)>0:
ax.plot(bin_centres, avg_probe_spike_rate, '-', color='Blue')
ax.fill_between(bin_centres, avg_probe_spike_rate-probe_firing_rate_map_sem,
avg_probe_spike_rate+probe_firing_rate_map_sem, color="Blue", alpha=0.5)
tick_spacing = 50
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.ylabel('Spike rate (hz)', fontsize=20, labelpad = 10)
plt.xlabel('Location (cm)', fontsize=20, labelpad = 10)
plt.xlim(0,track_length)
x_max = np.nanmax(avg_beaconed_spike_rate)
if len(avg_nonbeaconed_spike_rate)>0:
nb_x_max = np.nanmax(avg_nonbeaconed_spike_rate)
if nb_x_max > x_max:
x_max = nb_x_max
plot_utility.style_vr_plot(ax, x_max)
plot_utility.style_track_plot(ax, track_length)
plt.tight_layout()
plt.savefig(save_path + '/' + spike_data.session_id.iloc[cluster_index] + '_rate_map_Cluster_' + str(cluster_id) + '.png', dpi=200)
plt.close()
def get_trial_color(trial_type):
if trial_type == 0:
return "tab:blue"
elif trial_type == 1:
return "tab:red"
elif trial_type == 2:
return "lightcoral"
else:
print("invalid trial-type passed to get_trial_color()")
def plot_stops_on_track(processed_position_data, output_path, track_length=200):
print('I am plotting stop rasta...')
save_path = output_path+'/Figures/behaviour'
if os.path.exists(save_path) is False:
os.makedirs(save_path)
stops_on_track = plt.figure(figsize=(6,6))
ax = stops_on_track.add_subplot(1, 1, 1) # specify (nrows, ncols, axnum)
for index, trial_row in processed_position_data.iterrows():
trial_row = trial_row.to_frame().T.reset_index(drop=True)
trial_type = trial_row["trial_type"].iloc[0]
trial_number = trial_row["trial_number"].iloc[0]
trial_stop_color = get_trial_color(trial_type)
if trial_stop_color == "blue":
alpha=0
else:
alpha=1
ax.plot(np.array(trial_row["stop_location_cm"].iloc[0]), trial_number*np.ones(len(trial_row["stop_location_cm"].iloc[0])), 'o', color=trial_stop_color, markersize=4, alpha=alpha)
plt.ylabel('Stops on trials', fontsize=25, labelpad = 10)
plt.xlabel('Location (cm)', fontsize=25, labelpad = 10)
plt.xlim(0,track_length)
tick_spacing = 100
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.xaxis.set_tick_params(labelsize=20)
ax.yaxis.set_tick_params(labelsize=20)
plot_utility.style_track_plot(ax, track_length)
n_trials = len(processed_position_data)
x_max = n_trials+0.5
plot_utility.style_vr_plot(ax, x_max)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.32, right = 0.87, top = 0.92)
plt.savefig(output_path + '/Figures/behaviour/stop_raster' + '.png', dpi=200)
plt.close()
def plot_stop_histogram(processed_position_data, output_path, track_length=200):
print('plotting stop histogram...')
save_path = output_path + '/Figures/behaviour'
if os.path.exists(save_path) is False:
os.makedirs(save_path)
stop_histogram = plt.figure(figsize=(6,2))
ax = stop_histogram.add_subplot(1, 1, 1)
bin_size = 5
beaconed_trials = processed_position_data[processed_position_data["trial_type"] == 0]
non_beaconed_trials = processed_position_data[processed_position_data["trial_type"] == 1]
probe_trials = processed_position_data[processed_position_data["trial_type"] == 2]
beaconed_stops = pandas_collumn_to_numpy_array(beaconed_trials["stop_location_cm"])
non_beaconed_stops = pandas_collumn_to_numpy_array(non_beaconed_trials["stop_location_cm"])
#probe_stops = pandas_collumn_to_numpy_array(probe_trials["stop_location_cm"])
beaconed_stop_hist, bin_edges = np.histogram(beaconed_stops, bins=int(track_length/bin_size), range=(0, track_length))
non_beaconed_stop_hist, bin_edges = np.histogram(non_beaconed_stops, bins=int(track_length/bin_size), range=(0, track_length))
#probe_stop_hist, bin_edges = np.histogram(probe_stops, bins=int(track_length/bin_size), range=(0, track_length))
bin_centres = 0.5*(bin_edges[1:]+bin_edges[:-1])
ax.plot(bin_centres, beaconed_stop_hist/len(beaconed_trials), '-', color='Black')
if len(non_beaconed_trials)>0:
ax.plot(bin_centres, non_beaconed_stop_hist/len(non_beaconed_trials), '-', color='Red')
#if len(probe_trials)>0:
# ax.plot(bin_centres, probe_stop_hist/len(probe_trials), '-', color='Blue')
plt.ylabel('Per trial', fontsize=25, labelpad = 10)
plt.xlabel('Location (cm)', fontsize=25, labelpad = 10)
plt.xlim(0,track_length)
ax.set_yticks([0, 1])
ax.set_yticklabels(["0", "1"])
ax.xaxis.set_tick_params(labelsize=20)
ax.yaxis.set_tick_params(labelsize=20)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plot_utility.style_track_plot(ax, track_length)
tick_spacing = 100
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.xticks(fontsize=20)
plot_utility.style_vr_plot(ax)
plt.subplots_adjust(hspace = .35, wspace = .35, bottom = 0.2, left = 0.32, right = 0.87, top = 0.92)
plt.savefig(output_path + '/Figures/behaviour/stop_histogram' + '.png', dpi=200)
plt.close()
def get_max_SNR(spatial_frequency, powers):
max_SNR = powers[np.argmax(powers)]
max_SNR_freq = spatial_frequency[np.argmax(powers)]
return max_SNR, max_SNR_freq
def add_displayed_peak_firing(spike_data):
peak_firing = []
for cluster_index, cluster_id in enumerate(spike_data.cluster_id):
cluster_spike_data = spike_data[spike_data["cluster_id"] == cluster_id]
firing_times_cluster = np.array(cluster_spike_data["firing_times"].iloc[0])
if len(firing_times_cluster)>1:
fr_binned_in_space = np.asarray(cluster_spike_data["fr_binned_in_space_smoothed"].iloc[0])
fr_binned_in_space[np.isnan(fr_binned_in_space)] = 0
fr_binned_in_space[np.isinf(fr_binned_in_space)] = 0
peak_firing.append(np.nanpercentile(fr_binned_in_space.flatten(), 99))
else:
peak_firing.append(np.nan)
spike_data["vr_peak_firing"] = peak_firing
return spike_data
def get_rolling_lomb_classifier_for_centre_trial(centre_trials, powers, power_threshold, power_step, track_length, n_window_size=Settings.rolling_window_size_for_lomb_classifier, lomb_frequency_threshold=Settings.lomb_frequency_threshold):
frequency = Settings.frequency
trial_points = []
peak_frequencies = []
rolling_lomb_classifier = []
rolling_lomb_classifier_numeric = []
rolling_lomb_classifier_colors = []
for i in range(len(centre_trials)):
centre_trial = centre_trials[i]
if n_window_size>1:
if i<int(n_window_size/2):
power_window = powers[:i+int(n_window_size/2), :]
elif i+int(n_window_size/2)>len(centre_trials):
power_window = powers[i-int(n_window_size/2):, :]
else:
power_window = powers[i-int(n_window_size/2):i+int(n_window_size/2), :]
avg_power = np.nanmean(power_window, axis=0)
else:
avg_power = powers[i, :]
max_SNR, max_SNR_freq = get_max_SNR(frequency, avg_power)
lomb_classifier = get_lomb_classifier(max_SNR, max_SNR_freq, power_threshold, lomb_frequency_threshold, numeric=False)
peak_frequencies.append(max_SNR_freq)
trial_points.append(centre_trial)
if lomb_classifier == "Position":
rolling_lomb_classifier.append("P")
rolling_lomb_classifier_numeric.append(0.5)
rolling_lomb_classifier_colors.append(Settings.allocentric_color)
elif lomb_classifier == "Distance":
rolling_lomb_classifier.append("D")
rolling_lomb_classifier_numeric.append(1.5)
rolling_lomb_classifier_colors.append(Settings.egocentric_color)
elif lomb_classifier == "Null":
rolling_lomb_classifier.append("N")
rolling_lomb_classifier_numeric.append(2.5)
rolling_lomb_classifier_colors.append(Settings.null_color)
else:
rolling_lomb_classifier.append("U")
rolling_lomb_classifier_numeric.append(3.5)
rolling_lomb_classifier_colors.append("black")
return np.array(rolling_lomb_classifier), np.array(rolling_lomb_classifier_numeric), np.array(rolling_lomb_classifier_colors), np.array(peak_frequencies), np.array(trial_points)
def get_block_lengths_any_code(rolling_lomb_classifier):
block_lengths = []
current_block_length = 0
current_code=rolling_lomb_classifier[0]
for i in range(len(rolling_lomb_classifier)):
if (rolling_lomb_classifier[i] == current_code):
current_block_length+=1
else:
if (current_block_length != 0) and (current_code != "N"):
block_lengths.append(current_block_length)
current_block_length=0
current_code=rolling_lomb_classifier[i]
if (current_block_length != 0) and (current_code != "N"):
block_lengths.append(current_block_length)
block_lengths = np.array(block_lengths)/len(rolling_lomb_classifier) # normalise by length of session
return block_lengths.tolist()
def get_block_lengths(rolling_lomb_classifier, modal_class_char):
block_lengths = []