-
Notifications
You must be signed in to change notification settings - Fork 0
/
HPsubfield_eco.Rmd
2239 lines (1843 loc) · 85.8 KB
/
HPsubfield_eco.Rmd
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
---
title: "Ecological Correlates of Hippocampal Subfield Volumes Across Primates"
author: |
| Brian M. Schilder, Bioinformatician II
| Raj Lab
| Department of Neuroscience
| Icahn School of Medicine at Mount Sinai
| NYC, New York
date: "4/29/2017"
output:
rmarkdown::html_document:
theme: yeti
highlight: zenburn
code_folding: show
toc: true
toc_float: true
smooth_scroll: true
number_sections: false
editor_options:
chunk_output_type: console
---
# Setup
Read comments in the setup section below for directions on install additional dependencies.
```{r setup, warning=F, message=F, include=T, dpi = 600}
setwd("~/Desktop/Hippo_Eco/")
library(readxl)
library(dplyr)
library(pander)
library(reshape2)
library(shiny)
library(DT)
library(ggplot2) #devtools::install_github('cran/ggplot2')
library(gplots)
library(corrplot)
library(ggdendro)
library(ggrepel)
library(ggbiplot) #devtools::install_github("vqv/ggbiplot")
library(gridExtra)
library(grid)
library(cowplot)
library(plotly)
library(heatmaply)
library(tidyverse)
# library(xlss) # For xlss, must first download JDK: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html
library(ggtree)# BiocManager::install("ggtree")
library(ggimage)
library(ggstance)
library(phytools)
library(caper)
library(ape)
library(dispRity)
# install.packages("https://cran.r-project.org/src/contrib/Archive/genlasso/genlasso_1.3.tar.gz", repos=NULL, method="libcurl")
# devtools::install_github("khabbazian/l1ou")
library(l1ou)
# For interactive 3D plotting
library(knitr)
library(rgl) # Macs need to download X11 first. Link here: http://xquartz.macosforge.org/trac/wiki
knitr::knit_hooks$set(webgl = hook_webgl)
knitr::opts_chunk$set(echo=T, warning=F, message=F)
# thm <- knitr::knit_theme$get("solarized-dark")
# knitr::knit_theme$set(thm)
sessionInfo()
```
# Import Data
```{r Import Data}
#### LOAD PREVIOUSLY COMPUTED RESULTS #### #### #### #### #### ####
# load("~/Desktop/Hippo_Eco/Data/HippoEco_AllResults.RData")
#### #### #### #### #### #### #### #### #### #### #### #### ####
# Frahm HP-subfield data (1982) + Barger whole-HP & brain (2015) + Pantheria eco + ATWP eco
HP_orig <- as.data.frame(read_excel("Data/Frahm_HPsub_eco.xlsx", sheet = "Final_Data", na = "NA"))
## Designate groups
HP_orig$Genus <- gsub("_.*","",HP_orig$Species_10K)
HP_orig$Clade <-
ifelse(grepl("Homo", HP_orig$Genus), "Homo sapiens",
ifelse(grepl("Gorilla|Hylobates|Pan", HP_orig$Genus), "Apes",
ifelse(grepl("Cercopithecus|Erythrocebus|Lophocebus|Miopithecus|Nasalis|Papio|Piliocolobus|Pygathrix", HP_orig$Genus), "Old World Monkeys",
ifelse(grepl("Alouatta|Aotus|Ateles|Callicebus|Callimico|Callithrix|Cebus|Lagothrix|Pithecia|Saguinus|Saimiri", HP_orig$Genus), "New World Monkeys",
ifelse(grepl("Tarsius", HP_orig$Genus), "Tarsiiformes",
ifelse(grepl("Avahi|Cheirogaleus|Eulemur|Indri|Lepilemur|Microcebus|Propithecus|Varecia|Galago|Galagoides|Loris|Nycticebus|Otolemur|Perodicticus|Daubentonia", HP_orig$Genus), "Strepsirrhines",
"NA"))))))
# Order Clade for plots
orderedClades <- c("Homo sapiens","Apes","Old World Monkeys","New World Monkeys","Tarsiiformes","Strepsirrhines")
HP_orig$Clade <- factor(HP_orig$Clade, labels=orderedClades, levels=orderedClades, ordered=T)
# Rename some variables
HP_orig <- HP_orig %>% dplyr::rename(retroHP=HippocampusRetro,
FD=FasciaDentata,
Sub=Subiculum,
Fibers=HP_HS_fibers,
Body_Size=Body,
# "EC*"=Schizocortex,
EC=Schizocortex,
Diet_Breadth = DietBreadth,
Group_Size = GroupSize_filled,
Home_Range = HR_filled,)
# Log Neuroanatomical vars
#cols <- c("Body_Size","BrainVol","retroHP","FD","Hilus","CA3","CA2","CA1","Sub")
#HP_orig[cols] <- log(HP_orig[cols])
# Log Eco vars
# HP_orig$PopulationDensity_n_km2 <- scales::rescale(log(HP_orig$PopulationDensity_n_km2),c(1,10))
# HP_orig$GroupSize_filled <- scales::rescale(log(HP_orig$GroupSize_filled),c(1,10))
# HP_orig$Home_Range <- scales::rescale(log(HP_orig$Home_Range),c(1,10))
# Add combined regions as variables
HP_orig$retroHP.EC <- HP_orig$retroHP + HP_orig$EC
HP_orig$DG <- HP_orig$FD + HP_orig$Hilus
HP_orig$CA2.3 <- HP_orig$CA2 + HP_orig$CA3
# Correct units of Barger (2015) data
HP_orig[,c("BrainVol","HPvol")] <- HP_orig[,c("BrainVol","HPvol")] * 1000
# Create retoHP minus each subregion
HP_orig$Body__Brain <- HP_orig$Body_Size - HP_orig$BrainMass
HP_orig$Brain__HP <- HP_orig$BrainVol - HP_orig$retroHP
HP_orig$Brain__EC <- HP_orig$BrainVol - HP_orig$EC
HP_orig$Brain__Fib <- HP_orig$BrainVol - HP_orig$Fibers
HP_orig$retroHP__DG <- HP_orig$retroHP - HP_orig$DG
HP_orig$retroHP__FD <- HP_orig$retroHP - HP_orig$FD
HP_orig$retroHP__Hil <- HP_orig$retroHP - HP_orig$Hilus
HP_orig$retroHP__CA2.3 <- HP_orig$retroHP - HP_orig$CA2.3
HP_orig$retroHP__CA3 <- HP_orig$retroHP - HP_orig$CA3
HP_orig$retroHP__CA2 <- HP_orig$retroHP - HP_orig$CA2
HP_orig$retroHP__CA1 <- HP_orig$retroHP - HP_orig$CA1
HP_orig$retroHP__Sub <- HP_orig$retroHP - HP_orig$Sub
colnames(HP_orig)
# Convert ACtivityCycle to categorical
# ActCycle_dict <- setNames(c("A","B","C",NA), unique(HP_orig$ActivityCycle))
# HP_orig$ActivityCycle <- ActCycle_dict[HP_orig$ActivityCycle]
## Make shapes and colors consistent
shapes <- c(17,16,18,15,7,9)
names(shapes) <-levels(HP_orig$Clade)
#gg_color_hue <- function(n) { # ggplot default colors
#hues = seq(15, 375, length=n+1)
#hcl(h=hues, l=65, c=100)[1:n]
#}
#colors <- gg_color_hue(6)
colors <- c("#C99800","#F8766D","#00BCD8","#00BA38","blue2","#FD61D1")
# Remove human shape/color if humans were removed
if(!("Homo" %in% HP_orig$Genus)){colors<-colors[-1]; shapes<-shapes[-1]}
names(colors) <- names(shapes)
```
## Filter & Normalize
```{r Filter & Normalize}
# log normalize neuro and/or eco data
## Don't need to normalize the neuro vars bc they're already normal and on the same scale.
## Besides, I'm using the residuals for the selective regime analyses.
var_list <- c(
# "Diet_Breadth", # Can't normalize bc it's ordinal data, not numeric like the others
"Population_Density", # "PopulationDensity_n_km2",
"Group_Size",
"Home_Range")
# vec <- HP$data$CA1_res
scale_ <- function(vec, lower=1, upper=2){
scaled <- as.vector(scales::rescale(vec, to=c(lower:upper)))
return(scaled)
}
log_scale <- function(vec){
logged <- log10(vec)
scaled <- scale_(logged)
# scaled <- scaled + 0.00000000000000001
# scaled <- zscore(logged, rescale_01 = T)
return(scaled)
}
scale_log <- function(vec){
scaled <- scale_(vec)# + .Machine$double.xmin
logged <- log10(scaled)
return(logged)
}
scale_minmax <- function(vec){
scaled <- vec + abs(min(vec)) + 0.1
return(scaled)
}
logTrans <- function(vec, constant=1){
logged <- log10(vec + constant - min(vec))
return(logged)
}
logTrans_scale <- function(vec, constant=1){
logged <- log10(vec + constant - min(vec))
scaled <- scale_(logged)
return(scaled)
}
scale_logTrans <- function(vec, constant=1){
scaled <- scale_(vec)
logged <- logTrans(scaled)
return(logged)
}
scaleMM_logTrans <- function(vec, constant=1){
scaled <- scale_minmax(vec)
logged <- logTrans(scaled, constant = constant)
return(logged)
}
logTrans_missing <- function(vec){
indices <- match(NA, vec)
if(is.na(indices)){
completed <- scale_logTrans(vec)
} else {
non.missing <- vec[!is.na(vec)] %>% scale_logTrans()
completed <- R.utils::insert(x=non.missing, ats=indices, values=rep(NA, length(indices)))
}
return(completed)
}
logTrans_missing_scale <- function(vec){
trans <- logTrans_missing(vec)
scaled <- scale_(trans)
return(scaled)
}
rm_outliers <- function(vec, n_outliers=1){
# vec <- HP$data$Population_Density
outliers <- boxplot(vec, plot=F)$out %>% sort(decreasing = T)
if(length(outliers)>0){
indices <- match(outliers[n_outliers], vec)
vec[indices] <- NA
}
return(vec)
}
log_missing <- function(vec){
indices <- match(NA, vec)
if(is.na(indices)){
completed <- scale_logTrans(vec)
} else {
non.missing <- vec[!is.na(vec)] %>% log10()
completed <- R.utils::insert(x=non.missing, ats=indices, values=rep(NA, length(indices)))
}
return(completed)
}
log_missing_scale <- function(vec){
logged <- log_missing(vec)
scaled <- scale_(logged)
return(scaled)
}
# HP_scaled <- HP_orig
# for(v in var_list){
# print(v)
# scaled <- log_scale(HP_orig[[v]] )
# res <- shapiro.test(scaled)
# print(res)
# HP_scaled[v] <- scaled
# # hist(HP_orig[[v]])
# # hist(scaled)
# # From the output, the p-value > 0.05 implying that the distribution of the data are not significantly different from normal distribution. In other words, we can assume the normality.
# }
# HP_orig <- HP_scaled
# Apply filter to find variables with more than ##% of species missing that data, so that they can be excluded from the model (or have data added to them)
# HP_orig <- HP_orig %>% dplyr::select(which(colMeans(is.na(.)) < 0.40))
# ************** Exclude strepsirrhines # **************
# HP_orig <- subset(HP_orig, Clade != "Strepsirrhines")
```
## Tree & Comparative Files
```{r Tree & Comparative Files}
# Primate tree from 10K Trees
tree10K <- read.nexus(file = "Data/Phylo/10k_Primates.nex")
## Rescale tree
# Need to rescale the tree due to errors with pgls described here: http://blog.phytools.org/2011/12/error-message-from-brownielite-and.html#
#scale <- 100
#tree10K$edge.length <- tree10K$edge.length/max(nodeHeights(tree10K)[,2])*scale
# Create comparative.data
HP <- comparative.data(phy=tree10K, data=HP_orig, names.col=Species_10K,
vcv=T, na.omit=F, warn.dropped=T)
# Put Species_10K back as col too
HP$data["Species_10K"] <- row.names(HP$data)
```
# Create Functions
## Assign norm function
```{r}
# res_norm_func=function(x){x}
# resHR_norm_func=scale_
# norm_func=scale_
```
## PGLS residuals & plot function
```{r PGLS residuals & plot function}
pgls.plot_curve <- function(comp_data, x, y, model, xy_plot, x_norm_func, y_norm_func){
x.values <- x_norm_func(as.numeric(comp_data$data[[x]]))
x.smooth<- seq(min(x.values),max(x.values),.01)
exp.predict <- exp(predict(model, setNames(list(x.smooth), x)))
exp.line <- data.frame(x=x.smooth, y=exp.predict)
return( xy_plot + geom_line(data = exp.line, aes(x, y), inherit.aes = F) )
}
pgls.xy_plot <- function(comp_data, pgls_summary,
response_var, predictor_var,
norm_func=function(x){x},
x_prefix="", x_suffix="",
y_prefix="", y_suffix="", interact=F){
xy_plot_legend <- ggplot(comp_data$data, aes(y=norm_func(eval(parse(text=response_var))),
x=norm_func(eval(parse(text=predictor_var))),
fill=Clade, color=Clade, shape=Clade) ) +
geom_abline(slope = pgls_summary$coefficients[2,1], intercept = pgls_summary$coefficients[1,1], color="black") +
geom_point(size=3) +
labs(y=paste0(y_prefix,response_var,y_suffix), x=paste0(x_prefix, predictor_var,x_suffix)) +
theme(plot.title = element_text(hjust=0.5, size=8)) +
scale_shape_manual(values=shapes) + scale_color_manual(values=colors) + scale_fill_manual(values=colors)
if(interact){
print(xy_plot_legend %>% ggplotly())
} else{
print(xy_plot_legend)
}
xy_plot <- xy_plot_legend + theme(legend.position = "none")
return(xy_plot)
}
pgls_function <- function(comp_data,
response_var,
predictor_var,
lambda='ML',
interact=T,
norm_func=log10,#log_missing,
y_prefix="",
x_prefix="",
y_suffix=" (mm3)",
x_suffix=" (mm3)"){
model <- caper::pgls(data=comp_data,
norm_func(eval(parse(text=response_var))) ~
norm_func(eval(parse(text=predictor_var))), lambda=lambda)
pgls_summary <- summary(model)
print(pgls_summary)
## Get res
res <- resid(model)
res_name <- paste(response_var,"res",sep="_")
## Put back into comparative.data
comp_data$data[res_name] <- as.vector(res)# as.vector(scales::rescale(res, c(1:2))) #
new_comp_data <- comp_data
# Put into actual comparative.data in global environment
# comp_data$data[res_name] <- as.vector(scales::rescale(res, c(1:2)))
assign('HP',comp_data,envir=.GlobalEnv)
# Test if residuals are normally distributed
#shapiro.test <- shapiro.test(x = comp_data$data[paste(response_var,"res",sep="_")])
# Residuals XY Plot
# radj <- as.numeric(pgls_summary$adj.r.squared)
# p <- as.numeric(pgls_summary$coefficients[2,4])
#title = title=paste(response_var,"vs.", predictor_var, paste("\n adj.R^2=", round(radj,4),", p= ",round(p,4)))
xy_plot <- pgls.xy_plot(comp_data, pgls_summary,
response_var, predictor_var )
# xy_plot <- pgls.plot_curve(comp_data,
# x=predictor_var, y=response_var,
# model=model, xy_plot=xy_plot,
# x_norm_func = norm_func,
# y_norm_func = function(x){x})
# + annotate("text",x=5, y=10, hjust=0, label = paste("adj.R^2 =", round(radj,4), "; p = ", round(p,4)))
# Plot fancy contMaps
## Absolute vols plot (not that informative since it's basically just tracking brain size)
#HP_data <- as.matrix(comp_data$data[response_var])
#names(HP_data) <- comp_data$phy$tip.label
# phylo_plot <- contMap(comp_data$phy, HP_data, type="phylogram", plot=TRUE)
## Residuals plot
HPres_data <- as.matrix(comp_data$data[res_name])
names(HPres_data) <- comp_data$phy$tip.label
res_phylo_plot <- contMap(comp_data$phy, HPres_data, type="phylogram",
plot=FALSE, fsize=c(0.5, 1))
plot(res_phylo_plot, leg.txt=paste(res_name),lwd=3, fsize=c(0.5, 1))
# Use plot() to edit further
#plot(res_phylo_plot)
#par(cex.lab=.5)
# Top residuals
#res <- DG.HP_res$residuals
res_data <- data.frame(species=row.names(res),res=res)
print(paste("Top 5 Positive Residuals:", res_name))
sort_res <- res_data[with(res_data, order(-res)), ]
row.names(sort_res) <- NULL
print(sort_res[1:5,])
print("=====================================================")
print(paste("Top 5 Negative Residuals:", res_name))
sort_res <- res_data[with(res_data, order(res)), ]
row.names(sort_res) <- NULL
print(sort_res[1:5,])
# Output
output <- list(response_var=response_var, predictor_var=predictor_var,
pgls_summary=pgls_summary, residuals=res, sort_res=sort_res,
xy_plot= xy_plot,
res_phylo_plot=res_phylo_plot,
new_comp_data=new_comp_data)
return(output)
}
```
## Eco analyses function
**NOTE**: Some variables may not be appropriate to put in model together due to colinearity. To solve this, could:
* Remove certain variables
* Perform a stepwise regression: http://blog.phytools.org/2014/06/performing-stepwise-phylogenetic.html
### Phylostep
Optimize the mode through systematic variable selection.
```{r Phylostep}
run_eco.variable_selection <- function(pgls_function.out,
pgls_eco_raw,
eco_vars,
res_norm_func=function(x){x},
resHR_norm_func=scale_,
norm_func=scale_,
bootstraps=100){
# pgls_function.out <- CA1.HP_res
message(">>>>> PHYLOSTEP:: <<<<<<<")
library(future); plan(multiprocess)
# Filtering
dat <- pgls_function.out$new_comp_data
dat <- subset(dat, Genus!="Homo")
keep.species <- row.names(dat$data[,c(pgls_function.out$response_var, eco_vars)] %>% na.omit() %>% droplevels())
dat <- subset(dat, Species %in% keep.species)
# Run variable selection
# text.formula <- paste(pgls_function.out$response_var, "~", paste(eco_vars,collapse="+"))
text.formula <- paste0(pgls_function.out$response_var,"_res ~ ", as.character(pgls_eco_raw$formula)[3])
best.model <- phylolm::phylostep(data = dat$data,
phy = dat$phy,
direction = "both",
model = "lambda",
boot = bootstraps,
formula = eval(parse(text=text.formula)))
message(">>>>> PHYLOSTEP:: Optimized model results <<<<<<<")
print(summary(best.model) )
# Re-run with pgls function just because the summary output is nicer
message(">>>>> PHYLOSTEP:: New Model results <<<<<<<")
print(best.model$formula)
new.model <- caper::pgls(data = dat, formula = eval(parse(text=best.model$formula)))
summary(new.model)
return(best.model)
}
```
```{r Eco analyses function}
nonNA_subset <- function(HP,
response_var,
no_homo = T,
remove_outliers = F,
eco_vars = c("Diet_Breadth",
"Population_Density",
"Group_Size",
"Home_Range",
"Residual_HomeRange")){
dat <- HP
if(no_homo){
print("Removing Homo sapiens...")
# Phylo object understand subset command
dat <- subset(dat, Genus!="Homo")
}
keep.species <- row.names(dat$data[,c(response_var, eco_vars)] %>%
na.omit() %>% droplevels())
dat <- subset(dat, Species %in% keep.species)
if(remove_outliers!=F){
print("Removing outliers...")
for(v in eco_vars){
x <- as.numeric(dat$data[[v]])
dat$data[v] <- rm_outliers(x, remove_outliers)
}
}
return(dat)
}
# MODEL HERE
# Analyze all eco variables in one model
run_eco <- function(pgls_function.out,
res_norm_func=function(x){x},
resHR_norm_func=scale_,
norm_func=scale_,#log_missing_scale,#scale_log,
no_homo=T,
remove_outliers=0,
variable_selection=F){
dat <- pgls_function.out$new_comp_data
eco_vars <- c("Diet_Breadth",
"Population_Density",
"Group_Size",
"Home_Range",
"Residual_HomeRange")
dat <- nonNA_subset(HP = dat,
response_var = pgls_function.out$response_var,
no_homo = no_homo,
eco_vars = eco_vars)
pgls_eco_raw <- pgls(data=dat, formula=
res_norm_func(eval(parse(text=paste(pgls_function.out$response_var,"res",sep="_"))))~
resHR_norm_func(Diet_Breadth) +
norm_func(Population_Density) +
norm_func(Group_Size) +
norm_func(Home_Range) +
resHR_norm_func(Residual_HomeRange),# Residual Home range has to be normalized differently bc it's residual (can't log negatives)
# log10(ActivityCycle) +
# log10(HabitatBreadth) +
# log10(ATWP_perForaging) +
# log10(ATWP_DR),
lambda='ML'
)
# + HR_filled + GroupSize_filled + ATWP_DR + ATWP_perForaging + ATWP_perTravel
pgls_eco_summary <- summary(pgls_eco_raw)
# Variable selection using phylostep
# best.model <- phylolm::phylostep(data = dat$data,
# phy = dat$phy,
# direction = "both",
# model = "BM",
# formula = pgls_eco_raw$formula)
# new.model <- pgls(data = dat, formula = eval(parse(text=best.model$formula)))
# summary(new.model)
if(variable_selection){
optimized.model <- run_eco.variable_selection(pgls_function.out,
pgls_eco_raw,
eco_vars,
res_norm_func,
resHR_norm_func,
norm_func)
} else {optimized.model <- NULL }
print(pgls_eco_summary)
output <- list(pgls_eco_summary=pgls_eco_summary,
pgls_eco_raw=pgls_eco_raw,
optimized.model=optimized.model)
return(output)
}
```
## Eco plot functions
```{r Eco plot functions}
# Plot eco variable function
eco_plots <- function(pgls_function.out,
eco_var,
run_eco.out,
figLabel="",
res_norm_func=function(x){x},
norm_func_plot=log10,
x_prefix=""){
pgls_eco_sum <- run_eco.out$pgls_eco_summary
response_var <- pgls_function.out$response_var
data <- pgls_function.out$new_comp_data$data
brain <- data[,paste(response_var,"res",sep="_")]
eco_x <-data[,paste(eco_var)]
eco.row <- pgls_eco_sum$coefficients[grep(eco_var, rownames(pgls_eco_sum$coefficients)), ]
slope <- as.numeric(eco.row[["Estimate"]])
p <- as.numeric(eco.row[["Pr(>|t|)"]])
# Initialize plot
# if(eco_var=="Residual_HomeRange"){norm_func <- res_norm_func}
eco_plot <- ggplot(data, aes(y=res_norm_func(brain), x=norm_func_plot(eco_x),
fill=Clade, color=Clade, shape=Clade)) +
theme_classic() + ggtitle(figLabel)
# Conditionally add regression line
if ( p<=0.05){
eco_plot <- eco_plot +
geom_smooth(na.rm=F, inherit.aes=F, method="lm", alpha = .15,
data=data, aes(y=res_norm_func(brain), x=norm_func_plot(eco_x)))
}
# Conditionally add legend
if (eco_var == "Residual_HomeRange"){
eco_plot = eco_plot + theme(legend.position=c(1.75, 0.35), legend.background = element_rect(fill="whitesmoke"),
plot.title = element_text(hjust= -.1))
} else{
eco_plot = eco_plot + theme( legend.position="none",
plot.title = element_text(hjust= -.1))
}
# Add remaining featuress
eco_plot <- eco_plot + geom_point(size=3, alpha=.7) +
xlab(paste(x_prefix,eco_var,sep="")) + ylab(paste(response_var,"res",sep="_")) +
scale_shape_manual(values=shapes) + scale_color_manual(values=colors) + scale_fill_manual(values=colors)
#geom_abline(slope=SLOPE, intercept=INTERCEPT)
#assign(paste("eco_plot",paste(response_var,"res",sep="_"), "vs",eco_var,sep="."),eco_plot)
return(eco_plot) # %>% ggplotly()
}
# MAKE MORE FLEXIBLE (dependent on which model variables actually used)
all_eco_plots <- function(pgls_function.out,
norm_func_plot = log_scale,
resHR_norm_func_plot=scale_
){
eco=run_eco(pgls_function.out = pgls_function.out)
print(eco$pgls_eco_summary)
p_f.o <-pgls_function.out
# e0 <- eco_plots(eco_var = "Nocturnality", run_eco.out=eco)
e1 <-eco_plots(pgls_function.out = p_f.o, eco_var = "Diet_Breadth", run_eco.out=eco, figLabel="(a)",
norm_func_plot = resHR_norm_func_plot)
#e2 <-eco_plots(p_f.o, eco_var = "HomeRange_km2", run_eco.out=eco)
#e3 <-eco_plots(p_f.o, eco_var = "HomeRange_Indiv_km2", run_eco.out=eco)
e4 <-eco_plots(p_f.o, eco_var = "Population_Density", run_eco.out=eco, figLabel="(b)", norm_func_plot = norm_func_plot)
# e5 <-eco_plots(p_f.o, eco_var = "SocialGrpSize", run_eco.out=eco)
# e6 <-eco_plots(p_f.o, eco_var = "ATWP_DR", run_eco.out=eco)
# e7 <-eco_plots(p_f.o, eco_var = "ATWP_perForaging", run_eco.out=eco)
#e8 <-eco_plots(p_f.o, eco_var = "ATWP_GroupSize", run_eco.out=eco)
#e9 <-eco_plots(p_f.o, eco_var = "ATWP_HR", run_eco.out=eco)
#e10 <-eco_plots(p_f.o, eco_var = "ATWP_perTravel", run_eco.out=eco)
e11 <-eco_plots(p_f.o, eco_var = "Group_Size", run_eco.out=eco, figLabel="(c)", norm_func_plot = norm_func_plot)
e12 <-eco_plots(p_f.o, eco_var = "Home_Range", run_eco.out=eco, figLabel="(d)", norm_func_plot = norm_func_plot)
e13 <-eco_plots(p_f.o, eco_var = "Residual_HomeRange", run_eco.out=eco, figLabel="(e)",
norm_func_plot = resHR_norm_func_plot)
# Additional variables
# e14 <-eco_plots(p_f.o, eco_var = "ActivityCycle", run_eco.out=eco, figLabel="(f)")
# e15 <-eco_plots(p_f.o, eco_var = "HabitatBreadth", run_eco.out=eco, figLabel="(g)")
# e16 <-eco_plots(p_f.o, eco_var = "ATWP_perForaging", run_eco.out=eco, figLabel="(h)")
# e17 <-eco_plots(p_f.o, eco_var = "ATWP_DR", run_eco.out=eco, figLabel="(i)")
mp <- gridExtra::grid.arrange(e1,e4,e11,e12,e13,
# e14,e15,e16,e17,
ncol=3,
top = textGrob(paste("Ecological Plots:",
paste(pgls_function.out$response_var,"res",sep="_")),
gp=gpar(fontsize=18)))
return(mp)
#e6,e7,e10
# mod_vars <- list(eco_vars=c("DietBreadth","PopulationDensity_n_km2","GroupSize_filled", "Home_Range", "Residual_HomeRange"))
# subplot(e1,e4,e11,e12,e13, nrows = 2, shareY=F, shareX=F, titleX = T, titleY=T, margin = 0.1)
# fluidPage(
# fluidRow( column(4, e1), column(4, e4), column(4, e11)),
# fluidRow( column(4, e12), column(8, e13) )
# )
#plot_grid( plotlist = list(e1,e4,e11,e12,e13), labels = list())
}
```
# Plots & Analyses
## Calculate Residual_HomeRange
```{r Calculate Residual_HomeRange}
suffix = " (log mm3)"#expression(" (log"~mm^3~')')
# HR_phylo <- contMap(HP$phy, HP$data$Home_Range, type="phylogram", plot=F)
# plot(HR_phylo, leg.txt="Home Range",lwd=3, fsize=c(0.5, 1))
# We know HomeRange scales with BodySize, so perhaps using "extra" HR relative to body weight is a more relavent measure.
## Alternatively could include BodySize as covariate in eco model.
# HP$data$Body.Size <- log10(HP$data$Body_Size)
HR.body_res <- pgls_function(HP, "Home_Range", "Body_Size",
norm_func = log_scale,
x_prefix = "", x_suffix = " (g)",
y_prefix = "", y_suffix = " (km2)")
# Put back into Comp.data
HP$data$Residual_HomeRange <- HR.body_res$residuals
```
## Retrocommissural Hippocampus
### retroHP vs. Total Brain Vol
- For eco analysis, use ``scale_log`` (or else PGLS will throw a "reciprocal" error).
- For eco plot, just plot ``log10`` of each ecological varialbe (except *Residual_HomeRange*, which is already normal), and the untransformed y-axis residuals (which are also already normal).
```{r retroHP vs. Total Brain Vol}
# HP vs. Brain
HP.Brain_res <- pgls_function(HP, "retroHP", "Brain__HP", y_suffix = suffix, x_suffix = suffix)
run_eco(pgls_function.out = HP.Brain_res)
all_eco_plots(pgls_function.out = HP.Brain_res)
```
### __***retroHP vs. Medulla***__
```{r retroHP vs. Medulla}
# HP vs. Medulla
HP.Med_res <- pgls_function(HP, "retroHP", "Medulla", y_suffix = suffix, x_suffix = suffix)
retroHP.Medulla <- run_eco(HP.Med_res)
all_eco_plots(HP.Med_res)
# Hyp: Relationship with overall brain vol?
#pgls_function(HP, "retroHP_res", "BrainVol")
```
#### retroHP.vs.Medulla Phenogram
```{r retroHP.vs.Medulla Phenogram, fig.height=8,fig.width=7}
HPres <- HP.Med_res$new_comp_data$data$retroHP_res
names(HPres) <- HP.Med_res$new_comp_data$phy$tip.label
## Get colors from ggplot defaults
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
colz = gg_color_hue(6)
phenogram(HP.Med_res$new_comp_data$phy, x=HPres, spread.labels=T,
fsize=.75, colors=colz, axes=c(time, HPres),
main="Phenogram:\n retroHP vs. medulla PGLS residuals",
xlab="Mya", ylab="retroHP residuals") #spread.cost = c(1, 0)
## Color branches by clades??
```
#### retroHP_res vs. BrainVol
```{r retroHP_res vs. BrainVol}
#Hyp: As brain size scales up, does retroHP_res becomes proportionally smaller?
HPres.Brain_res <- pgls_function(HP, "retroHP_res", "log10(Brain__HP)", y_suffix = "",
norm_func = function(x){x})
retroHP.Brain <- run_eco(pgls_function.out = HPres.Brain_res)
all_eco_plots(HPres.Brain_res)
#Result: No relationship.
```
#### retroHP_res vs. Encephalization
```{r retroHP_res vs. Encephalization}
#Hyp: As Encephalization scales up, does retroHP_res become proportionally smaller?
Enceph_res <- pgls_function(HP, "BrainVol", "Body__Brain", y_suffix = suffix, x_suffix = suffix)
#Don't normalize residuals
pgls_function(HP, "retroHP_res", "BrainVol_res", x_suffix = "", y_suffix = "")
run_eco(HPres.Enceph_res)
all_eco_plots(HPres.Enceph_res)
#Result: No relationship.
```
## Entorhinal Cortex*
* Entorhinal Cortex*: "Included are entorhinal, perirhinal, presubicular and parasubicular cortices and the underlying white matter. These cortices are characterized by the presence of one or several, almost cell-free layers of sublayers."
+ Stephan, H. et al. (1981) New and revised data on volume of brain structures in insectivores and primates. Folia primatol. 35, 1–29
### Entorhinal Cortex* vs. Medulla
NOTE: Using EC.med instead of EC.HP 1) flips the axes of the pPCA, and 2) gets rid of selective regime shift in human lineage. This is because humans are more divergent in EC.med (due to our massively enlarged neocotex, which EC is part of).
```{r Entorhinal Cortex* vs. Medulla}
EC.Med_res <-pgls_function(HP, "EC", "Medulla", y_suffix = suffix, x_suffix = suffix)
run_eco(pgls_function.out = EC.Med_res)
all_eco_plots(EC.Med_res)
```
### Entorhinal Cortex* vs. BrainVol
- Happ-only eco model approaching sig (p=~0.06) after normalizing and using phylostep for variable selection.
```{r Entorhinal Cortex* vs. BrainVol, eval=F}
EC.Brain_res <-pgls_function(HP, "EC", "Brain__EC", y_suffix = suffix, x_suffix = suffix)
run_eco(EC.Brain_res)
all_eco_plots(EC.Brain_res)
```
### Entorhinal Cortex* vs. retroHP
**Note:: Used as final EC**
- Happ-only eco model sig (p=~0.01) after normalizing and using phylostep for variable selection.
```{r Entorhinal Cortex* vs. retroHP}
EC.HP_res <-pgls_function(HP, "EC", "retroHP", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
EC.retroHP <- run_eco(EC.HP_res)
all_eco_plots(EC.HP_res)
#pgls_function(HP, "EC_res", "BrainVol")
```
## HP Fibers
### HP Fibers vs. Medulla
```{r HP Fibers vs. Medulla}
fibers.Med_res <-pgls_function(HP, "Fibers", "Medulla", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
run_eco(fibers.Med_res)
all_eco_plots(fibers.Med_res)
```
### HP Fibers vs. BrainVol
```{r HP Fibers vs. BrainVol}
fibers.brain_res <-pgls_function(HP, "Fibers", "Brain__Fib", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
run_eco(fibers.brain_res)
all_eco_plots(fibers.brain_res)
```
### HP Fibers vs. retroHP + EC * * *
Result: No relationship
```{r HP Fibers vs. retroHP + EC}
fibers.HP_res <-pgls_function(HP, "Fibers", "retroHP.EC", lambda = 0.001, norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
Fibers.retroHP.EC <- run_eco(fibers.HP_res)
all_eco_plots(fibers.HP_res)
#pgls_function(HP, "Fibers_res", "BrainVol")
```
## Subfields
### DentateGyrus vs. retroHP
Result: No relationship
```{r DentateGyrus vs. retroHP}
DG.HP_res <- pgls_function(HP, "DG", "retroHP__DG", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
DG.retroHP <- run_eco(DG.HP_res)
all_eco_plots(DG.HP_res)
#pgls_function(HP, "DG_res", "BrainVol")
```
### FasciaDentata vs. retroHP
Result: No relationship
```{r FasciaDentata vs. retroHP}
FD.HP_res <- pgls_function(HP, "FD", "retroHP__FD", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
FD.retroHP <- run_eco(FD.HP_res, variable_selection = T)
mp <- all_eco_plots(FD.HP_res)
ggsave("./Figures/FINAL/Fig4.png", mp, dpi=400, height=6, width=9)
# improve model
dat <- nonNA_subset(HP = HP, eco_vars = "Residual_HomeRange", response_var = "FD_res")
model <- caper::pgls(data = dat, formula = FD_res ~ Residual_HomeRange, lambda = "ML")
summary(model)
#pgls_function(HP, "FD_res", "BrainVol")
```
### Hilus vs. retroHP
Result: No relationship
```{r Hilus vs. retroHP}
Hilus.HP_res <- pgls_function(HP, "Hilus", "retroHP__Hil", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
Hilus.retroHP <- run_eco(Hilus.HP_res, norm_func = logTrans_missing)
all_eco_plots(Hilus.HP_res)
#pgls_function(HP, "Hilus_res", "BrainVol")
```
### CA2/3 vs. retroHP
Result: Positive relationship between CA2.3_res and retroHP_res.
```{r CA2/3 vs. retroHP}
CA2.3.HP_res <- pgls_function(HP, "CA2.3", "retroHP__CA2.3", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
CA2.3.retroHP <- run_eco(CA2.3.HP_res)
all_eco_plots(CA2.3.HP_res)
#pgls_function(HP, "CA2.3_res", "BrainVol") # No relationship
#pgls_function(HP, "CA2.3_res", "retroHP") # No relationship
#pgls_function(HP, "CA2.3_res", "retroHP_res") # Signficant***
```
### CA3 vs. retroHP
Result: CA3_res gets smaller as retroHP_res gets larger. Humans deviate drastically from this trend by having an unusually large CA3_res.
```{r CA3 vs. retroHP}
CA3.HP_res <- pgls_function(HP, "CA3", "retroHP__CA3", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
CA3.retroHP <- run_eco(CA3.HP_res)
all_eco_plots(CA3.HP_res)
#pgls_function(HP, "CA3_res", "BrainVol")# No relationship
#pgls_function(HP, "CA3_res", "retroHP")# No relationship
#pgls_function(HP, "CA3_res", "retroHP_res") # Approaching sig **
```
### CA2 vs. retroHP
Result: CA2_res gets smaller has retroHP_res gets larger. Humans deviate from this by having somewhat larger CA2_res than expected.
```{r CA2 vs. retroHP}
CA2.HP_res <- pgls_function(HP, "CA2", "retroHP__CA2", norm_func = log10,
y_suffix = suffix, x_suffix = suffix)
CA2.retroHP <- run_eco(CA2.HP_res)
all_eco_plots(CA2.HP_res)
#pgls_function(HP, "CA2_res", "BrainVol")# No relationship
#pgls_function(HP, "CA2_res", "retroHP")# No relationship
#pgls_function(HP, "CA2_res", "retroHP_res") # Significant ***
```
### CA1 vs. retroHP
Result: No relationship.
```{r CA1 vs. retroHP}
CA1.HP_res <- pgls_function(HP, "CA1", "retroHP__CA1", y_suffix = suffix, x_suffix = suffix)
CA1.retroHP <- run_eco(pgls_function.out = CA1.HP_res, variable_selection = T)
ca1.plot <- all_eco_plots(CA1.HP_res)
print(ca1.plot)
ggsave("./Figures/FINAL/Fig5.png", ca1.plot, dpi=400, height=6, width=9)
dat <- nonNA_subset(HP = HP, eco_vars = "Residual_HomeRange", response_var = "CA1_res")
model <- caper::pgls(data = dat, formula = CA1_res ~ Residual_HomeRange, lambda = "ML")
summary(model)
CA1.HP_res <- pgls_function(dat, "CA1_res", "Residual_HomeRange",
y_suffix = suffix, x_suffix = suffix, norm_func = function(x){x})
CA1.HP_res$xy_plot +
geom_point(data = HP$data["Homo_sapiens",], aes(x=Residual_HomeRange, y=CA1_res),
shape="2", color="goldenrod2", size=4)
# Phylogram
res_name <- "Residual_HomeRange"
cont_map <- function(comp_data, res_name){
# comp_data <- HP
HPres_data <- as.matrix(comp_data$data[res_name])
names(HPres_data) <- comp_data$phy$tip.label
res_phylo_plot <- contMap(comp_data$phy,
HPres_data,
type="phylogram",
plot=F, fsize=c(0.5, 1))
# fancyTree(tree = comp_data$phy,
# x=HPres_data,
# type="contmap",
# fsize=c(0.5, 1))
## simulate correlated trait data
# http://blog.phytools.org/2013/09/plotting-facing-trees-using-phytools.html
return(res_phylo_plot)
}
fsize <- c(.5, 1)
plot.new()
par(mfrow=c(1,1))
res_name <- "Residual_HomeRange"
cp0 <- cont_map(HP, res_name)
plot(cp0, leg.txt=paste(res_name),lwd=3, fsize=fsize)
png("./Figures/pheno1.png", res = 100, height=10)
dev.off()
res_name <- "FD_res"
cp1 <- cont_map(HP, res_name)
plot(cp1, leg.txt=paste(res_name),lwd=3, fsize=fsize)
res_name <- "CA1_res"
cp2 <- cont_map(HP, res_name)
plot(cp2, leg.txt=paste(res_name),lwd=3, fsize=fsize)
dev.off()