# Custom R functions used in analyses by Cole et al. (2019)
# Written by David F. Wright (last updated 2/8/2019)


######################################################################################

# Feel free to use/modify/improve this code, but please by kind and cite our paper:

#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
# 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.
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  
######################################################################################


#require(paleotree)
#require(phytools)

#####################
# Custom functions###
#####################


#---------------------
# get.cal3Tree.distr
#---------------------

# Function to generate a distribution of time-scaled trees using cal3 (Bapst, 2013) from interval-based occurrences.
# This function differs from standard node age distributions given by cal3 by also accounting for uncertainty in diversification and sampling parameters.
# Uncertainty is estimated by resampling the fossil record (with replacement) and calculating maximum likelihood estimates of p=q and r (based on Foote, 1997), which generates a distribution of parameters from which we can draw random samples and provide them to cal3.

# tree == an unscaled of cladogram/tree (i.e., in ape format)
# time_list == intervals of first and last appearance. *MUST* be of the same form as a timelist object in paleotree
# max.div == "root.max" in bin_cal3TimePaleoPhy function of paleotree

get.cal3Tree.distr <- function(trees, time_list, Ntrees, max.div = NULL){
  
  Ntrees <- Ntrees
  foo.list <- time_list
  c3.trees <- list(); class(c3.trees) <- "multiPhylo"
  stage_dur <- mean((time_list[[1]][,1] - time_list[[1]][,2])) 
  q <- c()
  r <- c()
  
  for(i in 1:(Ntrees)){
    
    b.matrix <- matrix(data=NA, ncol = 2, nrow = length(time_list[[2]][,1]))
    rownames(b.matrix) <- rownames(time_list[[2]])
    
    for(j in 1:length(b.matrix[,1])){
      
      foo <- sample(time_list[[2]][sample(1:Ntip(tree), size = 1),])
      
      if (names(foo[1]) == "FAD"){
        
        b.matrix[j,] <- foo
      }
      
      else {
        
        b.matrix[j,1] <- foo[2]
        b.matrix[j,2] <-foo[1]
        
      }
      
    }
    
    foo.list[[2]] <- b.matrix
    likFun <- make_durationFreqDisc(foo.list, groups = NULL, drop.extant = TRUE)
    
    bar <- optim(parInit(likFun),likFun,lower=parLower(likFun),upper=parUpper(likFun),
                 method="L-BFGS-B",control=list(maxit=1000000))
    
    q[i] <- bar$par[1]
    r[i] <- sProb2sRate(R = bar$par[2], int.length = stage_dur) 
    
  }
  
  
  for (k in 1:Ntrees){
    
    if (is.null(max.div) == TRUE){
      
      samp.rate <- sample(r,1)
      div.rate <- sample(q,1)
      c3.trees[[k]] <- suppressMessages(bin_cal3TimePaleoPhy(tree, time_list, div.rate,div.rate,samp.rate, ntrees = 1, anc.wt = 0, randres = TRUE))
      print(c(Ntrees - k, "trees left to timescale"))
      
    } else {
      
      tree <- trees[[k]]
      samp.rate <- sample(r,1)
      div.rate <- sample(q,1)
      c3.trees[[k]] <- suppressMessages(bin_cal3TimePaleoPhy(tree, time_list, div.rate,div.rate,samp.rate, ntrees = 1, anc.wt = 0, randres = TRUE, root.max = max.div))
      print(c(Ntrees - k, "trees left to timescale"))
      
    }
    
  }
  
  return(list(c3.trees = c3.trees, q = q, r = r))
  
}



#----------------
# multi.phylosig
#----------------

# Basic wrapper for phylosig (in phytools, Revell, 2012) to summarize phylogenetic signal results over a distribution of trees

multi.phylosig <- function(trees, trait, method = c("lambda", "K")) {
  
  Ntrees = length(trees)
  
  if (method == "lambda"){
    
    L <- c()
    P <- c()
    
    for (i in 1:Ntrees){
      
      tree <- trees[[i]]
      phy.sig <- phylosig(tree, trait, method = "lambda", test = TRUE)
      L[i] <- phy.sig$lambda
      P[i] <- phy.sig$P
      
    }
    
    return(list(lambda = L, P = P))
    
  }
  
  else if (method == "K"){
    
    K <- c()
    P <- c()
    
    for (i in 1:Ntrees){
      
      tree <- trees[[i]]
      phy.sig <- phylosig(tree, trait, method = "K", test = TRUE)
      K[i] <- phy.sig$K
      P[i] <- phy.sig$P
      
    }
    
    return(list(K = K, P = P))
    
  }
  
}

