data(InfTemp)
# Simulate a trait with temperature dependence of the optimum on a simulated tree
# \donttest{
set.seed(9999) # for reproducibility
# Let's start by simulating a trait under a climatic OU
beta = 0.6 # relationship to the climate curve
sim_theta = 4 # value of the optimum if the relationship to the climate curve is 0
sim_sigma2 = 0.025 # variance of the scatter = sigma^2
sim_alpha = 0.36 # alpha value = strength of the OU; quite high here...
delta = 0.001 # time step used for the forward simulations => here its 1000y steps
tree <- phytools::pbtree(n=200, d=0.3) # simulate a bd tree with some extinct lineages
root_age = 60 # height of the root (almost all the Cenozoic here)
tree$edge.length <- root_age*tree$edge.length/max(phytools::nodeHeights(tree))
# here - for this contrived example - I scale the tree so that the root is at 60 Ma
trait <- sim_t_env_ou(tree, sigma=sqrt(sim_sigma2), alpha=sim_alpha, theta0=sim_theta,
param=beta, env_data=InfTemp, step=0.01, scale=TRUE, plot=TRUE)
## Fit the Environmental model (default)
result1 <- fit_t_env_ou(phylo = tree, data = trait, env_data =InfTemp,
method = "Nelder-Mead", df=50, scale=TRUE)
plot(result1)
## Fit user defined model (note that several other environmental variables
## can be simultaneously encapsulated in this function through the env argument)
# We re-define the function for the OU model with linear trend to the climatic curve
# NOTE: the env(t) function should return the value at the root for t=0
my_fun<-function(t, env, param, theta0){
theta0 + param[1]*env(t)
}
# starting value for param[1]. Here we use an arbitrary value of 0.1
beta_guess = 0.1
# fit the model
result2 <- fit_t_env_ou(phylo = tree, data = trait, env_data =InfTemp,
model = my_fun, param = beta_guess,
method = "Nelder-Mead", df=50, scale=TRUE)
# Retrieve the parameters and compare to 'result1'
result2
lines(result2, col="red", lty=2)
## Fit user defined environmental function
require(pspline)
spline_result <- sm.spline(x=InfTemp[,1],y=InfTemp[,2], df=50)
env_func <- function(t){predict(spline_result,t)}
t<-unique(InfTemp[,1])
# We build the interpolated smoothing spline function (not scaled here)
env_data<-splinefun(t,env_func(t))
# We then fit the model
result3 <- fit_t_env_ou(phylo = tree, data = trait, env_data = env_data,
model = my_fun, param = 0.01, method = "Nelder-Mead")
# }
Run the code above in your browser using DataLab