

# Nov 17 2017 Revisions ##########################################################################
#################################################################################################
## Passerine only analysis #######################################################################

# Loading data:
pass.dat = read.csv("passerines only data.csv", header = T, stringsAsFactors = F)
head(pass.dat)
str(pass.dat)

# Organizing data:
pass.dat$Carot <- as.factor(pass.dat$Carot)
pass.dat$Author <- as.factor(pass.dat$Author)
pass.dat$Species <- as.factor(pass.dat$Species)
pass.dat$animal <- as.factor(pass.dat$animal)
pass.dat$Category <- as.factor(pass.dat$Category)
pass.dat$Color.Variable <- as.factor(pass.dat$Color.Variable)
pass.dat$Sex <- as.factor(pass.dat$Sex)

# Creating weight for Zr effect size:
pass.dat$wi <- pass.dat$Sample.Size - 3


############################################
### Covariance matrix among effect sizes ###
############################################
# create square matrix matching N of ES, filled with zeros

vc_matrixB <- matrix(0,nrow = dim(pass.dat)[1],ncol = dim(pass.dat)[1])

pass.dat$EffectID<-as.factor(1:length(pass.dat$ID))

# Naming matrix rows and columns by Effect Size ID:
rownames(vc_matrixB) <- pass.dat$EffectID
colnames(vc_matrixB) <- pass.dat$EffectID 

# Find start and end coordinates for the subsets based on same study:
shared_coord <- which(pass.dat$ExpPop %in% pass.dat$ExpPop[duplicated(pass.dat$ExpPop)]==TRUE)
shared_coord

# Matrix of combinations of coordinates for each study with shared effect sizes:
combinations <- do.call("rbind", tapply(shared_coord, pass.dat[shared_coord,"ExpPop"], function(x) t(combn(x,2))))
combinations

# Calculate covariance values between effect sizes from the same study at the positions in shared_list and place them on the matrix. "SE" is the SD of estimate, so that the covariance is r[corr coefficient] * SD * SD. We are assuming that effect sizes from the same study have a correlation of 0.5. If the correlation is 0, then we can model without this matrix. If r = 1, then we should collapse the related data points:

for (i in 1:dim(combinations)[1]){
  p1 <- combinations[i,1]
  p2 <- combinations[i,2]
  p1_p2_cov <- 0.5*pass.dat[p1,"SE"] * pass.dat[p2,"SE"]
  vc_matrixB[p1,p2] <- p1_p2_cov
  vc_matrixB[p2,p1] <- p1_p2_cov
}

# add the diagonal - use "Variance"
#created variance-covariance matrix
diag(vc_matrixB) <- pass.dat$Variance
head(vc_matrixB) 

is.positive.definite(vc_matrixB)
#[1] TRUE

# you could save this if you like
#save(vc_matrixB,file="vc_matrixB.RData")
#load("vc_matrixB.RData")

# Prepare for MCMCglmm:
AinvGA <- solve(vc_matrixB)
AinvGA <- as(AinvGA,"dgCMatrix") 
str(AinvGA)




## Passerine-only data
trees<-read.nexus("12928.tre")

to.remove = c(1, 21)
pass.tree = lapply(trees, drop.tip, to.remove)

save(pass.tree,file="passerine-only-trees.tre")

# phylogenetic meta-analysis:
invB <- inverseA(pass.tree[[1]], nodes = "TIPS")

# Prior, parameter expanded:
prior <- list(R=list(V=1, nu=0.002), 
              G=list(G1=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000), 
                     G2=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000), 
                     G3=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000), 
                     G4=list(V=1, fix=1)))

# Prior, same as above, but without the random effect for EffectID, in models that don't assume a 0.5 correlation between effect sizes:
prior1 <- list(R=list(V=1, nu=0.002), G=list(G1=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000), G2=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000), G3=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000)))

prior2 <- list(R=list(V=1, nu=0.002), G=list(G1=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000)))



########################################################
### Model with overall effect: Assumming effect sizes are correlated
########################################################
mc.start0_pass <- MCMCglmm(Z.transf ~ 1,
                           data = pass.dat,
                           random = ~animal + Species + Author + EffectID,
                           mev = 1/pass.dat$wi,
                           ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                           prior = prior,
                           nitt = 1000, 
                           burnin = 0, 
                           thin = 1,
                           pl = T,
                           pr = T,
                           verbose = F)

mphylMCMC0_pass <- mc.start0_pass



for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab = mphylMCMC0_pass$Liab[1,], 
                R = mphylMCMC0_pass$VCV[1,1], 
                G = list(G1=mphylMCMC0_pass$VCV[1,2], 
                         G2=mphylMCMC0_pass$VCV[1,3], 
                         G3=mphylMCMC0_pass$VCV[1,4], 
                         G4=mphylMCMC0_pass$VCV[1,5]))
  
  mphylMCMC0_pass <- MCMCglmm(Z.transf ~ 1,
                              data = pass.dat,
                              random = ~ animal + Species + Author + EffectID,
                              mev = 1/pass.dat$wi,
                              ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                              prior = prior,
                              nitt = 1000, 
                              burnin = 999, 
                              thin = 1,
                              start = start,
                              pl = T,
                              pr = T,
                              verbose = F)
  
  if(i>300){ 
    mc.start0_pass$VCV[i-300,]<-mphylMCMC0_pass$VCV[1,]
    mc.start0_pass$Sol[i-300,]<-mphylMCMC0_pass$Sol[1,]
    mc.start0_pass$Liab[i-300,]<-mphylMCMC0_pass$Liab[1,]
  }
  
  print(i)  
}




hist(mc.start0_pass$Liab)
hist(mc.start0$Liab)

hist(mc.start0_pass$VCV[,1])
mean(mc.start0_pass$VCV[,1])
HPDinterval(mc.start0_pass$VCV[,1])


summary(mc.start0_pass)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -472.5074 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.04778 1.992e-11  0.08537     1000
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01822 1.044e-07  0.05483    533.5
# 
# ~Author
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Author  0.005617 1.572e-07  0.01828    248.5
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID         1        1        1        0
# 
# R-structure:  ~units
# 
# post.mean  l-95% CI u-95% CI eff.samp
# units  0.002698 0.0002548 0.007996    63.75
# 
# Location effects: Z.transf ~ 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC
# (Intercept)    0.1609  -0.0797   0.3686     1000 0.102


s2m.0_pass <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.0_pass <- mc.start0_pass$VCV[,"animal"] + mc.start0_pass$VCV[,"Species"] + mc.start0_pass$VCV[,"Author"] + mc.start0_pass$VCV[,"EffectID"]

total.var.0_pass <- mc.start0_pass$VCV[,"animal"] + mc.start0_pass$VCV[,"Species"] + mc.start0_pass$VCV[,"Author"] + mc.start0_pass$VCV[,"EffectID"] + mc.start0_pass$VCV[,"units"] +s2m.0_pass

I2.0_pass<-100*(btw.study.var.0_pass)/(total.var.0_pass)


posterior.mode(I2.0_pass)
# var1 
# 98.3291

summary(I2.0_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 98.110564       0.284002       0.008981       0.041884 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 97.41 98.00 98.18 98.32 98.45 


HPDinterval(I2.0_pass)

# lower   upper
# var1 97.47192 98.4865
# attr(,"Probability")
# [1] 0.95

#===
# MCMCglmm phylogenetic signal = lambda:
#===
I2.animal.0_pass <- 100*(mc.start0_pass$VCV[,"animal"]/total.var.0_pass)

posterior.mode(I2.animal.0_pass)
# var1 
# 0.1190537 

summary(I2.animal.0_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 2.2494         3.5227         0.1114         0.1432 
# 
# 2. Quantiles for each variable:
#   
#   2.5%     25%     50%     75%   97.5% 
# 0.0038  0.3960  1.2704  2.6784 11.1902 



HPDinterval(I2.animal.0_pass)

# lower    upper
# var1 3.813853e-06 7.882944
# attr(,"Probability")
# [1] 0.95

#===
# I2 Species
#===
I2.species.0_pass <- 100*(mc.start0_pass$VCV[,"Species"]/total.var.0_pass)

posterior.mode(I2.species.0_pass)
# var1 
# 0.02740433

summary(I2.species.0_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 1.17077        1.43679        0.04544        0.10831 
# 
# 2. Quantiles for each variable:
#   
#   2.5%      25%      50%      75%    97.5% 
# 0.005361 0.210823 0.688592 1.500106 5.146467

HPDinterval(I2.species.0_pass)
# 
# lower    upper
# var1 2.137837e-05 4.102612
# attr(,"Probability")
# [1] 0.95

#===
# I2 Study
#===
I2.study.0_pass <- 100*(mc.start0_pass$VCV[,"Author"]/total.var.0_pass)

posterior.mode(I2.study.0_pass)

# var1 
# 0.01111063 

summary(I2.study.0_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 0.68734        0.78384        0.02479        0.08675 
# 
# 2. Quantiles for each variable:
#   
#   2.5%       25%       50%       75%     97.5% 
# 0.0009968 0.0977300 0.3976548 0.9745582 2.8146062 


HPDinterval(I2.study.0_pass)

# lower    upper
# var1 4.86142e-06 2.356475
# attr(,"Probability")
# [1] 0.95



########################################################################
###            Egger regression & trim-and-fill (overall effect):
########################################################################
prior.egger <- list(R=list(V=1, nu=0.002), 
                    G=list(G1=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000), 
                           G2=list(V=1, nu=1, alpha.mu = 0, alpha.V = 1000)))


mc0egger_pass <- MCMCglmm(Z.transf ~ 1,
                     data = pass.dat,
                     random = ~ Species + Author,
                     mev = 1/pass.dat$wi,
                     prior = prior.egger,
                     nitt = 1000000, 
                     burnin = 900000, 
                     thin = 100,
                     pl = T,
                     pr = T,
                     verbose = F)

summary(mc0egger_pass) 
save(mc0egger_pass, file = "mc0egger.pass.Rdata")

# Iterations = 900001:999901
# Thinning interval  = 100
# Sample size  = 1000 
# 
# DIC: -118.6474 
# 
# G-structure:  ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01609 3.658e-08  0.05113    823.6
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03884  0.01136  0.06987     1000
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.01801 0.005877  0.02997     1000
# 
# Location effects: Z.transf ~ 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC   
# (Intercept)   0.18003  0.07693  0.26999     1000 0.006 **
#   ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

model<-mc0egger_pass
model$Random$formula<-update(model$Random$formula, ~.+leg(mev, -1, FALSE):units)

Pred<-predict(model, marginal=~leg(mev, -1, FALSE):units)
Prec<-1/sqrt(pass.dat$Variance) # Precision = 1/sqrt(V)
es<-pass.dat$Z.transf-Pred
#save(es,file="newResiduals_pass.RData")

Data1<-data.frame(ES=es,Prec=Prec)

# meta-analysis on residual - we should get meta-analytic mean of 0
mmm2<-rma(yi= es, sei= 1/Prec, method="REML", data=Data1)
summary(mmm2)

# Random-Effects Model (k = 191; tau^2 estimator: REML)
# 
# logLik  deviance       AIC       BIC      AICc  
# 26.1897  -52.3794  -48.3794  -41.8854  -48.3152  
# 
# tau^2 (estimated amount of total heterogeneity): 0.0066 (SE = 0.0025)
# tau (square root of estimated tau^2 value):      0.0813
# I^2 (total heterogeneity / total variability):   28.43%
# H^2 (total variability / sampling variability):  1.40
# 
# Test for Heterogeneity: 
#   Q(df = 190) = 291.8215, p-val < .0001
# 
# Model Results:
#   
#   estimate       se     zval     pval    ci.lb    ci.ub          
# -0.0032   0.0125  -0.2568   0.7973  -0.0276   0.0212


par(mfrow=c(1,2))
funnel(mmm2)
funnel(mmm2,yaxis="seinv")

# We will do publication bias tests for mc.start0 w/o the covariances:

mmmr2<-regtest(mmm2,model="lm")
mmmr2

# Regression Test for Funnel Plot Asymmetry
# 
# model:     weighted regression with multiplicative dispersion
# predictor: standard error
# 
# test for funnel plot asymmetry: t = 1.9804, df = 189, p = 0.0491

mmmt2<-trimfill(mmm2,estimator="L0")
summary(mmmt2)

# Estimated number of missing studies on the left side: 26 (SE = 8.9767)
# 
# Random-Effects Model (k = 217; tau^2 estimator: REML)
# 
# logLik  deviance       AIC       BIC      AICc  
# -7.5537   15.1074   19.1074   25.8580   19.1638  
# 
# tau^2 (estimated amount of total heterogeneity): 0.0218 (SE = 0.0045)
# tau (square root of estimated tau^2 value):      0.1475
# I^2 (total heterogeneity / total variability):   54.91%
# H^2 (total variability / sampling variability):  2.22
# 
# Test for Heterogeneity: 
#   Q(df = 216) = 416.5559, p-val < .0001
# 
# Model Results:
#   
#   estimate       se     zval     pval    ci.lb    ci.ub          
# -0.0413   0.0152  -2.7154   0.0066  -0.0711  -0.0115       ** 





######################################################################################################
###            Model with converted vs. dietary carotenoids (ASSUMING r = 0.5 among ES):
######################################################################################################


mc.start.3_pass <- MCMCglmm(Z.transf~Carot - 1,
                            data = pass.dat,
                            random = ~animal + Species + Author + EffectID,
                            ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                            prior = prior,
                            nitt = 1000, 
                            burnin = 0, 
                            thin = 1,
                            pl = T,
                            verbose = F)

summary(mc.start.3_pass)

mphylMCMC.3_pass <- mc.start.3_pass



for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.3_pass$Liab[1,], R =mphylMCMC.3_pass$VCV[1,1], G = list(G1=mphylMCMC.3_pass$VCV[1,2], G2=mphylMCMC.3_pass$VCV[1,3], G3=mphylMCMC.3_pass$VCV[1,4], G4=mphylMCMC.3_pass$VCV[1,5]))
  
  mphylMCMC.3_pass <- MCMCglmm(Z.transf~Carot - 1,
                               data = pass.dat,
                               random = ~animal + Species + Author + EffectID,
                               ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                               prior = prior,
                               nitt = 1000, 
                               burnin = 999, 
                               thin = 1,
                               start = start,
                               pl = T,
                               verbose = F)
  
  if(i>300){ 
    mc.start.3_pass$VCV[i-300,]<-mphylMCMC.3_pass$VCV[1,]
    mc.start.3_pass$Sol[i-300,]<-mphylMCMC.3_pass$Sol[1,]
    mc.start.3_pass$Liab[i-300,]<-mphylMCMC.3_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.3_pass)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -5.568277 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.01882 3.244e-08  0.06819    277.1
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species    0.0122 4.389e-09  0.04896      264
# 
# ~Author
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Author   0.03217 6.233e-08   0.0712    8.031
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3445  0.05129        1    1.964
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05531  0.03223   0.0782    4.608
# 
# Location effects: Z.transf ~ Carot - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# CarotConverted   0.26321  0.06223  0.49189     1000 0.022 *
#   CarotDietary     0.08957 -0.12355  0.29253     1108 0.346  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1



s2m.3_pass <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.3_pass <- mc.start.3_pass$VCV[,"animal"] + mc.start.3_pass$VCV[,"Species"] + mc.start.3_pass$VCV[,"Author"] + mc.start.3_pass$VCV[,"EffectID"]

total.var.3_pass <- mc.start.3_pass$VCV[,"animal"] + mc.start.3_pass$VCV[,"Species"] + mc.start.3_pass$VCV[,"Author"] + mc.start.3_pass$VCV[,"EffectID"] + mc.start.3_pass$VCV[,"units"] +s2m.3_pass

I2.3_pass<-100*(btw.study.var.3_pass)/(total.var.3_pass)


posterior.mode(I2.3_pass)
# var1 
# 94.85841

summary(I2.3_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 72.433         15.652          0.495         10.262 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 51.96 60.44 65.83 94.44 95.59


HPDinterval(I2.3_pass)

# lower    upper
# var1 53.54631 95.85842
# attr(,"Probability")
# [1] 0.95


#####################################################################################
################## Getting difference between Converted and Dietary ################
###################################################################################

contrasts(pass.dat$Carot) <- contr.treatment(levels(pass.dat$Carot), base = 1)



mc.start.3_pass.cont <- MCMCglmm(Z.transf~Carot,
                            data = pass.dat,
                            random = ~animal + Species + Author + EffectID,
                            ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                            prior = prior,
                            nitt = 1000, 
                            burnin = 0, 
                            thin = 1,
                            pl = T,
                            verbose = F)

summary(mc.start.3_pass.cont)

mphylMCMC.3_pass.cont <- mc.start.3_pass.cont



for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.3_pass.cont$Liab[1,], R =mphylMCMC.3_pass.cont$VCV[1,1], G = list(G1=mphylMCMC.3_pass.cont$VCV[1,2], G2=mphylMCMC.3_pass.cont$VCV[1,3], G3=mphylMCMC.3_pass.cont$VCV[1,4], G4=mphylMCMC.3_pass.cont$VCV[1,5]))
  
  mphylMCMC.3_pass.cont <- MCMCglmm(Z.transf~Carot,
                               data = pass.dat,
                               random = ~animal + Species + Author + EffectID,
                               ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                               prior = prior,
                               nitt = 1000, 
                               burnin = 999, 
                               thin = 1,
                               start = start,
                               pl = T,
                               verbose = F)
  
  if(i>300){ 
    mc.start.3_pass.cont$VCV[i-300,]<-mphylMCMC.3_pass.cont$VCV[1,]
    mc.start.3_pass.cont$Sol[i-300,]<-mphylMCMC.3_pass.cont$Sol[1,]
    mc.start.3_pass.cont$Liab[i-300,]<-mphylMCMC.3_pass.cont$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.3_pass.cont)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: 52.03296 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.02374 4.665e-10   0.1112    68.22
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01337 2.293e-08  0.05222    340.1
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.04792  0.01789  0.08355    538.7
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3445  0.05162        1     2.01
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05879   0.0402  0.07761    11.41
# 
# Location effects: Z.transf ~ Carot 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# (Intercept)    0.26209  0.04523  0.54868   1426.6 0.036 *
#   CarotDietary  -0.15798 -0.38890  0.09700    845.2 0.162  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

###########################################################################################
###     Overall Model with Category (ASSUMING r = 0.5 BETWEEN ES):
###########################################################################################

mc.start.7_pass <- MCMCglmm(Z.transf~ Category - 1,
                            data = pass.dat,
                            random = ~animal + Species + Author + EffectID,
                            ginverse = list(animal=invB$Ainv, EffectID = AinvGA),
                            prior = prior,
                            nitt = 1000, 
                            burnin = 0, 
                            thin = 1,
                            pl = T,
                            verbose = F)

summary(mc.start.7_pass)

mphylMCMC.7_pass <- mc.start.7_pass



for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.7_pass$Liab[1,], R =mphylMCMC.7_pass$VCV[1,1], G = list(G1=mphylMCMC.7_pass$VCV[1,2], G2=mphylMCMC.7_pass$VCV[1,3], G3=mphylMCMC.7_pass$VCV[1,4], G4=mphylMCMC.7_pass$VCV[1,5]))
  
  mphylMCMC.7_pass <- MCMCglmm(Z.transf~Category - 1,
                               data = pass.dat,
                               random = ~animal + Species + Author + EffectID,
                               ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                               prior = prior,
                               nitt = 1000, 
                               burnin = 999, 
                               thin = 1,
                               start = start,
                               pl = T,
                               verbose = F)
  
  if(i>300){ 
    mc.start.7_pass$VCV[i-300,]<-mphylMCMC.7_pass$VCV[1,]
    mc.start.7_pass$Sol[i-300,]<-mphylMCMC.7_pass$Sol[1,]
    mc.start.7_pass$Liab[i-300,]<-mphylMCMC.7_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.7_pass)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -14.11343 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.03287 3.425e-08    0.114      670
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01396 3.992e-07  0.04937    530.8
# 
# ~Author
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Author   0.03035 3.132e-10   0.0649    6.816
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3436  0.05077        1        2
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05315  0.02544  0.07312    4.122
# 
# Location effects: Z.transf ~ Category - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# CategoryCondition               0.06451 -0.21849  0.35237    611.9 0.540  
# CategoryImmune                  0.10154 -0.21075  0.36287   1000.0 0.398  
# CategoryParasite                0.24330 -0.07472  0.51021    901.8 0.096 .
# CategoryParental/Reproduction   0.22311 -0.09988  0.46221   1000.0 0.122  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1



s2m.7_pass <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.7_pass <- mc.start.7_pass$VCV[,"animal"] + mc.start.7_pass$VCV[,"Species"] + mc.start.7_pass$VCV[,"Author"] + mc.start.7_pass$VCV[,"EffectID"]

total.var.7_pass <- mc.start.7_pass$VCV[,"animal"] + mc.start.7_pass$VCV[,"Species"] + mc.start.7_pass$VCV[,"Author"] + mc.start.7_pass$VCV[,"EffectID"] + mc.start.7_pass$VCV[,"units"] +s2m.7_pass

I2.7_pass<-100*(btw.study.var.7_pass)/(total.var.7_pass)


posterior.mode(I2.7_pass)
# var1 
# 94.36402

summary(I2.7_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 94.39660        0.95044        0.03006        0.05183 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 93.02 93.99 94.43 94.88 95.70


HPDinterval(I2.7_pass)

# lower    upper
# var1 93.12494 95.74877
# attr(,"Probability")
# [1] 0.95



###########################################################################################
###     Model with Category and type of Carotenoid  (Assuming r = 0.5 between ESs):
###########################################################################################


mc.start.9_pass <- MCMCglmm(Z.transf~ Category:Carot -1,
                            data = pass.dat,
                            random = ~animal + Species + Author + EffectID,
                            ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                            prior = prior,
                            nitt = 1000, 
                            burnin = 0, 
                            thin = 1,
                            pl = T,
                            verbose = F)

summary(mc.start.9_pass)

mphylMCMC.9_pass <- mc.start.9_pass



for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.9_pass$Liab[1,], R =mphylMCMC.9_pass$VCV[1,1], G = list(G1=mphylMCMC.9_pass$VCV[1,2], G2=mphylMCMC.9_pass$VCV[1,3], G3=mphylMCMC.9_pass$VCV[1,4], G4=mphylMCMC.9_pass$VCV[1,5]))
  
  mphylMCMC.9_pass <- MCMCglmm(Z.transf~Category:Carot - 1,
                               data = pass.dat,
                               random = ~animal + Species + Author + EffectID,
                               ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                               prior = prior,
                               nitt = 1000, 
                               burnin = 999, 
                               thin = 1,
                               start = start,
                               pl = T,
                               verbose = F)
  
  if(i>300){ 
    mc.start.9_pass$VCV[i-300,]<-mphylMCMC.9_pass$VCV[1,]
    mc.start.9_pass$Sol[i-300,]<-mphylMCMC.9_pass$Sol[1,]
    mc.start.9_pass$Liab[i-300,]<-mphylMCMC.9_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.9_pass)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -26.44002 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.02248 9.183e-09  0.08914    346.2
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01093 4.278e-09  0.03915    279.8
# 
# ~Author
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Author   0.02162 1.964e-07  0.05081    9.971
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3418  0.04901        1    1.994
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05092  0.02593  0.07172    2.176
# 
# Location effects: Z.transf ~ Category:Carot - 1 
# 
# post.mean  l-95% CI  u-95% CI eff.samp pMCMC   
# CategoryCondition:CarotConverted              0.084007 -0.158547  0.358236     1000 0.446   
# CategoryImmune:CarotConverted                 0.097922 -0.185954  0.367045     1000 0.436   
# CategoryParasite:CarotConverted               0.435114  0.174715  0.688995     1000 0.006 **
# CategoryParental/Reproduction:CarotConverted  0.337485  0.021148  0.618882     1000 0.034 * 
# CategoryCondition:CarotDietary                0.106965 -0.186198  0.387852     1158 0.398   
# CategoryImmune:CarotDietary                   0.113537 -0.135304  0.371149     1000 0.330   
# CategoryParasite:CarotDietary                 0.009203 -0.241867  0.283083     1000 0.920   
# CategoryParental/Reproduction:CarotDietary    0.095383 -0.182517  0.311780     1000 0.394   
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1



s2m.9_pass <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.9_pass <- mc.start.9_pass$VCV[,"animal"] + mc.start.9_pass$VCV[,"Species"] + mc.start.9_pass$VCV[,"Author"] + mc.start.9_pass$VCV[,"EffectID"]

total.var.9_pass <- mc.start.9_pass$VCV[,"animal"] + mc.start.9_pass$VCV[,"Species"] + mc.start.9_pass$VCV[,"Author"] + mc.start.9_pass$VCV[,"EffectID"] + mc.start.9_pass$VCV[,"units"] +s2m.9_pass

I2.9_pass<-100*(btw.study.var.9_pass)/(total.var.9_pass)


posterior.mode(I2.9_pass)
# var1 
# 94.44083

summary(I2.9_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 72.4043        15.7622         0.4984         8.6347 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 49.86 59.90 67.22 93.76 95.21



HPDinterval(I2.9_pass)

# lower   upper
# var1 52.19162 95.6872
# attr(,"Probability")
# [1] 0.9



###########################################################################################
###     Model with Category and type of Carotenoid (getting contrasts. Assuming r = 0.5 between ESs):
###########################################################################################


contrasts(pass.dat$Carot) <- contr.treatment(levels(pass.dat$Carot), base = 1)

pass.dat$Category <- relevel(pass.dat$Category, ref = "Parental/Reproduction")

mc.start.10_pass <- MCMCglmm(Z.transf~ Category*Carot ,
                            data = pass.dat,
                            random = ~animal + Species + Author + EffectID,
                            ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                            prior = prior,
                            nitt = 1000, 
                            burnin = 0, 
                            thin = 1,
                            pl = T,
                            verbose = F)

summary(mc.start.10_pass)

mphylMCMC.10_pass <- mc.start.10_pass



for(i in 1:length(pass.tree)){
  
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.10_pass$Liab[1,], R =mphylMCMC.10_pass$VCV[1,1], G = list(G1=mphylMCMC.10_pass$VCV[1,2], G2=mphylMCMC.10_pass$VCV[1,3], G3=mphylMCMC.10_pass$VCV[1,4], G4=mphylMCMC.10_pass$VCV[1,5]))
  
  mphylMCMC.10_pass <- MCMCglmm(Z.transf~Category*Carot,
                               data = pass.dat,
                               random = ~animal + Species + Author + EffectID,
                               ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                               prior = prior,
                               nitt = 1000, 
                               burnin = 999, 
                               thin = 1,
                               start = start,
                               pl = T,
                               verbose = F)
  
  if(i>300){ 
    mc.start.10_pass$VCV[i-300,]<-mphylMCMC.10_pass$VCV[1,]
    mc.start.10_pass$Sol[i-300,]<-mphylMCMC.10_pass$Sol[1,]
    mc.start.10_pass$Liab[i-300,]<-mphylMCMC.10_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.10_pass)



############## Parasite Contrast Converted vs Dietary  ################################

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: 38.56197 
# 
# G-structure:  ~animal
# 
# post.mean l-95% CI u-95% CI eff.samp
# animal   0.02853  7.2e-10   0.1094    222.3
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01436 2.642e-11  0.04804    437.9
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03286  0.01114  0.06415    497.5
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3427  0.04863        1    1.989
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units     0.056  0.03762  0.07449    13.31
# 
# Location effects: Z.transf ~ Category * Carot 
# 
# post.mean l-95% CI u-95% CI eff.samp  pMCMC    
# (Intercept)                                  0.44854  0.21269  0.74759   1000.0  0.004 ** 
#   CategoryImmune                              -0.36236 -0.55014 -0.17089    587.7 <0.001 ***
#   CategoryCondition                           -0.35844 -0.52029 -0.16418    907.0 <0.001 ***
#   CategoryParental/Reproduction               -0.10354 -0.35971  0.14681   1000.0  0.454    
# CarotDietary                                -0.42016 -0.69247 -0.16157   1000.0  0.006 ** 
#   CategoryImmune:CarotDietary                  0.46604  0.19554  0.72888   1000.0 <0.001 ***
#   CategoryCondition:CarotDietary               0.45638  0.20110  0.74210   1000.0  0.004 ** 
#   CategoryParental/Reproduction:CarotDietary   0.19616 -0.09604  0.53328   1000.0  0.202    
---

#########################################################################################
  ############## Parental/Reproduction Contrast Converted vs Dietary  ################################

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: 38.21046 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.02826 6.802e-09   0.1232    240.3
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01658 1.672e-08  0.05429    247.4
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03184 0.008112  0.06106    424.8
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3428  0.04961        1    1.964
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units    0.0554   0.0362  0.07428    32.03
# 
# Location effects: Z.transf ~ Category * Carot 
# 
# post.mean  l-95% CI  u-95% CI eff.samp pMCMC  
# (Intercept)                     0.329958  0.029001  0.705035   1000.0 0.074 .
# CategoryParasite                0.106467 -0.132606  0.384893   1000.0 0.422  
# CategoryImmune                 -0.260137 -0.507756  0.013516   1000.0 0.062 .
# CategoryCondition              -0.251666 -0.496756  0.009437   1000.0 0.060 .
# CarotDietary                   -0.227279 -0.536816  0.153791   1000.0 0.188  
# CategoryParasite:CarotDietary  -0.202335 -0.560660  0.077459   1000.0 0.214  
# CategoryImmune:CarotDietary     0.270533 -0.063736  0.640302   1000.0 0.136  
# CategoryCondition:CarotDietary  0.254847 -0.054931  0.648269    895.8 0.154  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1



#########################################################################################
###########    Species Effect Sizes With Only Passerines ################################
############                                             ###############################
########################################################################################


mc.start.14_pass <- MCMCglmm(Z.transf~ Species - 1,
                             data = pass.dat,
                             random = ~ Author,
                             ginverse = list(animal=invA$Ainv),
                             mev = 1/pass.dat$wi,
                             prior = prior2,
                             nitt = 1000, 
                             burnin = 0, 
                             thin = 1,
                             pl = T,
                             verbose = F)




mphylMCMC.14_pass <- mc.start.14_pass


for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.14_pass$Liab[1,], R =mphylMCMC.14_pass$VCV[1,1], G = list(G1=mphylMCMC.14_pass$VCV[1,2]))
  
  mphylMCMC.14_pass <- MCMCglmm(Z.transf~ Species - 1,
                                data = pass.dat,
                                random = ~Author,
                                ginverse = list(animal=invA$Ainv),
                                mev = 1/pass.dat$wi,
                                prior = prior2,
                                nitt = 1000, 
                                burnin = 999, 
                                thin = 1,
                                start = start,
                                pl = T,
                                verbose = F)
  
  if(i>300){ 
    mc.start.14_pass$VCV[i-300,]<-mphylMCMC.14_pass$VCV[1,]
    mc.start.14_pass$Sol[i-300,]<-mphylMCMC.14_pass$Sol[1,]
    mc.start.14_pass$Liab[i-300,]<-mphylMCMC.14_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.14_pass)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -105.0481 
# 
# G-structure:  ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03491 0.009886  0.06648     98.4
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.01769 0.006112  0.02804    309.7
# 
# Location effects: Z.transf ~ Species - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp  pMCMC    
# SpeciesAmerican Goldfinch        0.97737  0.44929  1.45653   1000.0  0.002 ** 
# SpeciesBlue Tit                  0.19733 -0.06987  0.41935    897.1  0.130    
# SpeciesCirl Bunting             -0.28475 -0.82989  0.22441   1153.1  0.286    
# SpeciesCommon Redpoll           -0.36304 -0.90784  0.16795   1000.0  0.182    
# SpeciesCommon Rosefinch          0.38901 -0.11061  0.93370   1525.9  0.136    
# SpeciesCommon Yellowthroat       0.07632 -0.14659  0.31485   1000.0  0.508    
# SpeciesEuropean Greenfinch       0.12989 -0.05268  0.29426   1000.0  0.170    
# SpeciesEuropean Serin            0.41891 -0.04887  0.95989   1000.0  0.100    
# SpeciesGolden-Collared Manakin   0.21609 -0.23979  0.65068   1102.5  0.340    
# SpeciesGolden-crowned Kinglet    0.12185 -0.24497  0.51106   1707.4  0.540    
# SpeciesGreat Tit                 0.13318  0.02762  0.24797   1000.0  0.022 *  
# SpeciesHouse Finch               0.38645  0.22058  0.55782   1000.0 <0.001 ***
# SpeciesKentucky Warbler          0.04108 -0.41631  0.53945   1000.0  0.876    
# SpeciesLinnet                    0.12288 -0.14729  0.40706   1000.0  0.392    
# SpeciesNorthern Cardinal         0.27164  0.09546  0.48522    899.4  0.010 *  
# SpeciesRed-winged Blackbird      0.14362 -0.32086  0.60549   1000.0  0.526    
# SpeciesRed Fody                  0.05935 -0.33474  0.50830   1000.0  0.810    
# SpeciesSouthern Red Bishop       0.34237 -0.09536  0.80193   1000.0  0.120    
# SpeciesYellowhammer             -0.05809 -0.26685  0.16384   1000.0  0.610    
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

###############################################################################################

##############################################################################################

################### parasite lumped with immune data  ########################################

#############################################################################################
Para.Data = read.csv("parasite lump immune data.csv", header = T, stringsAsFactors = F)
head(Para.Data)
str(Para.Data)

# Organizing data:
Para.Data$Carot <- as.factor(Para.Data$Carot)
Para.Data$Author <- as.factor(Para.Data$Author)
Para.Data$Species <- as.factor(Para.Data$Species)
Para.Data$animal <- as.factor(Para.Data$animal)
Para.Data$Category <- as.factor(Para.Data$Category)
Para.Data$Color.Variable <- as.factor(Para.Data$Color.Variable)
Para.Data$Sex <- as.factor(Para.Data$Sex)

# Creating weight for Zr effect size:
Para.Data$wi <- Para.Data$Sample.Size - 3


############################################
### Covariance matrix among effect sizes ###
############################################
# create square matrix matching N of ES, filled with zeros

vc_matrixA <- matrix(0,nrow = dim(Para.Data)[1],ncol = dim(Para.Data)[1])

Para.Data$EffectID<-as.factor(1:length(Para.Data$ID))

# Naming matrix rows and columns by Effect Size ID:
rownames(vc_matrixA) <- Para.Data$EffectID
colnames(vc_matrixA) <- Para.Data$EffectID 

# Find start and end coordinates for the subsets based on same study:
shared_coord <- which(Para.Data$ExpPop %in% Para.Data$ExpPop[duplicated(Para.Data$ExpPop)]==TRUE)
shared_coord

# Matrix of combinations of coordinates for each study with shared effect sizes:
combinations <- do.call("rbind", tapply(shared_coord, Para.Data[shared_coord,"ExpPop"], function(x) t(combn(x,2))))
combinations

# Calculate covariance values between effect sizes from the same study at the positions in shared_list and place them on the matrix. "SE" is the SD of estimate, so that the covariance is r[corr coefficient] * SD * SD. We are assuming that effect sizes from the same study have a correlation of 0.5. If the correlation is 0, then we can model without this matrix. If r = 1, then we should collapse the related data points:

for (i in 1:dim(combinations)[1]){
  p1 <- combinations[i,1]
  p2 <- combinations[i,2]
  p1_p2_cov <- 0.5*Para.Data[p1,"SE"] * Para.Data[p2,"SE"]
  vc_matrixA[p1,p2] <- p1_p2_cov
  vc_matrixA[p2,p1] <- p1_p2_cov
}

# add the diagonal - use "Variance"
#created variance-covariance matrix
diag(vc_matrixA) <- Para.Data$Variance
head(vc_matrixA) 

is.positive.definite(vc_matrixA)
#[1] TRUE

# you could save this if you like
save(vc_matrixA,file="vc_matrixA.RData")
load("vc_matrixA.RData")

# Prepare for MCMCglmm:
AinvGA <- solve(vc_matrixA)
AinvGA <- as(AinvGA,"dgCMatrix") 
str(AinvGA)

####################################################################################################
################# Parasite lumped with Immune category, but Oxidative measures separate Cat
#####################################################################################################

mc.start.9.para <- MCMCglmm(Z.transf~ Category:Carot - 1,
                            data = Para.Data,
                            random = ~animal + Species + Author + EffectID,
                            ginverse = list(animal=invA$Ainv, EffectID=AinvGA),
                            prior = prior,
                            nitt = 1000, 
                            burnin = 0, 
                            thin = 1,
                            pl = T,
                            verbose = F)

summary(mc.start.9.para)

mphylMCMC.9.para <- mc.start.9.para



for(i in 1:length(pass.tree)){
  
  invA <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.9.para$Liab[1,], R =mphylMCMC.9.para$VCV[1,1], G = list(G1=mphylMCMC.9.para$VCV[1,2], G2=mphylMCMC.9.para$VCV[1,3], G3=mphylMCMC.9.para$VCV[1,4], G4=mphylMCMC.9.para$VCV[1,5]))
  
  mphylMCMC.9.para <- MCMCglmm(Z.transf~Category:Carot - 1,
                               data = Para.Data,
                               random = ~animal + Species + Author + EffectID,
                               ginverse = list(animal=invA$Ainv, EffectID=AinvGA),
                               prior = prior,
                               nitt = 1000, 
                               burnin = 999, 
                               thin = 1,
                               start = start,
                               pl = T,
                               verbose = F)
  
  if(i>300){ 
    mc.start.9.para$VCV[i-300,]<-mphylMCMC.9.para$VCV[1,]
    mc.start.9.para$Sol[i-300,]<-mphylMCMC.9.para$Sol[1,]
    mc.start.9.para$Liab[i-300,]<-mphylMCMC.9.para$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.9.para)


# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -18.35145 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.01512 1.351e-09  0.06073    356.6
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species  0.008523 2.961e-09    0.033    525.7
# 
# ~Author
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Author    0.0292 4.521e-08  0.06379    12.57
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3438   0.0506        1    1.998
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05344  0.02533  0.07455    3.763
# 
# Location effects: Z.transf ~ Category:Carot - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# CategoryCondition:CarotConverted               0.07799 -0.13839  0.34085    889.5 0.464  
# CategoryImmune:CarotConverted                  0.31881  0.09434  0.55508   1000.0 0.012 *
#   CategoryOxidative:CarotConverted               0.08194 -0.53372  0.75162   1000.0 0.824  
# CategoryParental/Reproduction:CarotConverted   0.35361  0.09172  0.66097   1000.0 0.018 *
#   CategoryCondition:CarotDietary                 0.09672 -0.19545  0.33885   1000.0 0.378  
# CategoryImmune:CarotDietary                    0.02012 -0.19559  0.26759    592.5 0.864  
# CategoryOxidative:CarotDietary                 0.23630 -0.10725  0.52630   1000.0 0.130  
# CategoryParental/Reproduction:CarotDietary     0.10334 -0.11561  0.36005    790.8 0.306  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

##########################################################################################
######################  Immune Split from Oxidative ############################


Ox.Data = read.csv("Ox split immune data.csv", header = T, stringsAsFactors = F)
head(Ox.Data)
str(Ox.Data)

# Organizing data:
Ox.Data$Carot <- as.factor(Ox.Data$Carot)
Ox.Data$Author <- as.factor(Ox.Data$Author)
Ox.Data$Species <- as.factor(Ox.Data$Species)
Ox.Data$animal <- as.factor(Ox.Data$animal)
Ox.Data$Category <- as.factor(Ox.Data$Category)
Ox.Data$Color.Variable <- as.factor(Ox.Data$Color.Variable)
Ox.Data$Sex <- as.factor(Ox.Data$Sex)

# Creating weight for Zr effect size:
Ox.Data$wi <- Ox.Data$Sample.Size - 3


############################################
### Covariance matrix among effect sizes ###
############################################
# create square matrix matching N of ES, filled with zeros

vc_matrixA.2 <- matrix(0,nrow = dim(Ox.Data)[1],ncol = dim(Ox.Data)[1])

Ox.Data$EffectID<-as.factor(1:length(Ox.Data$ID))

# Naming matrix rows and columns by Effect Size ID:
rownames(vc_matrixA.2) <- Ox.Data$EffectID
colnames(vc_matrixA.2) <- Ox.Data$EffectID 

# Find start and end coordinates for the subsets based on same study:
shared_coord <- which(Ox.Data$ExpPop %in% Ox.Data$ExpPop[duplicated(Ox.Data$ExpPop)]==TRUE)
shared_coord

# Matrix of combinations of coordinates for each study with shared effect sizes:
combinations <- do.call("rbind", tapply(shared_coord, Ox.Data[shared_coord,"ExpPop"], function(x) t(combn(x,2))))
combinations

# Calculate covariance values between effect sizes from the same study at the positions in shared_list and place them on the matrix. "SE" is the SD of estimate, so that the covariance is r[corr coefficient] * SD * SD. We are assuming that effect sizes from the same study have a correlation of 0.5. If the correlation is 0, then we can model without this matrix. If r = 1, then we should collapse the related data points:

for (i in 1:dim(combinations)[1]){
  p1 <- combinations[i,1]
  p2 <- combinations[i,2]
  p1_p2_cov <- 0.5*Ox.Data[p1,"SE"] * Ox.Data[p2,"SE"]
  vc_matrixA.2[p1,p2] <- p1_p2_cov
  vc_matrixA.2[p2,p1] <- p1_p2_cov
}

# add the diagonal - use "Variance"
#created variance-covariance matrix
diag(vc_matrixA.2) <- Ox.Data$Variance
head(vc_matrixA.2) 

is.positive.definite(vc_matrixA.2)
#[1] TRUE

# you could save this if you like
save(vc_matrixA.2,file="vc_matrixA.2.RData")
load("vc_matrixA.2.RData")

# Prepare for MCMCglmm:
AinvGA <- solve(vc_matrixA.2)
AinvGA <- as(AinvGA,"dgCMatrix") 
str(AinvGA)



##############################################################################################
############ Model with parasite, oxidative, and immune separated. Passerines Only, effect sizes correlated
#############################################################################################

mc.start.9_ox <- MCMCglmm(Z.transf~ Category:Carot - 1,
                          data = Ox.Data,
                          random = ~animal + Species + Author + EffectID,
                          ginverse = list(animal=invA$Ainv, EffectID=AinvGA),
                          prior = prior,
                          nitt = 1000, 
                          burnin = 0, 
                          thin = 1,
                          pl = T,
                          verbose = F)

summary(mc.start.9_ox)

mphylMCMC.9_ox <- mc.start.9_ox



for(i in 1:length(pass.tree)){
  
  invA <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.9_ox$Liab[1,], R =mphylMCMC.9_ox$VCV[1,1], G = list(G1=mphylMCMC.9_ox$VCV[1,2], G2=mphylMCMC.9_ox$VCV[1,3], G3=mphylMCMC.9_ox$VCV[1,4], G4=mphylMCMC.9_ox$VCV[1,5]))
  
  mphylMCMC.9_ox <- MCMCglmm(Z.transf~Category:Carot - 1,
                             data = Ox.Data,
                             random = ~animal + Species + Author + EffectID,
                             ginverse = list(animal=invA$Ainv, EffectID=AinvGA),
                             prior = prior,
                             nitt = 1000, 
                             burnin = 999, 
                             thin = 1,
                             start = start,
                             pl = T,
                             verbose = F)
  
  if(i>300){ 
    mc.start.9_ox$VCV[i-300,]<-mphylMCMC.9_ox$VCV[1,]
    mc.start.9_ox$Sol[i-300,]<-mphylMCMC.9_ox$Sol[1,]
    mc.start.9_ox$Liab[i-300,]<-mphylMCMC.9_ox$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.9_ox)

# 
# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -22.95713 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.06377 8.729e-08   0.1003     1000
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01156 9.432e-10   0.0466    297.9
# 
# ~Author
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Author   0.02025 5.035e-08  0.04669    30.18
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3429  0.04911        1    2.017
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05183  0.02527  0.07335    3.226
# 
# Location effects: Z.transf ~ Category:Carot - 1 
# 
# post.mean  l-95% CI  u-95% CI eff.samp pMCMC  
# CategoryCondition:CarotConverted              0.077725 -0.238385  0.347682   1000.0 0.562  
# CategoryImmune:CarotConverted                 0.095474 -0.205007  0.420169   1000.0 0.478  
# CategoryOxidative:CarotConverted              0.107655 -0.515774  0.724251   1000.0 0.748  
# CategoryParasite:CarotConverted               0.437939  0.173215  0.750596   1000.0 0.014 *
# CategoryParental/Reproduction:CarotConverted  0.333549  0.011287  0.647277   1000.0 0.048 *
# CategoryCondition:CarotDietary                0.101476 -0.196321  0.397650   1000.0 0.458  
# CategoryImmune:CarotDietary                   0.044895 -0.285937  0.359493   1000.0 0.748  
# CategoryOxidative:CarotDietary                0.221911 -0.116100  0.592585   1000.0 0.182  
# CategoryParasite:CarotDietary                 0.002566 -0.256272  0.297976    900.6 0.994  
# CategoryParental/Reproduction:CarotDietary    0.089241 -0.210574  0.357996   1000.0 0.438 


#################################################################################
############################## The effect of sex on effect size estimates ######
####################################################################################


contrasts(pass.dat$Carot) <- contr.treatment(levels(pass.dat$Carot), base = 2)

pass.dat$Sex <- relevel(pass.dat$Sex, ref = "M")

mc.start.20_pass <- MCMCglmm(Z.transf~ Carot * Sex,
                        data = pass.dat, 
                        random = ~animal + Species + Author + EffectID,
                        ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                        prior = prior,
                        nitt = 1000, 
                        burnin = 0, 
                        thin = 1,
                        pl = T,
                        verbose = F)

summary(mc.start.20_pass)


mphylMCMC.20_pass <- mc.start.20_pass





for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.20_pass$Liab[1,], R =mphylMCMC.20_pass$VCV[1,1], G = list(G1=mphylMCMC.20_pass$VCV[1,2], G2=mphylMCMC.20_pass$VCV[1,3], G3=mphylMCMC.20_pass$VCV[1,4], G4=mphylMCMC.20_pass$VCV[1,5]))
  
  mphylMCMC.20_pass <- MCMCglmm(Z.transf~ Carot * Sex,
                           data = pass.dat,
                           random = ~animal + Species + Author + EffectID,
                           ginverse = list(animal=invB$Ainv, EffectID=AinvGA),
                           prior = prior,
                           nitt = 1000, 
                           burnin = 999, 
                           thin = 1,
                           start = start,
                           pl = T,
                           verbose = F)
  
  if(i>300){ 
    mc.start.20_pass$VCV[i-300,]<-mphylMCMC.20_pass$VCV[1,]
    mc.start.20_pass$Sol[i-300,]<-mphylMCMC.20_pass$Sol[1,]
    mc.start.20_pass$Liab[i-300,]<-mphylMCMC.20_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.20_pass)

#########################################################################
######################## Converted Male as baseline ####################

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: 43.24995 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal    0.0224 2.922e-09  0.07746    677.3
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01296 1.851e-08  0.04502    274.1
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.05834   0.0216  0.09951    750.8
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3436  0.05083        1    1.992
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05663  0.03499  0.07424    20.81
# 
# Location effects: Z.transf ~ Carot * Sex 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# (Intercept)            0.25113  0.03249  0.52189    880.8 0.044 *
#   CarotDietary          -0.10435 -0.33548  0.16522   1000.0 0.392  
# SexBoth                0.08471 -0.51019  0.73094    960.5 0.800  
# SexF                   0.10103 -0.07846  0.29449   1000.0 0.276  
# CarotDietary:SexBoth  -0.25792 -0.87708  0.40633    937.8 0.410  
# CarotDietary:SexF     -0.08750 -0.33620  0.13440   1000.0 0.464  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


########################################################################################
######################### Dietary Male as baseline ###################################


# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: 47.07863 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.09698 1.388e-07  0.08465     1000
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01149 1.232e-08  0.04135     1000
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.05703  0.02265  0.09864    747.5
# 
# ~EffectID
# 
# post.mean l-95% CI u-95% CI eff.samp
# EffectID    0.3436  0.05015        1    1.982
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.05749  0.03748  0.07593    24.93
# 
# Location effects: Z.transf ~ Carot * Sex 
# 
# post.mean  l-95% CI  u-95% CI eff.samp pMCMC
# (Intercept)             0.152945 -0.120056  0.399400   1000.0 0.226
# CarotConverted          0.100703 -0.126370  0.395352   1000.0 0.406
# SexF                    0.008555 -0.140245  0.170171    847.8 0.934
# SexBoth                -0.172165 -0.391642  0.059954    815.5 0.154
# CarotConverted:SexF     0.086097 -0.176962  0.306320    842.7 0.486
# CarotConverted:SexBoth  0.260407 -0.310638  1.039737    677.3 0.402



############################################################################################
############################################################################################
###################  Creating Figures   ####################################################
############################################################################################


require(ggplot2)

gdat = read.csv("ggplotdat.pass.only.csv", header =T, stringsAsFactors=F)

gdat$invar<- (1/(1/(gdat$N-3)))

gdat$Category<- factor(gdat$Category, levels=c("Overall","Condition","Immune","Parasite","Reproduction"))
gdat$Carot<- factor(gdat$Carot, levels=c("Dietary","Converted","Combined"))



ggplot(gdat, aes(x=Carot))+
  geom_linerange(aes( ymin = LCL, ymax = UCL))+
  geom_point(aes(y=Estimate,color=factor(Carot), size= invar),shape =15) +
  scale_color_manual(values=c("Yellow2","Red2","Black")) +
  scale_size_continuous(range= c(4,20)) +
  xlab("")+ ylab(expression(Effect~Size~italic((Zr)))) +
  theme_bw()+
  geom_hline(aes(yintercept = 0),linetype = "dashed", lwd=1)+
  facet_grid(Category~.)+
  coord_flip()+
  theme(strip.text = element_text(size = 20),
        axis.text = element_text(size=16), axis.title = element_text(size=17)) +
  theme_bw() + theme(panel.grid.major = element_blank(),
                     panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))


##########################################################################
############### Plot of Species by Effect Size  #########################
#########################################################################

head(Data)
require(tidyverse)

Data$animal = as.character(Data$animal)

for(i in 1:nrow(Data)){
  x = strsplit(Data$animal[i], split = "_")
  Data$Genus[i] = x[[1]][1]
}

# plot species colored by genus
Data %>%
  group_by(Carot, Genus) %>%
  count(Species) %>%
  arrange(desc(Carot), Genus, Species) %>%
  ungroup() %>%
  mutate(ord = c(1:length(Species)),
         sp = factor(ord, labels = Species)) %>%
  ggplot(aes(x = sp, y = n, fill = Genus)) +
  geom_bar(stat = "identity") +
  scale_fill_viridis(discrete  = T)+
  theme_bw() + 
  ylab("Number of effect sizes") + xlab("Species") +
  theme(axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5, hjust =1),
        axis.text.y = element_text(size = 12),
        axis.title = element_text(size = 14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"))


# plot data colored by carot type
Data %>%
  group_by(Carot, Genus) %>%
  count(Species) %>%
  arrange(desc(Carot), Genus, Species) %>%
  ungroup() %>%
  mutate(ord = c(1:length(Species)),
         sp = factor(ord, labels = Species)) %>%
  ggplot(aes(x = sp, y = n, fill = Carot)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("red2", "yellow2"),
                    name = "Carotenoid Type") +  theme_bw() + 
  ylab("Number of effect sizes") + xlab("Species") +
  theme(axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5, hjust =1),
        axis.text.y = element_text(size = 12),
        axis.title = element_text(size = 14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"))

#############################
### Plot concensus tree #####
############################
contree1 <- consensus(pass.tree, p=0.8)

plot(contree1)

contree2 <- consensus(pass.tree, p=1)
plot(contree2)


contree3 <- consensus(pass.tree, p=0.5)
plot(contree3)

contree4 <- consensus(pass.tree)

tiff(file = "phylotree.pass.tiff", units = "in", width = 4, height = 11, res = 300)  
plot(contree4)
dev.off()

########################################################
###   plot number of effect sizes by species colored by carot type and in Phlyo tree order
#######################################################

Data %>%
  group_by(Phylo.Graph, Carot) %>%
  count(Species) %>%
  arrange(Phylo.Graph, Carot) %>%
  ungroup() %>%
  mutate(ord = c(1:length(Species)),
         sp = factor(ord, labels = Species)) %>%
  ggplot(aes(x = sp, y = n, fill = Carot)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = c("red2", "yellow2"),
                    name = "Carotenoid Type") +  theme_bw() + 
  ylab("Number of effect sizes") + xlab("Species") +
  theme(axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5, hjust =1),
        axis.text.y = element_text(size = 12),
        axis.title = element_text(size = 14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"))

##########################################################################################
#######    plot effect size for each species  colored by carot type and in Phlyo tree order
##########################################################################################

sdat = read.csv("SpeciesPlotData.csv", header =T, stringsAsFactors=F)

sdat$invar<- (1/(1/(sdat$N-3)))
head(sdat)
sdat$Carot<- factor(sdat$Carot, levels=c("Dietary","Converted"))


sdat %>%
  mutate(sp = factor(Phylo.Ord, labels = Species)) %>%
  ggplot(aes(x=sp))+
  geom_linerange(aes( ymin = lcl, ymax = ucl))+
  geom_point(aes(y=Zr,color=factor(Carot), size= invar),shape =15) +
  scale_size_continuous(range = c(4,15)) +
  scale_color_manual(values = c("red2", "yellow2"),
                     name = "Carotenoid Type") +  theme_bw() + 
  ylab("Effect Size (Zr)") + xlab("Species") +
  geom_hline(aes(yintercept = 0),linetype = "dashed", lwd=1)+
  theme(axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5, hjust =1),
        axis.text.y = element_text(size = 12),
        axis.title = element_text(size = 14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"))




# plot genus 
Data %>%
  group_by(Carot, Genus) %>%
  count(Species) %>%
  arrange(desc(Carot), Genus, Species) %>%
  ungroup() %>%
  mutate(ord = c(1:length(Species)),
         sp = factor(ord, labels = Species)) %>%
  ggplot(aes(x = sp, y = n, fill = Genus)) +
  geom_bar(stat = "identity") +
  scale_fill_viridis(discrete  = T)+
  theme_bw() + 
  ylab("Number of effect sizes") + xlab("Species") +
  theme(axis.text.x = element_text(size = 12, angle = 90, vjust = 0.5, hjust =1),
        axis.text.y = element_text(size = 12),
        axis.title = element_text(size = 14),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black"))



###################################################
####### Counting Species per Category ############

require(tidyverse)

ca = unique(Data$Carot)
ct = unique(Data$Category)

res = data.frame()
for(i in 1:length(ca)){
  for(j in 1:length(ct)){
    d = subset(Data, Carot == ca[i] & Category == ct[j])
    sp = length(unique(d$Species))
    
    df = data.frame(Carot = ca[i],
                    Category = ct[j],
                    n.sp = sp)
    res = rbind(res, df)
  }
}


########################################################################################
############# Models assuming effect sizes are Not correlated #########################
#######################################################################################


########################################################
### Model with overall effect
########################################################

mc.start1_pass <- MCMCglmm(Z.transf ~ 1,
                           data = pass.dat,
                           random = ~animal + Species + Author,
                           ginverse = list(animal=invB$Ainv),
                           mev = 1/pass.dat$wi,
                           prior = prior1,
                           nitt = 1000, 
                           burnin = 0, 
                           thin = 1,
                           pl = T,
                           pr = T,
                           verbose = F)

mphylMCMC1_pass <- mc.start1_pass



for(i in 1:length(pass.tree)){
  
  invB <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab = mphylMCMC1_pass$Liab[1,], R = mphylMCMC1_pass$VCV[1,1], G = list(G1=mphylMCMC1_pass$VCV[1,2], G2=mphylMCMC1_pass$VCV[1,3], G3=mphylMCMC1_pass$VCV[1,4]))
  
  mphylMCMC1_pass <- MCMCglmm(Z.transf ~ 1,
                              data = pass.dat,
                              random = ~ animal + Species + Author,
                              ginverse = list(animal=invB$Ainv),
                              mev = 1/pass.dat$wi,
                              prior = prior1,
                              nitt = 1000, 
                              burnin = 999, 
                              thin = 1,
                              start = start,
                              pl = T,
                              pr = T,
                              verbose = F)
  
  if(i>300){ 
    mc.start1_pass$VCV[i-300,]<-mphylMCMC1_pass$VCV[1,]
    mc.start1_pass$Sol[i-300,]<-mphylMCMC1_pass$Sol[1,]
    mc.start1_pass$Liab[i-300,]<-mphylMCMC1_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start1_pass)


# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -117.2541 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.02351 7.899e-09   0.0842    334.3
# 
# ~Species
# 
# post.mean l-95% CI u-95% CI eff.samp
# Species   0.01195 1.42e-07  0.04808    214.1
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03612  0.01051  0.06471    413.5
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.01769 0.006754    0.029    204.1
# 
# Location effects: Z.transf ~ 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# (Intercept)   0.17848 -0.03808  0.41417     1000 0.088 .
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


s2m.1_pass <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.1_pass <- mc.start1_pass$VCV[,"animal"] + mc.start1_pass$VCV[,"Species"] + mc.start1_pass$VCV[,"Author"] 

total.var.1_pass <- mc.start1_pass$VCV[,"animal"] + mc.start1_pass$VCV[,"Species"] + mc.start1_pass$VCV[,"Author"] + mc.start1_pass$VCV[,"units"] +s2m.1_pass

I2.1_pass<-100*(btw.study.var.1_pass)/(total.var.1_pass)


posterior.mode(I2.1_pass)
# var1 
# 66.86848

summary(I2.1_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 64.6738        10.1364         0.3205         0.5265 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 45.19 57.51 64.95 71.62 83.55


HPDinterval(I2.1_pass)

# lower    upper
# var1 45.15061 83.40505
# attr(,"Probability")
# [1] 0.95

#===
# MCMCglmm phylogenetic signal = lambda:
#===
I2.animal.1_pass <- 100*(mc.start1_pass$VCV[,"animal"]/total.var.1_pass)

posterior.mode(I2.animal.1_pass)
# var1 
# 0.3711767 

summary(I2.animal.1_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 17.9163        17.1573         0.5426         1.3608 
# 
# 2. Quantiles for each variable:
#   
#   2.5%      25%      50%      75%    97.5% 
# 0.07335  3.78286 12.19177 28.73383 57.83835


HPDinterval(I2.animal.1_pass)

# lower    upper
# var1 8.61676e-06 51.47404
# attr(,"Probability")
# [1] 0.95

#===
# I2 Species
#===
I2.species.1_pass <- 100*(mc.start1_pass$VCV[,"Species"]/total.var.1_pass)

posterior.mode(I2.species.1_pass)
# var1 
# 0.2003761

summary(I2.species.1_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 10.4886        12.5085         0.3956         0.9289 
# 
# 2. Quantiles for each variable:
#   
#   2.5%      25%      50%      75%    97.5% 
# 0.02395  1.31876  5.75227 14.81536 45.34363 

HPDinterval(I2.species.1_pass)
# 
# lower    upper
# var1 0.0001385823 38.23944
# attr(,"Probability")
# [1] 0.95

#===
# I2 Study
#===
I2.study.1_pass <- 100*(mc.start1_pass$VCV[,"Author"]/total.var.1_pass)

posterior.mode(I2.study.1_pass)

# var1 
# 35.36642 

summary(I2.study.1_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 36.2689        14.0311         0.4437         1.0621 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 10.68 26.09 35.53 45.77 64.14 


HPDinterval(I2.study.1_pass)

# lower    upper
# var1 9.624955 62.44123
# attr(,"Probability")
# [1] 0.95



##############################################################
###            Model with converted vs. dietary carotenoids:
##############################################################

mc.start.2_pass <- MCMCglmm(Z.transf~Carot - 1,
                       data = pass.dat,
                       random = ~animal + Species + Author,
                       ginverse = list(animal=invA$Ainv),
                       mev = 1/pass.dat$wi,
                       prior = prior1,
                       nitt = 1000, 
                       burnin = 0, 
                       thin = 1,
                       pl = T,
                       verbose = F)
summary(mc.start.2_pass)

mphylMCMC.2_pass <- mc.start.2_pass



for(i in 1:length(pass.tree)){
  
  invA <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.2_pass$Liab[1,], R =mphylMCMC.2_pass$VCV[1,1], G = list(G1=mphylMCMC.2_pass$VCV[1,2], G2=mphylMCMC.2_pass$VCV[1,3], G3=mphylMCMC.2_pass$VCV[1,4]))
  
  mphylMCMC.2_pass <- MCMCglmm(Z.transf~Carot - 1,
                          data = pass.dat,
                          random = ~animal + Species + Author,
                          ginverse = list(animal=invA$Ainv),
                          mev = 1/pass.dat$wi,
                          prior = prior1,
                          nitt = 1000, 
                          burnin = 999, 
                          thin = 1,
                          start = start,
                          pl = T,
                          verbose = F)
  
  if(i>300){ 
    mc.start.2_pass$VCV[i-300,]<-mphylMCMC.2_pass$VCV[1,]
    mc.start.2_pass$Sol[i-300,]<-mphylMCMC.2_pass$Sol[1,]
    mc.start.2_pass$Liab[i-300,]<-mphylMCMC.2_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.2_pass)

# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -109.96 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal    0.1025 6.074e-08  0.05956     1000
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01206 1.904e-09  0.04814    166.8
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03411 0.009806  0.06372    411.8
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.01811 0.007003  0.02996    357.3
# 
# Location effects: Z.transf ~ Carot - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# CarotConverted   0.25526  0.03010  0.50640     1095 0.046 *
#   CarotDietary     0.07788 -0.13410  0.31822     1000 0.362  
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


#===
# MCMCglmm I^2:
#===
s2m <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.2_pass <- mc.start.2_pass$VCV[,"animal"] + mc.start.2_pass$VCV[,"Species"] + mc.start.2_pass$VCV[,"Author"]

total.var.2_pass <- mc.start.2_pass$VCV[,"animal"] + mc.start.2_pass$VCV[,"Species"] + mc.start.2_pass$VCV[,"Author"] + mc.start.2_pass$VCV[,"units"] + s2m

I2.2_pass<-100*(btw.study.var.2_pass)/(total.var.2_pass)


posterior.mode(I2.2_pass)

# var1 
# 63.04606

summary(I2.2_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 61.2651        11.9555         0.3781         0.7218 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 37.45 53.60 61.66 69.39 82.41

HPDinterval(I2.2_pass)

# lower    upper
# var1 37.45729 82.68403
# attr(,"Probability")
# [1] 0.95


###########################################################################################
###     Overall Model with Category:
###########################################################################################

mc.start.6_pass <- MCMCglmm(Z.transf~ Category - 1,
                       data = pass.dat,
                       random = ~animal + Species + Author,
                       ginverse = list(animal=invA$Ainv),
                       mev = 1/pass.dat$wi,
                       prior = prior1,
                       nitt = 1000, 
                       burnin = 0, 
                       thin = 1,
                       pl = T,
                       verbose = F)


mphylMCMC.6_pass <- mc.start.6_pass



for(i in 1:length(pass.tree)){
  
  invA <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.6_pass$Liab[1,], R =mphylMCMC.6_pass$VCV[1,1], G = list(G1=mphylMCMC.6_pass$VCV[1,2], G2=mphylMCMC.6_pass$VCV[1,3], G3=mphylMCMC.6_pass$VCV[1,4]))
  
  mphylMCMC.6_pass <- MCMCglmm(Z.transf~Category - 1,
                          data = pass.dat,
                          random = ~animal + Species + Author,
                          ginverse = list(animal=invA$Ainv),
                          mev = 1/pass.dat$wi,
                          prior = prior1,
                          nitt = 1000, 
                          burnin = 999, 
                          thin = 1,
                          start = start,
                          pl = T,
                          verbose = F)
  
  if(i>300){ 
    mc.start.6_pass$VCV[i-300,]<-mphylMCMC.6_pass$VCV[1,]
    mc.start.6_pass$Sol[i-300,]<-mphylMCMC.6_pass$Sol[1,]
    mc.start.6_pass$Liab[i-300,]<-mphylMCMC.6_pass$Liab[1,]
  }
  
  print(i)  
}



hist(mc.start.6_pass$Liab)
hist(mc.start.6_pass$VCV[,1])
mean(mc.start.6_pass$VCV[,1])
HPDinterval(mc.start.6_pass$VCV[,1])


summary(mc.start.6_pass)

# 
# Iterations = 1:1000
# Thinning interval  = 1
# Sample size  = 1000 
# 
# DIC: -129.733 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal    0.0263 5.547e-06  0.09806    422.8
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01226 1.478e-08  0.04532    297.4
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.03488  0.01044  0.06292    478.1
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.01648    0.007  0.02906    318.2
# 
# Location effects: Z.transf ~ Category - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC  
# CategoryCondition               0.06893 -0.14799  0.32779    873.6 0.482  
# CategoryImmune                  0.14185 -0.07739  0.40637    916.5 0.170  
# CategoryParasite                0.23727 -0.02004  0.46697    884.6 0.060 .
# CategoryParental/Reproduction   0.22525 -0.02229  0.45101    907.6 0.066 .

#===
# MCMCglmm I^2:
#===
s2m <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.6_pass <- mc.start.6_pass$VCV[,"animal"] + mc.start.6_pass$VCV[,"Species"] + mc.start.6_pass$VCV[,"Author"]

total.var.6_pass <- mc.start.6_pass$VCV[,"animal"] + mc.start.6_pass$VCV[,"Species"] + mc.start.6_pass$VCV[,"Author"] + mc.start.6_pass$VCV[,"units"] + s2m

I2.6_pass<-100*(btw.study.var.6_pass)/(total.var.6_pass)


posterior.mode(I2.6_pass)

# var1 
# 66.65274

summary(I2.6_pass)

# Iterations = 1:1000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 1000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 66.2701        10.1267         0.3202         0.4995 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 44.86 59.47 66.58 73.02 84.61


HPDinterval(I2.6_pass)

# lower    upper
# var1 48.14886 86.66289
# attr(,"Probability")
# [1] 0.95

###########################################################################################
###     Model with Category and type of Carotenoid:
###########################################################################################

mc.start.8_pass <- MCMCglmm(Z.transf~ Category:Carot - 1,
                       data = pass.dat,
                       random = ~animal + Species + Author,
                       ginverse = list(animal=invA$Ainv),
                       mev = 1/pass.dat$wi,
                       prior = prior1,
                       nitt = 3000, 
                       burnin = 0, 
                       thin = 1,
                       pl = T,
                       verbose = F)

mphylMCMC.8_pass <- mc.start.8_pass



for(i in 1:length(pass.tree)){
  
  invA <- inverseA(pass.tree[[i]], nodes = "TIPS")
  
  start <- list(Liab=mphylMCMC.8_pass$Liab[1,], R =mphylMCMC.8_pass$VCV[1,1], G = list(G1=mphylMCMC.8_pass$VCV[1,2], G2=mphylMCMC.8_pass$VCV[1,3], G3=mphylMCMC.8_pass$VCV[1,4]))
  
  mphylMCMC.8_pass <- MCMCglmm(Z.transf~Category:Carot - 1,
                          data = pass.dat,
                          random = ~animal + Species + Author,
                          ginverse = list(animal=invA$Ainv),
                          mev = 1/pass.dat$wi,
                          prior = prior1,
                          nitt = 3000, 
                          burnin = 2999, 
                          thin = 1,
                          start = start,
                          pl = T,
                          verbose = F)
  
  if(i>300){ 
    mc.start.8_pass$VCV[i-300,]<-mphylMCMC.8_pass$VCV[1,]
    mc.start.8_pass$Sol[i-300,]<-mphylMCMC.8_pass$Sol[1,]
    mc.start.8_pass$Liab[i-300,]<-mphylMCMC.8_pass$Liab[1,]
  }
  
  print(i)  
}


summary(mc.start.8_pass)

# Iterations = 1:3000
# Thinning interval  = 1
# Sample size  = 3000 
# 
# DIC: -118.6808 
# 
# G-structure:  ~animal
# 
# post.mean  l-95% CI u-95% CI eff.samp
# animal   0.02708 5.882e-10  0.09942     89.6
# 
# ~Species
# 
# post.mean  l-95% CI u-95% CI eff.samp
# Species   0.01003 2.295e-10    0.038    291.8
# 
# ~Author
# 
# post.mean l-95% CI u-95% CI eff.samp
# Author   0.02106 0.005048  0.04171      494
# 
# R-structure:  ~units
# 
# post.mean l-95% CI u-95% CI eff.samp
# units   0.01757 0.006983    0.029    181.5
# 
# Location effects: Z.transf ~ Category:Carot - 1 
# 
# post.mean l-95% CI u-95% CI eff.samp pMCMC   
# CategoryCondition:CarotConverted               0.10364 -0.16058  0.39035     3512 0.373   
# CategoryImmune:CarotConverted                  0.13343 -0.16150  0.41359     3000 0.291   
# CategoryParasite:CarotConverted                0.42263  0.13460  0.68851     2821 0.008 **
# CategoryParental/Reproduction:CarotConverted   0.36777  0.06685  0.67678     2957 0.028 * 
# CategoryCondition:CarotDietary                 0.10604 -0.16292  0.38526     3000 0.380   
# CategoryImmune:CarotDietary                    0.12906 -0.15362  0.38447     2901 0.267   
# CategoryParasite:CarotDietary                  0.02994 -0.25576  0.27598     3006 0.789   
# CategoryParental/Reproduction:CarotDietary     0.08649 -0.14654  0.36497     3363 0.428   
# ---
#   Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


hist(mc.start.8_pass$Liab)
hist(mc.start.8_pass$VCV[,1])
mean(mc.start.8_pass$VCV[,1])
HPDinterval(mc.start.8_pass$VCV[,1])


#===
# MCMCglmm I^2:
#===
s2m <- sum(pass.dat$wi*(length(pass.dat$wi)-1))/(sum(pass.dat$wi)^2-sum(pass.dat$wi^2)) 

btw.study.var.8_pass <- mc.start.8_pass$VCV[,"animal"] + mc.start.8_pass$VCV[,"Species"] + mc.start.8_pass$VCV[,"Author"]

total.var.8_pass <- mc.start.8_pass$VCV[,"animal"] + mc.start.8_pass$VCV[,"Species"] + mc.start.8_pass$VCV[,"Author"] + mc.start.8_pass$VCV[,"units"] + s2m

I2.8_pass<-100*(btw.study.var.8_pass)/(total.var.8_pass)


posterior.mode(I2.8_pass)

# var1 
# 56.94887

summary(I2.8_pass)

# Iterations = 1:3000
# Thinning interval = 1 
# Number of chains = 1 
# Sample size per chain = 3000 
# 
# 1. Empirical mean and standard deviation for each variable,
# plus standard error of the mean:
#   
#   Mean             SD       Naive SE Time-series SE 
# 57.906         14.568          0.266          1.630 
# 
# 2. Quantiles for each variable:
#   
#   2.5%   25%   50%   75% 97.5% 
# 28.03 48.03 58.07 68.58 84.94

HPDinterval(I2.8_pass)
# lower    upper
# var1 30.29974 86.32168
# attr(,"Probability")
# [1] 0.95