###############################################################################

# R code used in analyses by Cole et al. (2019)
# Written by Selina R. Cole and David F. Wright (last updated 2/7/2019)

# Citation:
# Cole, S.R., Wright, D.F., and Ausich, W.I., 2019, Phylogenetic community paleoecology of one of the earliest complex crinoid faunas (Brechin Lagerstätte, Ordovician). Palaeogeography, Palaeoclimatology, Palaeoecology.

################################################################################

#####################################################
# Load required packages and source custom scripts###
#####################################################

#----------
# Packages
#----------

library(cluster)
library(sparcl)  
library(vegan)    
library(ape)
library(paleotree)
library(phytools)
library(phangorn)

#------------------------------------------------------------------------------------------
# Source customized R functions and load data (make sure the files are in your working directory!)
#------------------------------------------------------------------------------------------

source("Functions.R")

#------------------------
#Read in & organize data
#------------------------

data <- read.csv("brechin_trait_data.csv", header=TRUE)

#partition out the columns and exclude taxa with NA's
data<-na.omit(data[c(4:19)]) 

#combine columns with genus and species names
sp <- paste0(data$genus,"_",data$species)

#subset the variables to be included in the PCO & link to genus/species names
species <- data[,c(4:13)] 
rownames(species) <- sp

# load the time_list object with geologic timescale and occurrence intervals (as used in paleotree)
load("time_list.RData")



####################
### PCO Analyses ###
####################


#---------------------
# PCO on species data
#---------------------

#the "daisy" function is from the package cluster


#calculate a gower dissimilarity matrix using the daisy function
dist.data <- as.matrix(daisy(species, metric = "gower"))


#number of species in analysis after dropping NA's 
N.taxa <- length(dist.data[,1]) 
N.taxa


# PCO of dissimilarity matrix 
pco.data <- cmdscale(dist.data, k= (8) - 1, add=T)$points


# Optional: look at PCO scree plot
scree.data <- apply(pco.data, 2, var) / sum(apply(pco.data, 2, var)) * 100
plot(scree.data, type="l", xlab="Ordination axis", ylab="Percentage variance")


#Plot  eigenvectors of the Gower diss. matrix against each other
PCOx <- 1
PCOy <- 2
PCOz <- 3
PCOm <- 4
PCOn <- 5
PCOp <- 6



#PCO 1 & 2
plot(pco.data[, PCOx], pco.data[, PCOy], xlab=paste("PCO ", PCOx, " (", round(scree.data[PCOx], 2), "% variance)", sep=""), ylab=paste("PCO ", PCOy, " (", round(scree.data[PCOy], 2), "% variance)", sep=""), pch=19,xlim = c(-0.65,0.3))
text(pco.data[, PCOx], pco.data[, PCOy], rownames(pco.data), pos = 1, cex = 0.6)


#Note: the PCO plots will rotate if you change the order of taxa in the .csv file! 
#color coding will also not apply correctly if order of taxa changes

#to color code PCO:
foo <- read.csv("brechin_trait_data.csv", header=TRUE) 
foo <-na.omit(foo[c(1,4:19)]) 
subclass <- as.character(foo[,1])
clade <- as.character(data[,1])
sp <- paste0(data$genus,"_", data$species)


cols <- "#E5896A" # Diplobathrida (first item in clade)

for (i in 2:length(clade)){
  if (clade[i] == "Diplobathrida"){
    cols <- append(cols, "#E5896A")
  }
  if (clade[i] == "Monobathrida"){
    cols <- append(cols, "#D35777")
  }
  if (clade[i] == "Eucladida"){
    cols <- append(cols, "#A8D0E5")
  }
  if (clade[i] == "Disparida"){
    cols <- append(cols, "#3D798E")
  }
  if (clade[i] == "Flexibilia"){
    cols <- append(cols, "#966AAA")
  }
  if (clade[i] == "Porocrinoidea"){
    cols <- append(cols, "#3EC6AC")
  }
  if (clade[i] == "Stem_Eucamerate"){
    cols <- append(cols, "#F9BF7A")
  }
}


#PCO 1 & 2
plot(pco.data[, PCOx], pco.data[, PCOy], xlab=paste("PCO ", PCOx, " (", round(scree.data[PCOx], 2), "% variance)", sep=""), ylab=paste("PCO ", PCOy, " (", round(scree.data[PCOy], 2), "% variance)", sep=""), pch= ifelse(subclass == "Camerata", 21,22), bg = cols, col = "black", cex=1.4)
text(pco.data[, PCOx], pco.data[, PCOy], rownames(pco.data), pos = 1, cex = 0.6)

#PCO 1 & 3
plot(pco.data[,PCOx], pco.data[,PCOz], xlab=paste("PCO ", PCOx, " (", round(scree.data[PCOx], 2), "% variance)", sep=""), ylab=paste("PCO ", PCOz, " (", round(scree.data[PCOz], 2), "% variance)", sep=""), pch=ifelse(subclass=="Camerata", 21,22),bg = cols, col="black", cex=1.4)
text(pco.data[, PCOx], pco.data[, PCOz], rownames(pco.data), pos = 1, cex = 0.6)

legend("bottomleft", cex = 0.6, legend=c("Diplobathrida", "Monobathrid", "Stem Eucamerate", "Eucladida", "Flexibilia", "Porocrinoidea", "Disparida"), col=c("#E5896A", "#D35777", "#F9BF7A", "#A8D0E5", "#966AAA","#3EC6AC","#3D798E"), pch=c(16,16,16), pt.cex=1)


#-------------------------------
#Add a tree for phylomorphospace
#-------------------------------

tree <- read.nexus("brechin_tree.nex")
tree <- drop.tip(tree, c("Cleiocrinus_regius","Plicodendrocrinus_proboscidiatus"))

#add branch lengths to tree


#Get the total number of branches in the tree (N rows = branches)
Nbranches <- length(tree$edge[,1])

#add unit length (arbitrary for plotting) to each of the branches (N branches, recovered from step above) and format PCO scores for phylomorphospace plot
tree$edge.length <- rep(1,Nbranches); matrix <- cbind(pco.data[,1], pco.data[,2])


#plot the phylomorphospace tree
phylomorphospace(tree, matrix, label=FALSE, node.size=0.5, xlab=paste("PCO ", PCOx, " (", round(scree.data[PCOx], 2), "% variance)", sep=""), ylab=paste("PCO ", PCOy, " (", round(scree.data[PCOy], 2), "% variance)", sep=""))

#plot colored points over top of the phylomorphospace plot using info from the loop above
points(pco.data[, PCOx], pco.data[, PCOy], pch= ifelse(subclass == "Camerata", 21,22), bg = cols, col = "black", cex=1.4)




#---------------------------------------------------
# Spearman's rank correlations for PCO axes
#---------------------------------------------------
species <- as.character(data$genus); names(species) <- paste0(data$genus, "_", data$species)


# Format the data
vol <- log(data$vol_mm); names(vol) <- names(species)
density <- log(data$ff_density_mm); names(density) <- names(species)
area <- log(data$ff_area_mm); names(area) <- names(species)
armL <- data$arm_length
armO <- data$arm_openings
brachW <- data$brach_width
brachH <- data$brach_height
pinnW <- data$pinn_width
pinnD <- data$pinn_density
branch <- data$free_branching
tips <- data$total_tips


# Spearman rank correlations for PCO1
cor.test(pco.data[,1], density, method = "spearman")
cor.test(pco.data[,1], area, method ="spearman")
cor.test(pco.data[,1], vol, method = "spearman")
cor.test(pco.data[,1], armL, method = "spearman")
cor.test(pco.data[,1], armO, method ="spearman")
cor.test(pco.data[,1], brachW, method ="spearman")
cor.test(pco.data[,1], brachH, method ="spearman")
cor.test(pco.data[,1], pinnW, method ="spearman")
cor.test(pco.data[,1], pinnD, method ="spearman")
cor.test(pco.data[,1], branch, method ="spearman")
cor.test(pco.data[,1], tips, method ="spearman")


# Correlations for PCO 2
cor.test(pco.data[,2], density, method = "spearman")
cor.test(pco.data[,2], area, method ="spearman")
cor.test(pco.data[,2], vol, method = "spearman")
cor.test(pco.data[,2], armL, method = "spearman")
cor.test(pco.data[,2], armO, method ="spearman")
cor.test(pco.data[,2], brachW, method ="spearman")
cor.test(pco.data[,2], brachH, method ="spearman")
cor.test(pco.data[,2], pinnW, method ="spearman")
cor.test(pco.data[,2], pinnD, method ="spearman")
cor.test(pco.data[,2], branch, method ="spearman")
cor.test(pco.data[,2], tips, method ="spearman")


# Correlations for PCO 3
cor.test(pco.data[,3], density, method = "spearman")
cor.test(pco.data[,3], area, method ="spearman")
cor.test(pco.data[,3], vol, method = "spearman")
cor.test(pco.data[,3], armL, method = "spearman")
cor.test(pco.data[,3], armO, method ="spearman")
cor.test(pco.data[,3], brachW, method ="spearman")
cor.test(pco.data[,3], brachH, method ="spearman")
cor.test(pco.data[,3], pinnW, method ="spearman")
cor.test(pco.data[,3], pinnD, method ="spearman")
cor.test(pco.data[,3], branch, method ="spearman")
cor.test(pco.data[,3], tips, method ="spearman")


#-----------------------------------------------------------------
#Relationshsips between FFA and body size and between FFA and FFD
#-----------------------------------------------------------------

par(mfrow=c(2,1))
par(mar=c(4, 3.5, 1, 0.5))
par(mgp=c(1.8,0.6,0))


plot(area,vol, col="black", pch=21, bg="cornflowerblue", xlab="Filtration Fan Area (cm^2)", ylab="Body Size (cm^3)", cex=1.4)
cor.test(area, vol, method ="spearman")
abline(lm(vol~area), col="black")

plot(area,density, col="black", pch=21, bg="cornflowerblue", xlab="Filtration Fan Area (cm^2)", ylab="Filtration Fan Density (??/cm^2)", cex=1.4)
cor.test(area, density, method ="spearman")
abline(lm(density~area), col="black")


par(mfrow=c(1,1))
par(mar=c(0,0,0,0))
par(mgp=c(3,1,0))



##############################
###### Cluster Analyses ######
##############################



data <- read.csv("brechin_trait_data.csv", header=TRUE)
data<-na.omit(data[c(1,4:19)])


sp <- paste0(data$genus,"_",data$species)
labels <-data[,1:4]


#subset the variables to be included
species <- data[,c(5:14)]
rownames(species) <- sp


#normalize data
sp.norm <- decostand(species, "normalize") 


#calculate gower dissimilarity matrix
sp.gower <- daisy(sp.norm, metric="gower")


#clustering using the Ward method
cluster.ward <- hclust(sp.gower, method="ward.D")

plot(cluster.ward, hang=-0.1)


#convert to dendro object, which makes it easier to adjust graphics:
dendro.ward <- as.dendrogram(cluster.ward)



#-----------------------------------
# Color dendrogram by Subclass
#-----------------------------------

#library(sparcl)   #for function ColorDendrogram()


myCols <- vector(length = nrow(species))

x <- which(labels$subclass == "Pentacrinoidea")
myCols[x] <- "red"

x <- which(labels$subclass == "Camerata")
myCols[x] <- "cornflowerblue"


myCols <- vector(length = nrow(species))

for(i in 1:length(myCols)) {
  if(labels$subclass[i] == "Pentacrinoidea") myCols[i] <- "#60AAC4"
  else if(labels$subclass[i] == "Camerata") myCols[i] <- "#E26A6A"
  else myCols[i] <- "black"
}

myHClust <- as.hclust(dendro.ward)


#ColorDendrogram(): first parameter is data, the second parameter "y" is info used to color code the dendrogram
ColorDendrogram(myHClust, y = myCols, xlab="Gower Distance", labels=sp,branchlength=0.8)

legend("topright", cex = 0.7, legend=c("Pentacrinoidea", "Camerata"), col=c("#60AAC4", "#E26A6A"), pch=c(16,16,16), pt.cex=1.5)



#------------------------------
# Color dendrogram by subclade
#------------------------------

myCols2 <- vector(length = nrow(species))

x<- which(labels$subclade =="0")
myCols2[x] <- "black"

x <- which(labels$subclade == "Diplobathrida")
myCols2[x] <- "#E5896A"

x <- which(labels$subclade == "Monobathrida")
myCols2[x] <- "#D35777"	

x <- which(labels$subclade == "Stem_Eucamerate")
myCols2[x] <- "#F9BF7A"

x <- which(labels$subclade == "Eucladida")
myCols2[x] <- "#7DAECC"

x <- which(labels$subclade == "Flexibilia")
myCols2[x] <- "#A68BAF"

x <- which(labels$Subclade == "Porocrinoidea")
myCols2[x] <- "#7BC6BB"

x <- which(labels$Subclade == "Disparida")
myCols2[x] <- "#5791AA"


myCols2 <- vector(length = nrow(labels))

for(i in 1:length(myCols2)) {
  if(labels$subclade[i] == "Diplobathrida") myCols2[i] <- "#E5896A"
    else if(labels$subclade[i] == "Monobathrida") myCols2[i] <- "#D35777"
    else if(labels$subclade[i] == "Stem_Eucamerate") myCols2[i] <- "#F9BF7A"
    else if (labels$subclade[i] == "Eucladida") myCols2[i] <- "#7DAECC"
    else if(labels$subclade[i] == "Flexibilia") myCols2[i] <- "#A68BAF"
    else if(labels$subclade[i] == "Porocrinoidea") myCols2[i] <- "#7BC6BB"
    else if(labels$subclade[i] == "Disparida") myCols2[i] <- "#5791AA"
    else myCols2[i] <- "black"
}

myHClust2 <- as.hclust(dendro.ward)


ColorDendrogram(myHClust2, y = myCols2, xlab="Gower Distance", labels=sp, branchlength=0.8)

legend("topright", cex = 0.5, legend=c("Diplobathrida", "Monobathrid", "Stem Eucamerate", "Eucladida", "Flexibilia", "Porocrinoidea", "Disparida"), col=c("#E5896A", "#D35777", "#F9BF7A", "#7DAECC", "#A68BAF","#7BC6BB","#5791AA"), pch=c(16,16,16), pt.cex=1)


#----------------------------------
# co-phylogenetic plot/tanglegram
#----------------------------------


#read in phylogenetic tree
tree <- read.nexus("brechin_tree.nex")
tree <- drop.tip(tree, c("Cleiocrinus_regius", "Plicodendrocrinus_proboscidiatus"))


#convert dendrogram to phylo object using as.phylo function from ape
dendro <- as.phylo(cluster.ward)


# set margins
par(mar=c(0,0,0,0))


#combine the two trees & plot
combo <- cophylo(dendro, tree, rotate=TRUE)  #rotate=TRUE will optimize matching by rotating branches at nodes, this is the default
plot(combo, fsize=0.5, pts=TRUE)



#----------------------------------------------------------
# Comparison of cluster/simulated trees vs. cluster/phylogeny
#----------------------------------------------------------


Nsim <- 10000

D <- vector(mode = "numeric", length = Nsim)

for (i in 1:Nsim){
  
  tr <- rtree(Ntip(tree))
  tr$tip.label <- tree$tip.label
  D[i] <- RF.dist(dendro, tr)
  
}

empirical <- RF.dist(dendro, tree)

#reset margins
par(mar=c(5.1, 4.1, 4.1, 2.1))

hist(D, xlab = "Robinson-Foulds distance", breaks = 7, main = "", col = "darkgray", xlim = c(50,70))
abline(v = empirical, lty = 2, lwd = 2, col = "tomato3")

#calculate p-value for empirical data
p <- 2*(length(D[D <= empirical]) / Nsim) 

legend("topright", cex = 0.8, legend=c("n random trees = 10,000", paste0("p-value = ", p)), bty="n")



############################################
## Get a distribution of timescaled trees###
############################################

# read in the cladogram (if not already in the environment)
tree <- read.nexus("brechin_tree.nex")
tree <- drop.tip(tree, c("Plicodendrocrinus_proboscidiatus", "Cleiocrinus_regius"))


#--------------------
# Two possibilities: choose one before proceeding to "phylogenetic signal" section. Both obtain qualitatively (and quantitatively) similar results.  
#--------------------


#----------------------------------------------------------------------------------------
# 1: Time-scale the trees using cal3 with uncertainty in birth-death-sampling parameters
#----------------------------------------------------------------------------------------


tree.data <- suppressWarnings(get.cal3Tree.distr(tree, time_list, Ntrees = 500)) # suppresses paleotree warning about making inferences on a single tree because we're way past that here

# unpack the results and proceed to "Phylogenetic signal"
trees <- tree.data$c3.trees


######
# OR #
######


#----------------------------------------------------------------------------------------
# 2: Set diversification and sampling parameters to species-level point estimates  
# Rates are ML value estimates from a comprehensive global dataset of early Paleozoic crinoid species 
# (see Wright et al., 2018; and in prep)
#----------------------------------------------------------------------------------------

# grab a sample of 100 time scaled phylogenies and proceed to "Phylogenetic signal" below
trees <- suppressMessages(bin_cal3TimePaleoPhy(tree, time_list, 1.3,1.3,0.05,randres = TRUE, ntrees = 100, anc.wt = 0)) 



########################
# Phylogenetic signal###
########################

# Estimate distributions of Pagel's lambda and Blomberg's K over a distribution of time-scaled phylogenies obtained via one of the methods above

#------------------------
# Filtration fan density
#------------------------

# Pagel's lambda
temp <- multi.phylosig(trees, density, method = "lambda")
mean(temp$lambda); mean(temp$P); length(which(temp$P <= 0.05)) / length(temp$P)
hist(temp$lambda, xlim = c(0,1), col = "darkgrey", xlab = "Pagel's lambda", main = "filtration fan density")
# Blomberg's K
temp <- multi.phylosig(trees, density, method = "K")
mean(temp$K); mean(temp$P); length(which(temp$P <= 0.05)) / length(temp$P)
hist(temp$K, xlim = c(0,2), col = "darkgrey", xlab = "Blomberg's K", main = "Filtration fan density")


#---------------------
# Filtration fan area
#---------------------

# Pagel's lambda
temp <- multi.phylosig(trees, area, method = "lambda")
mean(temp$lambda); mean(temp$P); length(which(temp$P <= 0.05)) / length(temp$P)
hist(temp$lambda, xlim = c(0,1), col = "darkgrey", xlab = "Pagel's lambda", main = "Filtration fan area")
# Blomberg's K
temp <- multi.phylosig(trees, area, method = "K")
mean(temp$K); mean(temp$P); length(which(temp$P <= 0.05)) / length(temp$P)
hist(temp$K, xlim = c(0,2), col = "darkgrey", xlab = "Blomberg's K", main = "Filtration fan area")


#-----------
# Body size
#-----------

# Pagel's lambda
temp <- multi.phylosig(trees, vol, method = "lambda")
mean(temp$lambda); mean(temp$P); length(which(temp$P <= 0.05)) / length(temp$P)
hist(temp$lambda, xlim = c(0,1), col = "darkgrey", xlab = "Pagel's lambda", main = "Body Size")
# Blomberg's K
temp <- multi.phylosig(trees, vol, method = "K")
mean(temp$K); mean(temp$P); length(which(temp$P <= 0.05)) / length(temp$P)
hist(temp$K, xlim = c(0,2), col = "darkgrey", xlab = "Blomberg's K", main = "Body Size")


#################################
# Additional sensitivity test###
#################################

# Test for phylogenetic signal on a tree with unit length branches
# Biologically unrealistic, but neverthess it further tests the phylogenetic signal results independent of probabilistic time-scaling approaches
test <- tree
test$edge.length <- rep(1,60)
# Filtration fan density
phylosig(test, density, method = "lambda", test = TRUE)
phylosig(test, density, method = "K", test = TRUE)
# Filtration fan area
phylosig(test, area, method = "lambda", test = TRUE)
phylosig(test, area, method = "K", test = TRUE)
# Body size
phylosig(test, vol, method = "lambda", test = TRUE)
phylosig(test, vol, method = "K", test = TRUE)

