-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathFunctions.R
More file actions
1767 lines (1472 loc) · 70.3 KB
/
Functions.R
File metadata and controls
1767 lines (1472 loc) · 70.3 KB
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
### This script contains functions which are called in the Analysis markdown code
### Functions here are initially used in Figure 1 code
## Adds positions to a single column data frame that contains a neurons binned mean firing rate
add_position <- function(df, session_id = "", cluster_id = "") {
len = length(unlist(df))
df <- tibble(Rates = unlist(df), Position = rep(1:len))
#if(all(is.na(df$Rates))){print(paste0("All NAs. Session: ", session_id, ". Cluster:", cluster_id))}
df
}
## Fits a linear model to firing rate data contained in df, across the range from startbin to endbin.
# Returns output as a dataframe containing key model parameters extracted with glance and tidy.
lm_tidy_helper <- function(df,
startbin,
endbin) {
# Check for NAs
if (all(is.na(df$Rates))) {
df <-
tibble(
r.squared = c(NA),
p.value = c(NA),
intercept = c(NA),
slope = c(NA)
)
return(df)
}
df <- df %>%
subset(Position >= startbin & Position <= endbin)
df_fit <- lm(Rates ~ Position, data = df, na.action = na.exclude)
# get the model parameters
params <- select(glance(df_fit), r.squared, p.value)
# get the coefficients
coeffs <- tidy(df_fit)
# combine the parameters and coefficients
params$intercept <- coeffs$estimate[[1]]
params$slope <- coeffs$estimate[[2]]
return(params)
}
###Function to generate shuffled datasets from a neuron's mean firing rate profile.
# shuffles defines the number of shuffles. The default value is for testing.
# Use a larger value for analyses, e.g. 1000.
# shuffles spikes using sample() function
# fits lm
# extracts coefficients
# stores coefficients for each 1000 shuffles (less memory than saving 1000 shuffles)
# The id, slope, r2 and p values for each shuffled dataset are returned.
shuffle_rates <- function(df, startbin, endbin, shuffles = 10) {
df_modified <- data.frame(neuron=as.numeric(),
slope=as.numeric(),
rsquared=as.numeric(),
pval=vector())
names(df_modified) <- c("neuron", "slope", "rsquared", "pval")
x <- 0
repeat {
shuff_df <- tibble(Rates = sample(as.vector(unlist(df)),replace = TRUE, prob = NULL), Position = c(1:200))
df_mod <- lm_tidy_helper(shuff_df, startbin, endbin)
data <- data.frame(as.numeric(x), df_mod$slope, df_mod$r.squared, df_mod$p.value)
names(data) <- c("neuron", "slope", "r.squared", "p.value")
df_modified <- rbind(df_modified,data)
x = x+1
if (x == shuffles){
break
}
}
return(df_modified)
}
# Functions to return the slope for a given quantile in the shuffled datasets
extract_quantile_shuffle_slopes <- function(df, q_prob = 0.05){
df <- tibble(slopes = unlist(df$slope), r.squared = unlist(df$r.squared))
if (all(is.na(df$slopes))) {
return(NA)
}
min_slope_o <- quantile(as.numeric(unlist(df$slopes)), c(q_prob))[1]
return(min_slope_o)
}
# To classify neurons based on:
# 1. Whether their slopes are outside the 5-95% range of the shufled data.
# 2. Whether the adjusted p-value of the linear model fit is <= 0.01.
compare_slopes <-
function(min_slope = 1,
max_slope = 1,
slope = 1,
pval = 1) {
if (any(is.na(list(min_slope, max_slope, slope, pval)))) {
return("Unclassified")
}
if (pval > 0.01) {
return("Unclassified")
} else if (slope < min_slope & pval < 0.01) {
return("Negative")
} else if (slope > max_slope & pval < 0.01) {
return("Positive")
} else {
return("Unclassified")
}
}
# Function to normalize firing rates
normalise_rates <- function(df){
df <- tibble(Rates = unlist(df), Position = rep(1:200))
x <- scale(df$Rates, center=TRUE, scale=TRUE)[,1]
return(x)
}
normalise_smooth_rates <- function(df){
df <- tibble(Rates_smoothed = unlist(df), Position = rep(1:200))
x <- scale(df$Rates_smoothed, center=TRUE, scale=TRUE)[,1]
return(x)
}
#C alculates the difference between mean rate and predicted mean rate at the start of the homebound zone
calc_predict_diff <- function(rates, fit)
{
diff <- mean(as.double(rates[110:115])) - mean(as.double(fit[110:115]))
}
#make function to predict firing rate
lm_predict <- function(df){
new.data <- data.frame(Position =df$Position)
}
# Predict mean and confidence intervals for firing rate at the start of the homebound zone (track positions 110 to 115 cm) based on firing in the outbound zone (30 to 90 cm).
predict_homebound <- function(df, fit_start = 30, fit_end = 90){
# check for NAs
if(all(is.na(df)))
return(NA)
# Make track column
df <- tibble(Rates = unlist(df), Position=rep(1:200))
# fit
model <- lm(Rates ~ Position, data = filter(df, Position >= fit_start, Position <= fit_end))
# predict
homebound_prediction_pos <- tibble(Position = rep(1:200))
homebound_prediction <- predict(model, newdata = homebound_prediction_pos, interval = "prediction", level = 0.99)
as_tibble(homebound_prediction)
}
#Test whether data lies outside of confidence intervals
offset_test <- function(rates, lwr, upr, predict_start = 110, predict_end = 115){
# check for NAs
if(all(is.na(rates)))
return(NA)
rates <- mean(as.double(rates[predict_start:predict_end]))
upr <- mean(as.double(upr[predict_start:predict_end]))
lwr <- mean(as.double(lwr[predict_start:predict_end]))
if(rates > upr) {
return("Pos")
}
if (rates <= lwr) {
return("Neg")
}
return("None")
}
# Function to give a text label to cells based on groups
mark_track_category <- function(outbound, homebound){
if( outbound == "Positive" & homebound == "Negative") {
return( "posneg" )
} else if( outbound == "Positive" & homebound == "Positive") {
return( "pospos" )
} else if( outbound == "Negative" & homebound == "Positive") {
return( "negpos" )
} else if( outbound == "Negative" & homebound == "Negative") {
return( "negneg" )
} else if( outbound == "Negative" & homebound == "Unclassified") {
return( "negnon" )
} else if( outbound == "Positive" & homebound == "Unclassified") {
return( "posnon" )
} else {
return("None")
}
}
# Function to give a numeric label to cells based on groups
mark_numeric_track_category <- function(outbound, homebound){
if( outbound == "Positive" & homebound == "Negative") {
return( as.numeric(2) )
} else if( outbound == "Positive" & homebound == "Positive") {
return( as.numeric(1) )
} else if( outbound == "Negative" & homebound == "Positive") {
return( as.numeric(5) )
} else if( outbound == "Negative" & homebound == "Negative") {
return( as.numeric(4) )
} else if( outbound == "Negative" & homebound == "Unclassified") {
return( as.numeric(6) )
} else if( outbound == "Positive" & homebound == "Unclassified") {
return( as.numeric(3) )
} else {
return(as.numeric(0))
}
}
#Function to classify neurons based on offset
mark_reset_group_predict <- function(offset){
if (is.na(offset) ) {
return( "None" )
} else if( offset == "None") {
return( "Continuous" )
} else if( ( offset == "Neg" || offset == "Pos")) {
return( "Reset" )
}
}
# Plot histogram of distribution of firing rate offsets
offset_ggplot <- function(df, diff_colname = "predict_diff", group_colname = "reset_group", colour_1 = "grey", colour_2 = "chartreuse3", colour_3 = "red") {
ggplot(data=df, aes(x = unlist(.data[[diff_colname]]), fill=as.factor(unlist(.data[[group_colname]])))) +
coord_cartesian(xlim=c(-6,6)) +
geom_histogram(aes(y=..count..), alpha=0.5) +
scale_fill_manual(values=c(colour_1, colour_2, colour_3)) +
scale_y_continuous(breaks = scales::pretty_breaks(n = 3)) +
labs(y="Density", x="") +
theme_classic() +
theme(axis.text.x = element_text(size=13),
axis.text.y = element_text(size=13),
legend.position="bottom",
legend.title = element_blank(),
text = element_text(size=13),
legend.text=element_text(size=13),
axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
}
# Plot mean and SEM of firing rate as a function of position.
add_track <- function(gg, xlab = "Location (cm)", ylab = "Stops (cm)") {
gg +
annotate("rect", xmin=-30, xmax=0, ymin=-Inf,ymax=Inf, alpha=0.2, fill="Grey60") +
annotate("rect", xmin=140, xmax=170, ymin=-Inf,ymax=Inf, alpha=0.2, fill="Grey60") +
annotate("rect", xmin=60, xmax=80, ymin=-Inf,ymax=Inf, alpha=0.2, fill="Chartreuse4") +
scale_x_continuous(breaks=seq(-30,170,100), expand = c(0, 0)) +
scale_y_continuous(breaks = integer_breaks()) +
labs(y = ylab, x = xlab) +
theme_classic() +
theme(axis.text.x = element_text(size=18),
axis.text.y = element_text(size=18),
legend.title = element_blank(),
text = element_text(size=18),
plot.margin = margin(21, 25, 5, 20))
}
mean_SEM_plots_prep <- function(df) {
df <- df %>% dplyr::summarise(mean_r = mean(Rates, na.rm = TRUE),
sem_r = std.error(Rates, na.rm = TRUE))
}
mean_SEM_plots <- function(df, colour1 = "blue"){
gg <- ggplot(data=df) +
geom_ribbon(aes(x=Position, y=mean_r, ymin = mean_r - sem_r, ymax = mean_r + sem_r), fill = colour1, alpha=0.2) +
geom_line(aes(y=mean_r, x=Position), color = colour1)
add_track(gg, xlab = "Location (cm)", ylab = "Z-scored firing rate")
}
## --------------------------------------------------------------------------------------------- ##
# Load circular shuffled data from Python.
# this function will take load shuffles for a single trial type, e.g. beaconed outbound
# The input dataframe is the
local_circ_shuffles <- function(df_in, cs_path) {
shuffled_df <- read_feather(cs_path)
# get list of cells based on session id + cluster id
# add unique id for each cell to both data frames
shuffled_df$unique_cell_id <- paste(shuffled_df$session_id, shuffled_df$cluster_id)
unique_cells = unique(shuffled_df[c("unique_cell_id")])
number_of_cells = nrow(unique_cells)
print('Number of cells in spike-level shuffle data:')
print(number_of_cells)
# Provides a reference for cell IDs in the experimental data
unique_cell_ids <- paste(df_in$session_id, df_in$cluster_id)
shuffled_df <- shuffled_df %>%
group_by(unique_cell_id) %>%
nest()
# select shuffled data that matches the experimental data
shuffled_df_select <- shuffled_df[shuffled_df$unique_cell_id %in% unique_cell_ids, ]
shuffled_df_select <- unnest(shuffled_df_select, cols = c(data))
# reformat shuffled data
shuffled_b <- shuffled_df_select %>%
select(unique_cell_id, shuffle_id, beaconed_r2_ob, beaconed_slope_ob, beaconed_p_val_ob) %>%
rename(neuron = "shuffle_id", slope = "beaconed_slope_ob", r.squared = "beaconed_r2_ob", p.value = "beaconed_p_val_ob") %>%
group_by(unique_cell_id) %>%
nest()
shuffled_nb <- shuffled_df_select %>%
select(unique_cell_id, shuffle_id, non_beaconed_r2_ob, non_beaconed_slope_ob, non_beaconed_p_val_ob) %>%
rename(neuron = "shuffle_id", slope = "non_beaconed_slope_ob", r.squared = "non_beaconed_r2_ob", p.value = "non_beaconed_p_val_ob") %>%
group_by(unique_cell_id) %>%
nest()
shuffled_p <- shuffled_df_select %>%
select(unique_cell_id, shuffle_id, probe_r2_ob, probe_slope_ob, probe_p_val_ob) %>%
rename(neuron = "shuffle_id", slope = "probe_slope_ob", r.squared = "probe_r2_ob", p.value = "probe_p_val_ob") %>%
group_by(unique_cell_id) %>%
nest()
shuffled_b_h <- shuffled_df_select %>%
select(unique_cell_id, shuffle_id, beaconed_r2_hb, beaconed_slope_hb, beaconed_p_val_hb) %>%
rename(neuron = "shuffle_id", slope = "beaconed_slope_hb", r.squared = "beaconed_r2_hb", p.value = "beaconed_p_val_hb") %>%
group_by(unique_cell_id) %>%
nest()
shuffled_nb_h <- shuffled_df_select %>%
select(unique_cell_id, shuffle_id, non_beaconed_r2_hb, non_beaconed_slope_hb, non_beaconed_p_val_hb) %>%
rename(neuron = "shuffle_id", slope = "non_beaconed_slope_hb", r.squared = "non_beaconed_r2_hb", p.value = "non_beaconed_p_val_hb") %>%
group_by(unique_cell_id) %>%
nest()
shuffled_p_h <- shuffled_df_select %>%
select(unique_cell_id, shuffle_id, probe_r2_hb, probe_slope_hb, probe_p_val_hb) %>%
rename(neuron = "shuffle_id", slope = "probe_slope_hb", r.squared = "probe_r2_hb", p.value = "probe_p_val_hb") %>%
group_by(unique_cell_id) %>%
nest()
df <- tibble(unique_cell_id = shuffled_b$unique_cell_id,
shuffle_results_b_o = shuffled_b$data,
shuffled_results_nb_o = shuffled_nb$data,
shuffled_results_p_o = shuffled_p$data,
shuffle_results_b_h = shuffled_b_h$data,
shuffled_results_nb_h = shuffled_nb_h$data,
shuffled_results_p_h = shuffled_p_h$data)
return(df)
}
## ----------------------------------------------------------##
### Functions below here are initially used in Figure 2 code.
# Function to fit general linear mixed effect models
# The goal here is to evaluate influences of position, speed and acceleration on firing rate.
# This is set up with family = poisson as the data binned in time are counts.
# For use with smoothed data would need to change this to gamma (which won't work where there are zeros)
# Or consider using Tweedie family implemented in the glmBB package.
# Note also that we get similar results using linear mixed effect models so GLMER while more 'correct' may not be necessary.
# TT is trial type. Codes used in the spatial_firing$spikes_in_time are 0 (beaconed), 1 (non-beaconed) and 2 (probe).
# thresh is the minimum number of trials required for fitting the data.
mm_fit <- function(df, TT = 0, thresh = 20) {
if (length(df) == 1){
return(NA)}
df <-
tibble(
Rates = as.numeric(df[[1]]),
Position = as.numeric(df[[2]]),
Acceleration = as.numeric(df[[4]]),
Speed = as.numeric(df[[3]]),
Trials = as.factor(df[[5]]),
Types = as.factor(df[[6]])
)
print(nrow(df))
# subset by position, speed, types (beaconed/probe) and remove rates < 0.01 as model does not like this
df <- df %>%
subset(Position >= 30 & Position <= 90 & Speed >= 3 & Types == TT) %>%
select(-Types)
#scale variables, do not center or values go below 0 which does not work for this gamma model
df$Acceleration <- scale(df$Acceleration, center=FALSE, scale=TRUE)
df$Rates <- scale(df$Rates, center=FALSE, scale=TRUE)
df$Speed <- scale(df$Speed, center=FALSE, scale=TRUE)
df$Position <- scale(df$Position, center=FALSE, scale=TRUE)
if (length(df) == 1 | nrow(df) < thresh) {
return(NA)
}
# return NA if variables contain any NAs after scaling (very possible if cell doesn't spike on rewarded trials)
if (sum(is.na(as.matrix(df))) > 0) {
return(NA)
}
df_int <- lme4::glmer(formula = Rates ~ Position + Speed + Acceleration + (1 + Position | Trials),
data = df,
na.action = na.exclude,
family = poisson(link = "log"),
control=lme4::glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
}
# Function to extract P values for each coefficient from the model
mm_function <- function(mm, session_id) {
if (is.na(mm)) {
return(tibble(pos = NA, speed = NA, accel = NA))
}
modelAnova <- car::Anova(mm)
return_tibble <- tibble(pos = modelAnova$"Pr(>Chisq)"[[1]],
speed = modelAnova$"Pr(>Chisq)"[[2]],
accel = modelAnova$"Pr(>Chisq)"[[3]])
}
# Helper function for extracting P values for each coefficient from the model
mm_pvalues <- function(mm, session_id) {
tryCatch({
mm_function(mm, session_id)
},
error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
# Helper function to link to general linear mixed model fit
mm_fit_function <- function(mm, TT = 0, thresh = 20) {
tryCatch({
mm_fit(mm,TT, thresh)
},
error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
## Categorize neurons based on significant model coefficients
coef_comparison <- function(null_pos, null_speed, null_accel, pval = 0.01){
if(is.na(null_pos)) {
return("None")
} else if( null_pos < pval & null_accel > pval & null_speed > pval) {
return( "P" )
} else if( null_pos > pval & null_accel > pval & null_speed < pval) {
return( "S" )
} else if( null_pos > pval & null_accel < pval & null_speed > pval) {
return( "A" )
} else if( null_pos < pval & null_accel > pval & null_speed < pval) {
return("PS")
} else if( null_pos < pval & null_accel < pval & null_speed > pval) {
return( "PA" )
} else if( null_pos > pval & null_accel < pval & null_speed < pval) {
return("SA")
} else if( null_pos < pval & null_accel < pval & null_speed < pval) {
return("PSA")
} else {
return("None")
}
}
# Function to calculate standardized coefficients for a LMER
#https://stackoverflow.com/questions/25142901/standardized-coefficients-for-lmer-model
stdCoef.merMod <- function(object) {
sdy <- sd(getME(object,"y"))
sdx <- apply(getME(object,"X"), 2, sd)
sc <- fixef(object)*sdx/sdy
se.fixef <- coef(summary(object))[,"Std. Error"]
se <- se.fixef*sdx/sdy
return(data.frame(stdcoef=sc, stdse=se))
}
# Helperfunction to calculate standardized coefficients from the model fits
std_coef <- function(mm) {
tryCatch({
mod <- stdCoef.merMod(mm)
mod_coefs <- tibble(pos = mod[2,1],
speed = mod[3,1],
accel = mod[4,1])
},
error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
# Extracts counts for numbers of neurons sorted according to the classification from the GLMER fit
make_coeffs_table <- function(df) {
df <- df %>%
unlist() %>%
table() %>%
as_tibble() %>%
mutate(perc = (n / sum(n)) * 100)
colnames(df) <- c("ramp_id", "num", "perc")
df
}
# Function for plotting standardised coefficients
# df should contain columns with coef_type and coef
# These columns are generated as outputs after GLMER fits
# For Figure 2 these columns are in spatial_firing_coefs.
# This data frame was generated by unnesting spatial_firing.
standard_plot <- function(df) {
level_order <- c("P", "S", "A")
ggplot(data=df, aes(x = factor(coef_type), y = as.numeric(coef))) +
geom_violin(aes(x = factor(coef_type), y = as.numeric(coef), fill=factor(coef_type, level=level_order)), alpha=0.7) +
stat_summary(fun=mean, geom="point", shape=23, size=2) +
geom_jitter(alpha=0.05) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
scale_fill_manual(values=c("firebrick1","gold","dodgerblue2")) +
labs(y = "std coef", x="\n model parameter") +
scale_y_continuous(trans=pseudolog10_trans) +
theme_classic() +
theme(axis.text.x = element_text(size=14),
axis.text.y = element_text(size=12),
legend.position="bottom",
legend.title = element_blank(),
text = element_text(size=12),
legend.text=element_text(size=12),
axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
}
## ----------------------------------------------------------##
### Functions below here are initially used in Figure 3 code.
# A function that extracts into a tibble data from spatial_firing$spikes_in_time_reward_hit/run/try
extract_to_tibble <- function(df) {
df <-
tibble(
Rates = as.numeric(Re(df[[1]])),
Position = as.numeric(Re(df[[3]])),
Trials = as.numeric(Re(df[[4]]))
)
return (df)
}
# Function to join firing rates from different trial types and add indicator of the type of trial
# The trial types are:
# spatial_firing$spikes_in_time_reward_hit
# spikes_in_time_reward_run
# spikes_in_time_reward_try
join_rates <- function(hit, run, try, session_id, cluster_id) {
if (any(is.na(hit)) | any(is.na(run)) | any(is.na(try))) {
return(NA)
}
hit_df <- extract_to_tibble(hit)
run_df <- extract_to_tibble(run)
try_df <- extract_to_tibble(try)
df <- tibble(Rates = c(hit_df$Rates,
run_df$Rates,
try_df$Rates),
Reward_indicator = c(rep("Rewarded", times=nrow(hit_df)),
rep("Run", times=nrow(run_df)),
rep("Try", times=nrow(try_df))),
Position = c(hit_df$Position,
run_df$Position,
try_df$Position),
Trials = c(hit_df$Trials,
run_df$Trials,
try_df$Trials))
return (df)
}
# Function to fit a linear mixed effect model that takes trial type (hit, try, run) into account
# The car package is used to extract slope significance
compare_models_slope_lm <- function(df, run, try){
tryCatch({
if (any(is.na(run)) | any(is.na(try)) | any(is.na(df))) {
return("Contains NAs")
}
if (length(df) == 1 | nrow(df) < 6)
return("Too small")
df <- df %>%
filter(Position >= 30, Position <= 90) %>%
mutate(Rates = scale(Rates)) # This doesn't seem to make any substantial difference
fit <- lme4::lmer(Rates ~ scale(Position) * Reward_indicator + (1+scale(Position) | Trials), data = df, na.action=na.omit)
modelAnova <- car::Anova(fit)
to_return <- modelAnova$"Pr(>Chisq)"[[3]]
},
error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
# Function to fit a general linear mixed effect model that takes trial type (hit, try, run) into account
# This is set up with family = poisson as the data binned in time are counts.
# For use with smoothed data would need to change this to gamma (which won't work where there are zeros)
# Or consider using Tweedie family implemented in the glmBB package.
# Note also that we get similar results using linear mixed effect models so GLMER while more 'correct' may not be necessary.
# The car package is used to extract slope significance
compare_models_slope_glm <- function(df, run,try){
tryCatch({
if (any(is.na(run)) | any(is.na(try)) | any(is.na(df))) {
return("Contains NAs")
}
if (length(df) == 1 | nrow(df) < 6)
return("Too small")
df <- df %>%
filter(Position >= 30, Position <= 90)
glm1 <- glm(Rates ~ Position * Reward_Indicator , family = poisson(link = "log"), data = df)
fit <- lme4::glmer(formula = Rates ~ Position * Reward_indicator + (1 + Position | Trials),
data = df,
na.action = na.exclude,
family = poisson(link = "log"),
start=list(fixef=coef(glm1)),
control=glmerControl(optimizer="bobyqa",optCtrl=list(maxfun=2e5)))
modelAnova <- car::Anova(fit)
to_return <- modelAnova$"Pr(>Chisq)"[[3]]
},
error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
# Function to classify neurons based on whether there is a significant effect of trial outcome
mark_neurons_sig <- function(pval){
tryCatch({
if (is.na(pval)) {
return(NA)
}
if (pval == "NULL") {
return(NA)
}
if( pval < 0.01) {
return( "Significant" )
} else if( pval >= 0.01) {
return( "Not-Significant" )
} else {
return("None")
}
},
error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
# Function to join average firing rates from different trial types, normalize the rates and add indicator of the type of trial
join_average_rates <- function(hit, run, try, session_id, cluster_id) {
if (any(is.na(hit)) | any(is.na(run)) | any(is.na(try))) {
return(
df <- tibble(Rates = rep(NA, times=600),
Position = rep(NA, times=600),
Reward_indicator = c(rep("Rewarded", times=200), rep("Run Through", times=200), rep("Try", times=200)))
)
}
df <- tibble(Rates = c(unlist(hit), unlist(run), unlist(try)),
Position = c(rep(-30:169), rep(-30:169), rep(-30:169)),
Reward_indicator = c(rep("Rewarded", times=200), rep("Run Through", times=200), rep("Try", times=200)))
df$Rates <- scale(df$Rates, center=TRUE, scale=TRUE)[,1]
return (df)
}
# Generic function to subset data ready for plotting with mean_SEM_plots_by_Outcome
# Note the unnest() is only carried out if there is data.
subset_for_plots <- function(df, outbound_class = "Positive", homebound_class = "Positive") {
df <- df %>%
filter(lm_group_b == outbound_class,
lm_group_b_h == homebound_class) %>%
select(avg_both_asr_b) %>%
when(nrow(.) != 0 ~ unnest(., c(avg_both_asr_b))
)
}
integer_breaks <- function(n = 5, ...) {
fxn <- function(x) {
breaks <- floor(pretty(x, n, ...))
names(breaks) <- attr(breaks, "labels")
breaks
}
return(fxn)
}
# Generic function to plot firing rate ± SEM as a function of position and colour coded according to trial outcome.
# The function expects to receive the unnested mean firing rates for all neurons that are to be plotted.
# Conditions for selection should be given before calling the function.
# Column names of the input data frame should be 'Rates', 'Position' and 'Reward_indicator'.
mean_SEM_plots_by_Outcome <- function(df, x_start = -30, x_end = 170) {
# Check for data
if(is.null(df) == TRUE) {return(
ggplot() + theme_void())
}
# check for all NAs
if (sum(is.na(df$Rates)) == dim(df)[[1]]) {
return(ggplot() + theme_void())
}
# Carry on
df <- df %>%
group_by(Position, Reward_indicator) %>%
dplyr::summarise(mean_b = mean(Rates, na.rm = TRUE),
se_b = std.error(Rates, na.rm = TRUE))
ggplot(data=df) +
annotate("rect", xmin=-30, xmax=0, ymin=-Inf,ymax=Inf, alpha=0.2, fill="Grey60") +
annotate("rect", xmin=140, xmax=170, ymin=-Inf,ymax=Inf, alpha=0.2, fill="Grey60") +
annotate("rect", xmin=60, xmax=80, ymin=-Inf,ymax=Inf, alpha=0.2, fill="Chartreuse4") +
scale_x_continuous(breaks=seq(-30,170,100), expand = c(0, 0)) +
scale_y_continuous(breaks = integer_breaks()) +
geom_ribbon(aes(x=Position, y=mean_b, ymin = mean_b - se_b, ymax = mean_b + se_b,
fill=factor(Reward_indicator)), alpha=0.2) +
geom_line(aes(y=mean_b, x=Position, color=factor(Reward_indicator)), alpha=1) +
scale_fill_manual(values=c("black", "red", "blue")) +
scale_color_manual(values=c("black", "red", "blue")) +
labs(y = "Z-scored firing rate", x = "Location (cm)") +
theme_classic() +
theme(axis.text.x = element_text(size=18),
axis.text.y = element_text(size=18),
legend.position = "none",
legend.title = element_blank(),
text = element_text(size=18),
plot.margin = margin(21, 25, 5, 20))
}
# Function to generate plots by trial outome for each class of ramping neurons
# Also returns the number of neurons that contribute to each plot
# Calculation of number of neurons without NAs is somewhat improvised
# This could be modified by including neuron ID, etc.
all_plots_by_outome <- function(df) {
NegNegNeurons <- df %>%
subset_for_plots("Negative", "Negative")
NegNeg_plot <- NegNegNeurons %>%
mean_SEM_plots_by_Outcome(-29,169)
NegNeg_N <- sum(!is.na(NegNegNeurons$Rates))/600 # Relies on their being 200 x 3 location points
NegPosNeurons <- df %>%
subset_for_plots("Negative", "Positive")
NegPos_plot <- NegPosNeurons %>%
mean_SEM_plots_by_Outcome(-29,169)
NegPos_N <- sum(!is.na(NegPosNeurons$Rates))/600
PosPosNeurons <- df %>%
subset_for_plots("Positive", "Positive")
PosPos_plot <- PosPosNeurons %>%
mean_SEM_plots_by_Outcome(-29,169)
PosPos_N <- sum(!is.na(PosPosNeurons$Rates))/600
PosNegNeurons <- df %>%
subset_for_plots("Positive", "Negative")
PosNeg_plot <- PosNegNeurons %>%
mean_SEM_plots_by_Outcome(-29,169)
PosNeg_N <- sum(!is.na(PosNegNeurons$Rates))/600
return(list(list(NegNeg_plot, NegPos_plot, PosPos_plot, PosNeg_plot),
list(NegNeg_N, NegPos_N, PosPos_N, PosNeg_N)))
}
# sum(sapply(speed_neurons$avg_both_asr_b, anyNA))
# Function to plot slopes as a function of trial outcome
slopes_by_outcome <- function(df, min_y = -3.5, max_y = 3.5){
df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, asr_b_o_rewarded_fit_slope, asr_b_try_fit_slope, asr_b_run_fit_slope) %>%
rename(Hit = asr_b_o_rewarded_fit_slope,
Try = asr_b_try_fit_slope,
Run = asr_b_run_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", ) %>%
ggplot(aes(x = fct_relevel(Outcome, "Hit", "Try", "Run"), y = Slope)) +
coord_cartesian(ylim=c(min_y,max_y)) +
geom_point() +
geom_line(aes(group = unique_id, alpha = 0.5)) +
geom_violin(aes(alpha = 0.5, fill = fct_relevel(Outcome, "Hit", "Try", "Run"))) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
labs(x = "Outcome", y = "Pre-reward zone slope") +
scale_fill_manual(values=c("grey","red", "blue")) +
theme_classic() +
theme(text = element_text(size=20),
legend.position = "none")
}
h_slopes_by_outcome <- function(df, min_y = -3.5, max_y = 3.5){
df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, asr_b_h_hit_fit_slope, asr_b_h_try_fit_slope, asr_b_h_run_fit_slope) %>%
rename(Hit = asr_b_h_hit_fit_slope,
Try = asr_b_h_try_fit_slope,
Run = asr_b_h_run_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", ) %>%
ggplot(aes(x = fct_relevel(Outcome, "Hit", "Try", "Run"), y = Slope)) +
coord_cartesian(ylim=c(min_y,max_y)) +
geom_point() +
geom_line(aes(group = unique_id, alpha = 0.5)) +
geom_violin(aes(alpha = 0.5, fill = fct_relevel(Outcome, "Hit", "Try", "Run"))) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
labs(x = "Outcome", y = "Post-reward zone slope") +
scale_fill_manual(values=c("grey","red", "blue")) +
theme_classic() +
theme(text = element_text(size=20),
legend.position = "none")
}
# Function to plot offsets as a function of trial outcome
offsets_by_outcome <- function(df, min_y = -3.5, max_y = 3.5){
df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, predict_diff_hit, predict_diff_try, predict_diff_run) %>%
rename(Hit = predict_diff_hit,
Try = predict_diff_try,
Run = predict_diff_run) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", ) %>%
ggplot(aes(x = fct_relevel(Outcome, "Hit", "Try", "Run"), y = Slope)) +
coord_cartesian(ylim=c(min_y,max_y)) +
geom_point() +
geom_line(aes(group = unique_id, alpha = 0.5)) +
geom_violin(aes(alpha = 0.5, fill = fct_relevel(Outcome, "Hit", "Try", "Run"))) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
labs(x = "Outcome", y = "Offset") +
scale_fill_manual(values=c("grey","red", "blue")) +
theme_classic() +
theme(text = element_text(size=20),
legend.position = "none")
}
# One-way ANOVA to compare slopes by outcome
slopes_by_outcome_aov <- function(df) {
df <- df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, asr_b_o_rewarded_fit_slope, asr_b_try_fit_slope, asr_b_run_fit_slope) %>%
rename(Hit = asr_b_o_rewarded_fit_slope,
Try = asr_b_try_fit_slope,
Run = asr_b_run_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", )
#aov(Slope ~ as.factor(Outcome), data = df)
aov(Slope ~ as.factor(Outcome) + Error(as.factor(unique_id)), data = df)
#aov_2(df)
}
h_slopes_by_outcome_aov <- function(df) {
df <- df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, asr_b_h_hit_fit_slope, asr_b_h_try_fit_slope, asr_b_h_run_fit_slope) %>%
rename(Hit = asr_b_h_hit_fit_slope,
Try = asr_b_h_try_fit_slope,
Run = asr_b_h_run_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", )
#aov(Slope ~ as.factor(Outcome), data = df)
aov(Slope ~ as.factor(Outcome) + Error(as.factor(unique_id)), data = df)
#aov_2(df)
}
# To check AOV because F value was suspiciously low.
aov_2 <- function(df){
CF = (sum(df$Slope))^2/length(df$Slope)
total.ss = sum(df$Slope^2)-CF
between.ss = (sum(df$Slope[df$Outcome=="Try"])^2)/length(df$Slope[df$Outcome=="Try"]) +
(sum(df$Slope[df$Outcome=="Run"])^2)/length(df$Slope[df$Outcome=="Run"]) +
(sum(df$Slope[df$Outcome=="Hit"])^2)/length(df$Slope[df$Outcome=="Hit"]) - CF
within.ss = total.ss - between.ss
df.total = length(df$Slope) - 1
df.between = length(unique(df$Outcome)) - 1
df.within = df.total - df.between
between.ms = between.ss/df.between
within.ms = within.ss/df.within
F.value = between.ms/within.ms
list(CF, total.ss, between.ss, within.ss, df.total, df.between, df.within, between.ms, within.ms, F.value)
}
# One sample t-tests for slopes
slopes_by_outcome_t <- function(df) {
df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, asr_b_o_rewarded_fit_slope, asr_b_try_fit_slope, asr_b_run_fit_slope) %>%
rename(Hit = asr_b_o_rewarded_fit_slope,
Try = asr_b_try_fit_slope,
Run = asr_b_run_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", ) %>%
group_by(Outcome) %>%
summarise(ttest = list(t.test(Slope, mu = 0)$p.value)) %>%
unnest(cols = c(ttest))
}
h_slopes_by_outcome_t <- function(df) {
df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, asr_b_h_hit_fit_slope, asr_b_h_try_fit_slope, asr_b_h_run_fit_slope) %>%
rename(Hit = asr_b_h_hit_fit_slope,
Try = asr_b_h_try_fit_slope,
Run = asr_b_h_run_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Slope", ) %>%
group_by(Outcome) %>%
summarise(ttest = list(t.test(Slope, mu = 0)$p.value)) %>%
unnest(cols = c(ttest))
}
# One-way ANOVA to compare offsets by outcome
offsets_by_outcome_aov <- function(df) {
df <- df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, predict_diff_hit, predict_diff_try, predict_diff_run) %>%
rename(Hit = predict_diff_hit,
Try = predict_diff_try,
Run = predict_diff_run) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Offset", )
aov <- aov(Offset ~ as.factor(Outcome) + Error(as.factor(unique_id)), data = df)
}
# One sample t tests for offsets
offsets_by_outcome_t <- function(df) {
df[!(sapply(df$Avg_FiringRate_TryTrials, anyNA) | sapply(df$Avg_FiringRate_RunTrials, anyNA)),] %>% filter(lm_group_b == "Positive" | lm_group_b == "Negative") %>%
select(unique_id, predict_diff_hit, predict_diff_try, predict_diff_run) %>%
rename(Hit = predict_diff_hit,
Try = predict_diff_try,
Run = predict_diff_run) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Hit, Try, Run), names_to = "Outcome", values_to = "Offset", ) %>%
group_by(Outcome) %>%
summarise(ttest = list(t.test(Offset, mu = 0)$p.value)) %>%
unnest(cols = c(ttest))
}
# -------------------------------------------------------------------------------- #
# Functions below here are initially in Figure 4 code.
# To compare slopes on beaconed and probe trials
probe_out_slope_plot <- function(df, group = "Positive", min_y = -0.1, max_y = 0.45) {
df %>%
filter(final_model_o_b == "P" | final_model_o_b == "PS" | final_model_o_b == "PA" | final_model_o_b == "PSA",
lm_group_b == group) %>%
select(unique_id, asr_b_o_rewarded_fit_slope, asr_p_o_rewarded_fit_slope) %>%
rename(Beaconed = asr_b_o_rewarded_fit_slope,
Probe = asr_p_o_rewarded_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Beaconed, Probe), names_to = "Trial", values_to = "Slope", ) %>%
ggplot(aes(x = fct_relevel(Trial, "Beaconed", "Probe"), y = Slope)) +
coord_cartesian(ylim=c(min_y,max_y)) +
geom_point() +
geom_line(aes(group = unique_id, alpha = 0.5)) +
geom_violin(aes(alpha = 0.5, fill = fct_relevel(Trial, "Beaconed", "Probe"))) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
labs(x = "Trial", y = "Slope") +
scale_fill_manual(values=c("black", "#1FB5B2")) +
theme_classic() +
theme(text = element_text(size=20),
legend.position = "none")
}
probe_home_slope_plot <- function(df, group = "Positive", min_y = -0.1, max_y = 0.45) {
df %>%
filter(final_model_o_b == "P" | final_model_o_b == "PS" | final_model_o_b == "PA" | final_model_o_b == "PSA",
lm_group_b == group) %>%
select(unique_id, asr_b_h_rewarded_fit_slope, asr_p_h_rewarded_fit_slope) %>%
rename(Beaconed = asr_b_h_rewarded_fit_slope,
Probe = asr_p_h_rewarded_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Beaconed, Probe), names_to = "Trial", values_to = "Slope", ) %>%
ggplot(aes(x = fct_relevel(Trial, "Beaconed", "Probe"), y = Slope)) +
coord_cartesian(ylim=c(min_y,max_y)) +
geom_point() +
geom_line(aes(group = unique_id, alpha = 0.5)) +
geom_violin(aes(alpha = 0.5, fill = fct_relevel(Trial, "Beaconed", "Probe"))) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
labs(x = "Trial", y = "Slope") +
scale_fill_manual(values=c("black", "#1FB5B2")) +
theme_classic() +
theme(text = element_text(size=20),
legend.position = "none")
}
# To compare outbound slopes on beaconed, non-beaconed and probe trials.
nb_probe_out_slope_plot <- function(df, group = "Positive", min_y = -0.1, max_y = 0.45) {
df %>%
filter(final_model_o_b == "P" | final_model_o_b == "PS" | final_model_o_b == "PA" | final_model_o_b == "PSA",
lm_group_b == group) %>%
select(unique_id, asr_b_o_rewarded_fit_slope, asr_nb_o_rewarded_fit_slope, asr_p_o_rewarded_fit_slope) %>%
rename(Beaconed = asr_b_o_rewarded_fit_slope,
Nonbeaconed = asr_nb_o_rewarded_fit_slope,
Probe = asr_p_o_rewarded_fit_slope) %>%
mutate(unique_id = unlist(unique_id)) %>%
pivot_longer(cols = c(Beaconed, Nonbeaconed,Probe), names_to = "Trial", values_to = "Slope", ) %>%
ggplot(aes(x = fct_relevel(Trial, "Beaconed", "Nonbeaconed", "Probe"), y = Slope)) +
coord_cartesian(ylim=c(min_y,max_y)) +
geom_point() +
geom_line(aes(group = unique_id, alpha = 0.5)) +
geom_violin(aes(alpha = 0.5, fill = fct_relevel(Trial, "Beaconed", "Nonbeaconed", "Probe"))) +
geom_hline(yintercept=0, linetype="dashed", color = "black") +
labs(x = "Trial", y = "Slope") +
scale_fill_manual(values=c("violetred2", "chartreuse3", "grey")) +
theme_classic() +
theme(text = element_text(size=20),
legend.position = "none")