library(ape)
library(MASS)
library(phytools)
## Loading required package: maps
CompareRates.multTrait<-function(phy,x,TraitCov=T,ms.err=NULL,ms.cov=NULL){
  build.chol<-function(b){
    c.mat<-matrix(0,nrow = p,ncol = p)
    c.mat[lower.tri(c.mat)]<-b[-1]
    c.mat[p,p]<-exp(b[1])
    c.mat[1,1]<-sqrt(sum((c.mat[p,])^2))
    if(p>2){
      for(i in 2:(p-1)){
        c.mat[i,i]<-ifelse((c.mat[1,1]^2-sum((c.mat[i,])^2))>0,sqrt(c.mat[1,1]^2-sum((c.mat[i,])^2)),0)
      }
    }
    return(c.mat)
  }
  
  x<-as.matrix(x)
  N<-nrow(x)
  p<-ncol(x)
  C<-vcv.phylo(phy)
  C<-C[rownames(x),rownames(x)]
  
  I<-diag(1,N)
  
  if (is.matrix(ms.err)){
    ms.err<-as.matrix(ms.err[rownames(x),])}
  if (is.matrix(ms.cov)){
    ms.cov<-as.matrix(ms.cov[rownames(x),])}
  
  a.obs<-colSums(solve(C)) %*% x / sum(solve(C))
  one<-matrix(1,N,1)
  
  R.obs<-t(x-one%*%a.obs)%*%solve(C)%*%(x-one%*%a.obs)/N
  
  IIDcon<-function(trait=trait,mu=mu,sigma=sigma,C=C){
    z<- (trait-mu)/sigma
    eC<-eigen(C)
    D.n5<-diag(1/sqrt(eC$values))
    C.neg.5<-eC$vectors%*%D.n5%*%t(eC$vectors)
    return(C.neg.5%*%trait)
  }
  
  D<-matrix(0,N*p,p)
  for(i in 1:(N*p)){
    for(j in 1:p){
      if((j-1)*N < i && i<=j*N){
        D[i,j]=1.0
      }
    }
  }
  y<-as.matrix(as.vector(x))
  
  if (TraitCov==F){R.obs<-diag(diag(R.obs),p)}
  

  LLik.obs<-ifelse(is.matrix(ms.err)==TRUE, 
                   -t(y-D%*%t(a.obs))%*%ginv((kronecker(R.obs,C)+diag(as.vector(ms.err))))%*%(y-D%*%t(a.obs))/2-N*p*log(2*pi)/2-determinant((kronecker(R.obs,C)+ diag(as.vector(ms.err))))$modulus[1]/2,
                   -t(y-D%*%t(a.obs))%*%ginv(kronecker(R.obs,C))%*%(y-D%*%t(a.obs))/2-N*p*log(2*pi)/2-determinant(kronecker(R.obs,C))$modulus[1]/2)
  
  sigma.mn<-mean(diag(R.obs)) 
  if(is.matrix(ms.err) && is.matrix(ms.cov)){
    within.spp<-cbind(ms.err,ms.cov)
    rc.label<-NULL
    for(i in 1:p){
      rc.label<-rbind(rc.label,c(i,i))
    }
    for(j in 2:p){
      if(i!=j&&i<j){
        rc.label<-rbind(rc.label,c(i,j))
      }
    }
    m.e<-NULL
    for(i in 1:p){
      temp<-NULL
      for(j in 1:p){
        for(k in 1:nrow(rc.label)){
          if(setequal(c(i,j),rc.label[k,])==T)
          {tmp<-cbind(tmp,diag(within.spp[,k]))}
        }
      }
      m.e<-rbind(m.e,tmp)
    }
  }
  
  lik.covF<-function(sigma){
    R<-R.obs
    diag(R)<-sigma
    LLik<-ifelse(is.matrix(ms.err)==TRUE,
                 -t(y-D%*%t(a.obs))%*%ginv((kronecker(R,C)+m.e))%*%(y-D%*%t(a.obs))/2-N*p*log(2*pi)/2-determinant((kronecker(R,C)+ m.e))$modulus[1]/2,
                 -t(y-D%*%t(a.obs))%*%ginv(kronecker(R,C))%*%(y-D%*%t(a.obs))/2-N*p*log(2*pi)/2-determinant(kronecker(R,C))$modulus[1]/2)
    if(LLik==-Inf){LLik<--1e+10}
    return(-LLik)
  }
  
  
  ################################
  #h12<-(h1+h2)/2# HERE IS AN ISSUE
  ################################
  #Sh12 <- h12^2*C + (1-h12^2)*I
  
  
  lik.covT<-function(sigma){
    low.chol<-build.chol(sigma)
    R<-low.chol%*%t(low.chol)
    LLik <- ifelse(is.matrix(ms.err)==TRUE,
                   -t(y-D%*%t(a.obs))%*%ginv(kronecker(R,C)+m.e)%*%(y-D%*%t(a.obs))/2-N*p*log(2*pi)/2-determinant(kronecker(R,C)+m.e)$modulus[1]/2,
                   -t(y-D%*%t(a.obs))%*%ginv(kronecker(R,C))%*%(y-D%*%t(a.obs))/2-N*p*log(2*pi)/2-determinant(kronecker(R,C))$modulus[1]/2
    )
    if(LLik==-Inf){LLik<--le+10}
    return(-LLik)
  }
  
  #TraitCov=F
  ## Optimize for no trait covariation
  if(TraitCov==F){model<-optim(sigma.mn,fn=lik.covF,method
                               ="L-BFGS-B",hessian = TRUE,lower = c(0.0))}
  sigma.upper<-2*max(apply(x,2,sd))
  
  
  #TraitCov=T
  ## Optimize with trait covariation
  R.offd<-rep(0,(p*(p-1)/2))
  if(TraitCov==T){model1<-
    #  optim(par=c(sigma.mn,R.offd),fn=lik.covT,method="L-BFGS-B",lower = c(0,0))
    optim(par=c(sigma.mn,R.offd),fn=lik.covT,method="L-BFGS-B",lower = c(0,0))
  }
  
  #sigma<-c(sigma.mn,R.offd)
  #### Assemble R.constrained
  if(TraitCov==F){R.constr<-diag(model$par,p)}
  
  if(TraitCov==T){
    chol.mat<-build.chol(model1$par)
    R.constr<-chol.mat%*%t(chol.mat)
  }
  
  if(model1$convergence==0){
    message<-"Optimization has converged."}else{
      message<-"Optim may not have converrged.
  Consideer changing startt value or lower/upper limits."}
  
  
  LRT<-(-2*((-model1$value-LLik.obs)))
  
  LRT.prob<-pchisq(LRT, (p-1),lower.tail = FALSE)
  
  AIC.obs<- -2*LLik.obs+2*p+2*p #(2p twice: 1x for rates, 1x for anc.states)
  AIC.common<--2*(-model1$value)+2+2*p #(2*1:for 1 rate 2p for anc.states)
  
  return(
    
    list(
      Robs=R.obs,
      Rconstrained=R.constr,
      Lobs=LLik.obs,
      Lconstrained=(-model1$value),
      LRTest=LRT,
      Prob=LRT.prob,
      AICc.obs=AIC.obs,
      AICc.constrained=AIC.common,
      optimmessage=message
    )
  )
}

phy<-rcoal(5)
plot(phy)

x<- matrix(c(rnorm(5,2,1),rnorm(5,0,0.5)),ncol=2)
rownames(x)<-phy$tip.label#LETTERS[1:N]


CompareRates.multTrait(phy=phy,x=x,TraitCov=T,ms.err=NULL,ms.cov=NULL)
## $Robs
##           [,1]       [,2]
## [1,]  9.758637 -1.1807692
## [2,] -1.180769  0.9287916
## 
## $Rconstrained
##          [,1]     [,2]
## [1,] 5.343718 0.000000
## [2,] 0.000000 5.343718
## 
## $Lobs
## [1] -14.21705
## 
## $Lconstrained
## [1] -17.50352
## 
## $LRTest
## [1] 6.572937
## 
## $Prob
## [1] 0.01035409
## 
## $AICc.obs
## [1] 36.43411
## 
## $AICc.constrained
## [1] 41.00704
## 
## $optimmessage
## [1] "Optimization has converged."
tree<-read.tree("http://tonyjhwueng.info/phyrates/ple.nwk")
plot(tree)

tree$tip.label
##  [1] "Plethodon_dorsalis"       "Plethodon_ventralis"     
##  [3] "Plethodon_angusticlavius" "Plethodon_welleri"       
##  [5] "Plethodon_punctatus"      "Plethodon_wehrlei"       
##  [7] "Plethodon_websteri"       "Plethodon_teyahalee"     
##  [9] "Plethodon_cylindraceus"   "Plethodon_variolatus"    
## [11] "Plethodon_chlorobryonis"  "Plethodon_chattahoochee" 
## [13] "Plethodon_cheoah"         "Plethodon_shermani"      
## [15] "Plethodon_amplus"         "Plethodon_meridianus"    
## [17] "Plethodon_montanus"       "Plethodon_albagula"      
## [19] "Plethodon_sequoyah"       "Plethodon_ocmulgee"      
## [21] "Plethodon_savannah"       "Plethodon_grobmani"      
## [23] "Plethodon_kisatchie"      "Plethodon_mississippi"   
## [25] "Plethodon_kiamichi"       "Plethodon_aureolus"      
## [27] "Plethodon_glutinosus"     "Plethodon_jordani"       
## [29] "Plethodon_metcalfi"       "Plethodon_ouachitae"     
## [31] "Plethodon_fourchensis"    "Plethodon_caddoensis"    
## [33] "Plethodon_kentucki"       "Plethodon_petraeus"      
## [35] "Plethodon_yonahlossee"    "Plethodon_hubrichti"     
## [37] "Plethodon_nettingi"       "Plethodon_richmondi"     
## [39] "Plethodon_electromorphus" "Plethodon_cinereus"      
## [41] "Plethodon_shenandoah"     "Plethodon_hoffmani"      
## [43] "Plethodon_virginia"       "Plethodon_serratus"
df<-read.csv("http://tonyjhwueng.info/phyrates/Adams2012-SystBiolData.csv")
head(df)
##                  X HeadLength BodyWidth Forelimb
## 1       P_albagula  12.320000  8.160000 16.12000
## 2         P_amplus  11.120000  7.580000 16.44000
## 3 P_angusticlavius   7.033333  3.700000  8.10000
## 4       P_aureolus   9.200000  5.314286 12.52857
## 5     P_caddoensis   8.200000  3.600000  9.20000
## 6  P_chattahoochee  10.371429  6.400000 13.67143
spX<-strsplit(as.character(df$X),"_")
spname<-array(NA,length(tree$tip.label))
for(Index in 1:length(tree$tip.label)){
  spname[Index]<-paste("Plethodon_", spX[[Index]][2],sep="")
}
spname
##  [1] "Plethodon_albagula"       "Plethodon_amplus"        
##  [3] "Plethodon_angusticlavius" "Plethodon_aureolus"      
##  [5] "Plethodon_caddoensis"     "Plethodon_chattahoochee" 
##  [7] "Plethodon_cheoah"         "Plethodon_chlorobryonis" 
##  [9] "Plethodon_cinereus"       "Plethodon_cylindraceus"  
## [11] "Plethodon_dorsalis"       "Plethodon_electromorphus"
## [13] "Plethodon_fourchensis"    "Plethodon_glutinosus"    
## [15] "Plethodon_grobmani"       "Plethodon_hoffmani"      
## [17] "Plethodon_hubrichti"      "Plethodon_jordani"       
## [19] "Plethodon_kentucki"       "Plethodon_kiamichi"      
## [21] "Plethodon_kisatchie"      "Plethodon_meridianus"    
## [23] "Plethodon_metcalfi"       "Plethodon_mississippi"   
## [25] "Plethodon_montanus"       "Plethodon_nettingi"      
## [27] "Plethodon_ocmulgee"       "Plethodon_ouachitae"     
## [29] "Plethodon_petraeus"       "Plethodon_punctatus"     
## [31] "Plethodon_richmondi"      "Plethodon_savannah"      
## [33] "Plethodon_sequoyah"       "Plethodon_serratus"      
## [35] "Plethodon_shenandoah"     "Plethodon_shermani"      
## [37] "Plethodon_teyahalee"      "Plethodon_variolatus"    
## [39] "Plethodon_ventralis"      "Plethodon_virginia"      
## [41] "Plethodon_websteri"       "Plethodon_wehrlei"       
## [43] "Plethodon_welleri"        "Plethodon_yonahlossee"
df$X<-spname

HeadLength<-df$HeadLength
names(HeadLength)<-spname
BodyWidth<-df$BodyWidth
names(BodyWidth)<-spname

HeadLength<-HeadLength[tree$tip.label]
BodyWidth<-BodyWidth[tree$tip.label]
x<-cbind(HeadLength,BodyWidth)
CompareRates.multTrait(phy=tree,x=x,TraitCov=T,ms.err=NULL,ms.cov=NULL)
## $Robs
##            HeadLength BodyWidth
## HeadLength  0.2282753 0.1252281
## BodyWidth   0.1252281 0.1192467
## 
## $Rconstrained
##           [,1]      [,2]
## [1,] 1.0154436 0.1252281
## [2,] 0.1252281 1.0154436
## 
## $Lobs
## [1] -126.8484
## 
## $Lconstrained
## [1] -188.316
## 
## $LRTest
## [1] 122.9352
## 
## $Prob
## [1] 1.440774e-28
## 
## $AICc.obs
## [1] 261.6968
## 
## $AICc.constrained
## [1] 382.632
## 
## $optimmessage
## [1] "Optimization has converged."