####################################################################################
# Annotated code for Farquharson, Hogg, Grueber (submitted to Nat Comm August 2017) "A meta-analysis of birth-origin 
# effects on reproduction in diverse captive environments"
# This code written by Katherine Farquharson, The University of Sydney, 2017
# Some code adapted from:
# Winter (2013) rotl tutorial: https://cran.r-project.org/web/packages/rotl/vignettes/data_mashups.html
# Moatt et al. (2016): http://dx.doi.org/10.5061/dryad.3fc02
# Kamiya et al. (2014): https://datadryad.org/bitstream/handle/10255/dryad.71107/R%20code.R?sequence=1
####################################################################################

rm(list=ls())
##Load packages
library(rotl)
library(Hmisc)
library(MCMCglmm)
library(metafor)
library(ape)
library(mice)
library(lattice)
library(HDInterval)

############################
## Calculate effect sizes ##
############################
es <- read.csv('data file.csv')
#use log odds ratio as effect size (with captive-born input as control, wild-born as treatment)

#two kinds of data - continuous (mean, sd/SEM & N), and proportional (n/N)
#for proportional data
es.proportional <- subset(es, (!is.na(es$WB.n1)))
lnor.proportional <- escalc(measure="OR", ai=es.proportional$CB.success, bi=es.proportional$CB.failure, 
                            ci=es.proportional$WB.success, di=es.proportional$WB.failure, 
                            n1i=es.proportional$CB.N, n2i=es.proportional$WB.N, vtype='UB', add=0.5, 
                            to = 'only0', drop00=FALSE)
es.proportional$yi <- lnor.proportional$yi
es.proportional$vi <- lnor.proportional$vi

#for continuous data
es.continuous <- subset(es, (!is.na(es$WB.Mean)))
colnames(es.continuous)
lnor.continuous <- escalc(measure='D2ORN', m1i=es.continuous$CB.C.Mean, m2i=es.continuous$WB.C.Mean,
                          sd1i=es.continuous$CB.SD, sd2i=es.continuous$WB.SD, n1i=es.continuous$CB.N, 
                          n2i=es.continuous$WB.N, vtype='UB')
es.continuous$yi <- lnor.continuous$yi
es.continuous$vi <- lnor.continuous$vi

es <- rbind(es.proportional, es.continuous)

#############################
##Create phylogenetic tree ##
#############################
es$Scientific.name
es$Scientific.name <- as.character(es$Scientific.name)

#change species names in es to match those of rotl tree
es$Scientific.name[es$Scientific.name == "Cersus eldi thamin"] <- "Rucervus eldii"
es$Scientific.name[es$Scientific.name == "Choreopsis liberiensis"] <- "Hexaprotodon liberiensis"
es$Scientific.name[es$Scientific.name == "Clethrionymus glareolus"] <- "Myodes glareolus"
es$Scientific.name[es$Scientific.name == "Equus burchelli"] <- "Equus burchelii"
es$Scientific.name[es$Scientific.name == "Fenneropenaeus merguiensis"] <- "Penaeus merguiensis"
es$Scientific.name[es$Scientific.name == "Gorilla gorilla gorilla"] <- "Gorilla gorilla"
es$Scientific.name[es$Scientific.name == "Pan troglodytes"] <- "Pan troglodytes troglodytes"
es$Scientific.name[es$Scientific.name == "Saguinus fuscicollis illigeri"] <- "Saguinus fuscicollis"
es$Scientific.name[es$Scientific.name == "Eulemur mongoz, formerly Lemur mongoz "] <- "Eulemur mongoz"
species <- unique(es$Scientific.name)
species <- as.data.frame(species)

species[,1] <- as.character(species[,1])
#Add outgroup (box jellyfish) to root tree
outgroup <- 'Chironex fleckeri' 
species[45,1] <- outgroup

taxa <- tnrs_match_names(names=species[,1], context_name = "All life")
tr <- tol_induced_subtree(taxa$ott_id)
taxon_map <- structure(taxa$search_string, names=as.character(taxa$unique_name))

#tree contains node labels for nodes that match a higher taxonomic group
#remove extra information from tip labels:
tr$tip.label
otl_tips <- strip_ott_ids(tr$tip.label, remove_underscores = TRUE)
tr$tip.label

#map names to tree
tr$tip.label <- taxon_map[otl_tips]
tr$tip.label <- capitalize(tr$tip.label)

#remove node labels
any(duplicated(tr$node.label))
tr$node.label <- NULL

###############################
### Phylogenetic VCV matrix ###
###############################

#rename column to 'animal' for input to MCMCglmm
es$animal <- es$Scientific.name

#compute branch lengths using ape package default based on topology
CorMatrix <- vcv(compute.brlen(tr, corr = T))

#match matrix to dataset
CorExt <- as.matrix(CorMatrix[match(es$animal, rownames(CorMatrix)), match(es$animal, colnames(CorMatrix))])
levelplot(CorMatrix, xlab = '', ylab = 'Species')

#remove outgroup from CorMatrix
CorMatrix1 <- CorMatrix[-45, -45]
levelplot(CorMatrix1)

#MCMCglmm requires inverse matrix for input
Cinv <- solve(CorMatrix1)
Cinv2 <- as(Cinv, "dgCMatrix")

##################################
## Meta-analysis: overall model ##
##################################

#MCMCglmm also requires variances as input - we have no random structure specified for variances
MEV <- es$vi

prior <- list(R=list(V=1,nu=0.002),G=list(G1=list(V=1, nu=0.002)))

#model will take a few minutes to run
o.model <- MCMCglmm(yi ~ 1, random = ~ ID, mev = MEV, data = es, verbose=T, nitt=5000000,
                   thin=3000, burnin=150000, prior=prior, pr=T)

#results of all models may vary slightly from reported results (iterative Bayesian models)
summary(o.model)

#model diagnostics
effectiveSize(o.model$Sol) # >1000
effectiveSize(o.model$VCV) # >1000
autocorr.diag(o.model$VCV) #all below 0.1
plot(o.model$Sol[,1])
plot(o.model$VCV) #convergence looks good
heidel.diag(o.model$VCV) #all passed

#run same model again 2x to check convergence of results (Gelman-Rubin statistic < 1.1)
o.model_1 <- MCMCglmm(yi ~ 1, random = ~ ID, mev = MEV, data = es, verbose=T, nitt=5000000,
                     thin=3000, burnin=150000, prior=prior, pr=T)
o.model_2 <- MCMCglmm(yi ~ 1, random = ~ ID, mev = MEV, data = es, verbose=T, nitt=5000000,
                     thin=3000, burnin=150000, prior=prior, pr=T)
summary(o.model_1)
summary(o.model_2)

gelman.diag(mcmc.list(o.model$Sol, o.model_1$Sol, o.model_2$Sol)) #all < 1.1
o.model$DIC
o.model_1$DIC #use lowest DIC - o.model_1 in our case (though all are very similar)
o.model_2$DIC

################################################
### Meta-analysis: Overall model + phylogeny ###
################################################

prior.phylo <- list(R=list(V=1,nu=0.002),G=list(G1=list(V=1, nu=0.002), G2=list(V=1, nu=0.002)))

o.modelphylo <- MCMCglmm(yi ~ 1, random = ~animal + ID, mev = MEV, data = es, verbose=T,
                   nitt=5000000, thin=3000, burnin=150000, prior=prior.phylo, pr=T, 
                   ginverse=list(animal = Cinv2))
summary(o.modelphylo)

#model diagnostics:
effectiveSize(o.modelphylo$Sol) # >1000
effectiveSize(o.modelphylo$VCV) #>1000
autocorr.diag(o.modelphylo$VCV) #all below 0.1
plot(o.modelphylo$Sol[,1])
plot(o.modelphylo$VCV)
heidel.diag(o.modelphylo$VCV) #all passed

#run same model again 2x to check convergence of results (Gelman-Rubin statistic < 1.1)
o.modelphylo_1 <- MCMCglmm(yi ~ 1, random = ~animal + ID, mev = MEV, data = es, verbose=T, 
                     nitt=5000000, thin=3000, burnin=150000, prior=prior.phylo, pr=T, 
                     ginverse=list(animal = Cinv2))
o.modelphylo_2 <- MCMCglmm(yi ~ 1, random = ~animal + ID, mev = MEV, data = es, verbose=T, 
                     nitt=5000000, thin=3000, burnin=150000, prior=prior.phylo, pr=T, 
                     ginverse=list(animal = Cinv2))
summary(o.modelphylo_1)
summary(o.modelphylo_2)

o.modelphylo$DIC #317.6251
o.modelphylo_1$DIC #317.5601
o.modelphylo_2$DIC #317.5375 <- lowest DIC

gelman.diag(mcmc.list(o.modelphylo$Sol, o.modelphylo_1$Sol, o.modelphylo_2$Sol)) #all <1.1

############################################################
### Comparing overall model to overall model + phylogeny ###
############################################################

summary(o.model_1)$DIC #317.3776
summary(o.modelphylo_2)$DIC #317.5375
#the non-phylogenetic model has a slightly lower DIC so is the better model

## Heterogeneity statistics 
#for multilevel meta-analysis, extended heterogeneity statistic suggested (Nakagawa)

k <- 115 #number of effect sizes
#sampling error:
s2m <- sum(1/es$vi) * (k-1) / (sum(1/es$vi)^2 - sum((1/es$vi)^2))

#For overall model (without phylogeny)
s2t <- o.model_1$VCV[,"ID"]+o.model_1$VCV[,"units"]+s2m
#total heterogeneity:
I2t <- 100* ((o.model_1$VCV[,"units"]+o.model_1$VCV[,"ID"])/s2t)
posterior.mode(I2t)
#study ID heterogeneity:
I2s <- 100* ((o.model_1$VCV[,"ID"])/s2t)
posterior.mode(I2s)
#residual variance
I2r <- 100* ((o.model_1$VCV[,"units"])/s2t)
posterior.mode(I2r) #19.3%

#For overall model + phylogeny
#total variance:
s2t.p <- o.modelphylo_2$VCV[,"animal"]+o.modelphylo_2$VCV[,"ID"]+o.modelphylo_2$VCV[,"units"]+s2m
#total heterogeneity:
I2t.p <- 100* ((o.modelphylo_2$VCV[,"units"]+o.modelphylo_2$VCV[,"animal"]+o.modelphylo_2$VCV[,"ID"])/s2t.p)
posterior.mode(I2t.p)
#phylogeny heterogeneity:
I2p.p <- 100* ((o.modelphylo_2$VCV[,"animal"])/s2t.p)
posterior.mode(I2p.p)
HPDinterval(I2p.p)
#study ID heterogeneity:
I2s.p <- 100* ((o.modelphylo_2$VCV[,"ID"])/s2t.p)
posterior.mode(I2s.p)
#residual variance:
I2r.p <- 100* ((o.modelphylo_2$VCV[,"units"])/s2t.p)
posterior.mode(I2r.p) #24.2%

##Calculate phylogenetic heritability (lamda, phylogenetic signal)
lamda <- o.modelphylo_2$VCV[,"animal"]/
  (o.modelphylo_2$VCV[,"animal"] + o.modelphylo_2$VCV[,"ID"] + o.modelphylo_2$VCV[,'units'])
posterior.mode(lamda)

#Heterogeneity is high in both models
#Phylogenetic signal is low, and DIC is lower in non-phylogenetic model
#Proceed with non-phylogenetic meta-regression

#############################################
### Meta-regression: Captive Environment  ###
#############################################

mr.model.ce <- MCMCglmm(yi ~ factor(Captive.environment)-1, random = ~ ID, mev = MEV, data = es,
                   verbose=T, nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.ce)

#model diagnostics:
effectiveSize(mr.model.ce$Sol) # >1000
effectiveSize(mr.model.ce$VCV) #>1000
autocorr.diag(mr.model.ce$VCV) #all below 0.1
plot(mr.model.ce$Sol[,1])
plot(mr.model.ce$VCV)
heidel.diag(mr.model.ce$VCV) #all passed

#run same model again 2x to check convergence of results (Gelman-Rubin statistic < 1.1)
mr.model.ce_1 <- MCMCglmm(yi ~ factor(Captive.environment)-1, random = ~ ID, mev = MEV, data = es,
                     verbose=T, nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
mr.model.ce_2 <- MCMCglmm(yi ~ factor(Captive.environment)-1, random = ~ ID, mev = MEV, data = es,
                     verbose=T, nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.ce_1)
summary(mr.model.ce_2)

mr.model.ce$DIC #317.0837
mr.model.ce_1$DIC #317.0486
mr.model.ce_2$DIC #317.0434 <- lowest DIC model

gelman.diag(mcmc.list(mr.model.ce$Sol, mr.model.ce_1$Sol, mr.model.ce_2$Sol)) #all < 1.1

####################################
### Meta-regression - Trait type ###
####################################

mr.model.t <- MCMCglmm(yi ~ factor(Trait)-1, random = ~ ID, mev = MEV, data = es, verbose=T, 
                   nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.t)

#model diagnostics:
effectiveSize(mr.model.t$Sol) # >1000
effectiveSize(mr.model.t$VCV) #>1000
autocorr.diag(mr.model.t$VCV) #all below 0.1
plot(mr.model.t$Sol[,1])
plot(mr.model.t$VCV)
heidel.diag(mr.model.t$VCV) #all passed

#run same model again 2x to check convergence of results (Gelman-Rubin statistic < 1.1)
mr.model.t_1 <- MCMCglmm(yi ~ factor(Trait)-1, random = ~ ID, mev = MEV, data = es, 
                     verbose=T, nitt=5000000, thin=3000,burnin=150000, prior=prior, pr=T)
mr.model.t_2 <- MCMCglmm(yi ~ factor(Trait)-1, random = ~ ID, mev = MEV, data = es, 
                     verbose=T, nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.t_1)
summary(mr.model.t_2)

mr.model.t$DIC #286.5063
mr.model.t_1$DIC #286.5062 <- lowest DIC
mr.model.t_2$DIC #286.5142

gelman.diag(mcmc.list(mr.model.t$Sol, mr.model.t_1$Sol, mr.model.t_2$Sol)) #all < 1.1

####################################
### Measures of publication bias ###
####################################

##Time-lag bias
#meta-regression with year of publication to see if effect sizes change over time
mr.model.y <- MCMCglmm(yi ~ Year, random = ~ID, mev = MEV, data = es, verbose=T, nitt=5000000, 
                   thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.y)

#model diagnostics:
effectiveSize(mr.model.y$Sol) # >1000
effectiveSize(mr.model.y$VCV) #>1000
autocorr.diag(mr.model.y$VCV) #all below 0.1
plot(mr.model.y$Sol[,1])
plot(mr.model.y$VCV)
heidel.diag(mr.model.y$VCV) #all passed

#run same model again 2x to check convergence of results (Gelman-Rubin statistic < 1.1)
mr.model.y_1 <- MCMCglmm(yi ~ Year, random = ~ID, mev = MEV, data = es, verbose=T, 
                     nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
mr.model.y_2 <- MCMCglmm(yi ~ Year, random = ~ID, mev = MEV, data = es, verbose=T, 
                     nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.y_1)
summary(mr.model.y_2)

gelman.diag(mcmc.list(mr.model.y$Sol, mr.model.y_1$Sol, mr.model.y_2$Sol)) #all < 1.1
#year is not significant - no evidence of publication bias over time

mr.model.y$DIC #316.5641
mr.model.y_1$DIC #316.5887
mr.model.y_2$DIC #316.495 <-- lowest DIC

##Egger's regression 
#use meta-analytic residuals
#meta-analytic residuals = raw data - predictions
o.model_1$Random$formula <- update(o.model_1$Random$formula, ~.+leg(mev, -1, FALSE):units)
prediction <- predict(o.model_1, marginal= ~leg(mev, -1, FALSE):units)
precision <- sqrt(1/es$vi)
MR <- es$yi - prediction
zMR <- MR*precision
egger<-lm(zMR ~ precision)
summary(egger) 
#intercept is significant - evidence of possible publication bias (though correction is small)
summary(egger)$coefficients

##Funnel plot
graphics.off()
par(mfrow=c(1,2))
plot(es$yi, precision, xlab='Log odds ratio', ylab = 'Precision')
abline(v=posterior.mode(o.model_1$Sol)[1],lwd=1) #v is the meta-analytic mean
plot(MR, precision, xlab = 'Meta-analytic residuals', ylab = 'Precision')
abline(v=0,lwd=1,lty=2)

##Trim-and-fill analysis 
#for multi-level meta-analysis, can only be performed on meta-analytic residuals
#removes smaller studies causing funnel plot asymmetry,
#uses trimmed funnel plot to estimate the true centre of the funnel,  
#replaces omitted studies and their missing counterparts around the centre (filling)
model.tf <- rma(yi=MR,sei=1/precision)
summary(model.tf)
TFL <- trimfill(model.tf,side="left",estimator="R0")
TFR <- trimfill(model.tf, side='right', estimator = 'R0')
summary(TFL) #no studies estimated to be missing on left side
summary(TFR) #2 studies estimated to be missing on right side, but P = 0.125, estimate is small
graphics.off()
range(MR)
funnel(TFL,xlab="Meta-analytic residuals",xlim=c(-6,6))
funnel(TFR,xlab="Meta-analytic residuals",xlim=c(-6, 6))

#apparent outlier (with odds ratio = -10) could be affecting results
#this comes from ES.ID 75 (Murugan et al. 2013)

## Rerun all models without outlier 
es2 <- es[c(-90),]
MEV2 <- es2$vi

o.model_out <- MCMCglmm(yi ~ 1, random = ~ ID, mev = MEV2, data = es2, verbose=T, nitt=5000000,
                    thin=3000, burnin=150000, prior=prior, pr=T)
o.modelphylo_out <- MCMCglmm(yi ~ 1, random = ~animal + ID, mev = MEV2, data = es2, verbose=T,
                    nitt=5000000, thin=3000, burnin=150000, prior=prior.phylo, pr=T, 
                    ginverse=list(animal = Cinv2))
mr.model.ce_out <- MCMCglmm(yi ~ factor(Captive.environment)-1, random = ~ ID, mev = MEV2, 
                            data = es2, verbose=T, nitt=5000000, thin=3000, burnin=150000, 
                            prior=prior, pr=T)
mr.model.t_out <- MCMCglmm(yi ~ factor(Trait)-1, random = ~ ID, mev = MEV2, data = es2, 
                    verbose=T, nitt=5000000, thin=3000, burnin=150000, prior=prior, pr=T)

#compare models with & without outlier
summary(o.model)
summary(o.model_out)

summary(o.modelphylo)
summary(o.modelphylo_out) 

summary(mr.model.ce)
summary(mr.model.ce_out)

summary(mr.model.t)
summary(mr.model.t_out)
#qualitatively the same - does not alter conclusions

##Publication bias (with outlier removed)
##Time-lag bias
mr.model.y_out <- MCMCglmm(yi ~ Year, random = ~ID, mev = MEV2, data = es2, verbose=T, nitt=5000000, 
                       thin=3000, burnin=150000, prior=prior, pr=T)
summary(mr.model.y_out)

##Egger's regression 
o.model_out$Random$formula <- update(o.model_out$Random$formula, ~.+leg(mev, -1, FALSE):units)
prediction_out <- predict(o.model_out, marginal= ~leg(mev, -1, FALSE):units)
precision_out <- sqrt(1/es2$vi)
MR_out <- es2$yi - prediction_out
zMR_out <- MR_out*precision_out
egger_out <-lm(zMR_out ~ precision_out)
summary(egger_out) 
#intercept is significant, correction still small

##Funnel plot
graphics.off()
par(mfrow=c(1,2))
plot(es2$yi, precision_out, xlab='Log odds ratio', ylab = 'Precision')
abline(v=posterior.mode(o.model_out$Sol)[1],lwd=1) #v is the meta-analytic mean
plot(MR_out, precision_out, xlab = 'Meta-analytic residuals', ylab = 'Precision')
abline(v=0,lwd=2)

##Trim-and-fill analysis 
model.tf_out <- rma(yi=MR_out,sei=1/precision_out)
summary(model.tf_out)
TFL_out <- trimfill(model.tf_out,side="left",estimator="R0")
TFR_out <- trimfill(model.tf_out, side='right', estimator = 'R0')
summary(TFL_out) #no studies estimated to be missing on left side
summary(TFR_out) #now 0 studies are estimated to be missing on right side
graphics.off()
range(MR_out)
funnel(TFL_out,xlab="Meta-analytic residuals",xlim=c(-4,4))
funnel(TFR_out,xlab="Meta-analytic residuals",xlim=c(-4, 4))
#no substantial differences by excluding outlier

##MI to recover missing standard deviations (N = 17 additional comparisons)

complete <- read.csv('completecases.csv', header=T)
# as the data we are imputing is continuous (mean, sd, N) use this subset of data to form correlation matrix
#to impute data from
complete.c <- complete[49:115,]

#load missing data
missing <- read.csv('missing data imputation no variance without sample size.csv', header=T)
tail(missing)
colnames(complete.c)
colnames(missing)
combined <- rbind(complete.c, missing)
colnames(combined)

#using columns 27, 28, 31, 32 to impute missing data
#plot missing data using md.pattern (1 = observed, 0 = missing)
md.pattern(combined[, c(27, 28, 31, 32)]) #mean known for all,
#SD missing for 17 effect sizes.

#check correlations between variables - MI uses this matrix
cor(combined[,c(27, 28, 31, 32)], use = "pairwise.complete.obs")

#use log scale to impute data as relationship is not linear otherwise
plot(combined$CB.Mean, combined$CB.SD)
plot(log(combined$CB.Mean), log(combined$CB.SD))

plot(combined$WB.Mean, combined$WB.SD)
plot(log(combined$WB.Mean), log(combined$WB.SD))

#can't do log of negative numbers - identify negative values (direction of effect on reproductive success is negative)
CB.negatives <- which(combined$CB.C.Mean <0)
WB.negatives <- which(combined$WB.C.Mean <0)

which(combined$WB.SD == 0) #one WB.SD = 0, so can't be logged. Add 0.00001 (measurement is litter size) to this estimate?

combinedlog <- combined
combinedlog[66,28] <- 0.5
combinedlog$CB.C.Mean[CB.negatives] <- combined$CB.C.Mean[CB.negatives]*-1
combinedlog$WB.C.Mean[WB.negatives] <- combined$WB.C.Mean[WB.negatives]*-1

combinedlog$CB.C.Mean <- log(combinedlog$CB.C.Mean)
combinedlog$WB.C.Mean <- log(combinedlog$WB.C.Mean)
combinedlog$CB.SD <- log(combinedlog$CB.SD)
combinedlog$WB.SD <- log(combinedlog$WB.SD)
combinedlog$CB.N <- log(combinedlog$CB.N)
combinedlog$WB.N <- log(combinedlog$WB.N)

######################################################
### Multiple imputation (MI); creating 20 datasets ###
######################################################
#rerun all analyses with imputed data

#load missing data to be imputed
missing <- read.csv('data file 2.csv', header=T)
#17 comparisons have missing standard deviation, 24 have missing sample size

#reload original data (used above):
complete <- read.csv('data file.csv', header=T)
#as the data we are imputing is continuous (mean, sd, N) use this subset of data (continuous traits) to form correlation matrix
#to impute data from
complete.c <- complete[49:115,]

#impute missing standard deviations (N = 17 comparisons)
missing2 <- missing[!is.na(missing$WB.N),]
combined <- rbind(complete.c, missing2)

colnames(combined)
#using columns 19, 25, 27, 28, 31, 32 to impute missing data
#plot missing data using md.pattern (1 = observed, 0 = missing)
md.pattern(combined[, c(19, 25, 27, 28, 31, 32)]) #mean & N known for all, SD missing for 17

#check correlations between variables - MI uses this matrix
cor(combined[,c(19, 25, 27, 28, 31, 32)], use = "pairwise.complete.obs")

#use log scale to impute data as relationship is not linear otherwise
plot(combined$CB.Mean, combined$CB.SD)
plot(log(combined$CB.Mean), log(combined$CB.SD))
plot(combined$WB.Mean, combined$WB.SD)
plot(log(combined$WB.Mean), log(combined$WB.SD))
plot(combined$CB.Mean, combined$CB.N)
plot(log(combined$CB.Mean), log(combined$CB.N))
plot(combined$WB.Mean, combined$WB.N)
plot(log(combined$WB.Mean), log(combined$WB.N))

#can't do log of negative numbers - identify negative values (direction of effect on reproductive success is negative)
CB.negatives <- which(combined$CB.C.Mean <0)
WB.negatives <- which(combined$WB.C.Mean <0)

which(combined$WB.SD == 0) #one WB.SD = 0, so can't be logged. Add 0.5 (measurement is litter size) to this estimate

combinedlog <- combined
combinedlog[66,28] <- 0.5
combinedlog$CB.C.Mean[CB.negatives] <- combined$CB.C.Mean[CB.negatives]*-1
combinedlog$WB.C.Mean[WB.negatives] <- combined$WB.C.Mean[WB.negatives]*-1

combinedlog$CB.C.Mean <- log(combinedlog$CB.C.Mean)
combinedlog$WB.C.Mean <- log(combinedlog$WB.C.Mean)
combinedlog$CB.SD <- log(combinedlog$CB.SD)
combinedlog$WB.SD <- log(combinedlog$WB.SD)
combinedlog$CB.N <- log(combinedlog$CB.N)
combinedlog$WB.N <- log(combinedlog$WB.N)

#  multiple imputation (MI); creating 20 datasets
nos.log.Imp <- mice(combinedlog[,c(19, 25, 27, 28, 31, 32)], m = 20)

####check imputations (Imp)
names(nos.log.Imp)
nos.log.Imp$imp$WB.SD
nos.log.Imp$imp$CB.SD

#see if imputations seem reasonable given data:
stripplot(nos.log.Imp, pch = 20, cex = 1.2) #blue is observed values, red is imputed missing values
densityplot(nos.log.Imp)

#check convergence of imputations
plot(nos.log.Imp)

##Create function to backtransform, make negative values negative again (where direction
#of effect on reproductive success is negative), calculate effect sizes and run meta-analysis, 
#then run for each of 20 imputations and combine as one MCMClist

MImodel <- function(i) {
  data <- cbind(combinedlog[,1:13], combinedlog[,c(19, 25)], complete(nos.log.Imp, action = i))
  data$CB.C.Mean <- exp(data$CB.C.Mean)
  data$WB.C.Mean <- exp(data$WB.C.Mean)
  data$CB.SD <- exp(data$CB.SD)
  data$WB.SD <- exp(data$WB.SD)
  data$CB.N <- exp(data$CB.N)
  data$WB.N <- exp(data$WB.N)
  negs <- which(data$Direction == '-')
  data$WB.C.Mean[negs] <- data$WB.C.Mean[negs]*-1
  data$CB.C.Mean[negs] <- data$CB.C.Mean[negs]*-1
  lnor.continuous <- escalc(measure='D2ORN', m1i=data$CB.C.Mean, m2i=data$WB.C.Mean,
                            sd1i=data$CB.SD, sd2i=data$WB.SD, n1i=data$CB.N, 
                            n2i=data$WB.N, vtype='UB')
  data$yi <- lnor.continuous$yi
  data$vi <- lnor.continuous$vi
  data2 <- complete[1:48,]
  lnor.proportional <- escalc(measure="OR", ai=data2$CB.success, bi=data2$CB.failure, 
                              ci=data2$WB.success, di=data2$WB.failure, 
                              n1i=data2$CB.N, n2i=data2$WB.N, vtype='UB', add=0.5, 
                              to = 'only0', drop00=FALSE)
  data2$yi <- lnor.proportional$yi
  data2$vi <- lnor.proportional$vi
  data1 <- data[,c(1:13,22:23)]
  data3 <- data2[,c(1:13,34:35)]
  data4 <<- rbind(data1, data3)
  MEV <<- data4$vi
  prior <<- list(R=list(V=1,nu=0.002),G=list(G1=list(V=1, nu=0.002)))
}

o.model <- function(i) {
  MCMCglmm(yi ~ 1, random = ~ ID, mev = MEV, data = data4, verbose=T, nitt=5000000,
           thin=3000, burnin=150000, prior=prior, pr=T)
}

MImodel(1)
nos.log.model1 <- o.model(1)
MImodel(2)
nos.log.model2 <- o.model(2)
MImodel(3)
nos.log.model3 <- o.model(3)
MImodel(4)
nos.log.model4 <- o.model(4)
MImodel(5)
nos.log.model5 <- o.model(5)
MImodel(6)
nos.log.model6 <- o.model(6)
MImodel(7)
nos.log.model7 <- o.model(7)
MImodel(8)
nos.log.model8 <- o.model(8)
MImodel(9)
nos.log.model9 <- o.model(9)
MImodel(10)
nos.log.model10 <- o.model(10)
MImodel(11)
nos.log.model11 <- o.model(11)
MImodel(12)
nos.log.model12 <- o.model(12)
MImodel(13)
nos.log.model13 <- o.model(13)
MImodel(14)
nos.log.model14 <- o.model(14)
MImodel(15)
nos.log.model15 <- o.model(15)
MImodel(16)
nos.log.model16 <- o.model(16)
MImodel(17)
nos.log.model17 <- o.model(17)
MImodel(18)
nos.log.model18 <- o.model(18)
MImodel(19)
nos.log.model19 <- o.model(19)
MImodel(20)
nos.log.model20 <- o.model(20)

#VCV = variance components
nos.log.MI.comb.VCV <- mcmc.list(nos.log.model1$VCV, nos.log.model2$VCV, nos.log.model3$VCV, nos.log.model4$VCV, nos.log.model5$VCV, nos.log.model6$VCV, nos.log.model7$VCV,
                                 nos.log.model8$VCV, nos.log.model9$VCV, nos.log.model10$VCV, nos.log.model11$VCV, nos.log.model12$VCV, nos.log.model13$VCV,
                                 nos.log.model14$VCV, nos.log.model15$VCV, nos.log.model16$VCV, nos.log.model17$VCV, nos.log.model18$VCV, nos.log.model19$VCV,
                                 nos.log.model20$VCV)
summary(nos.log.MI.comb.VCV)

#Sol = solutions
nos.log.MI.comb.Sol <- mcmc.list(nos.log.model1$Sol, nos.log.model2$Sol, nos.log.model3$Sol, nos.log.model4$Sol, nos.log.model5$Sol, nos.log.model6$Sol, nos.log.model7$Sol, nos.log.model8$Sol,
                                 nos.log.model9$Sol, nos.log.model10$Sol, nos.log.model11$Sol, nos.log.model12$Sol, nos.log.model13$Sol, nos.log.model14$Sol, nos.log.model15$Sol, 
                                 nos.log.model16$Sol, nos.log.model17$Sol, nos.log.model18$Sol, nos.log.model19$Sol, nos.log.model20$Sol)
plot(mcmc.list(nos.log.model1$Sol[,1], nos.log.model2$Sol[,1], nos.log.model11$Sol[,1])) 
#check plot with different models for visual convergence

autocorr.diag(nos.log.MI.comb.VCV) #passes autocorrelation
heidel.diag(nos.log.MI.comb.VCV) #all passed

nos.log.MI.sol1 <- as.data.frame(nos.log.model1$Sol[,1])
nos.log.MI.sol2 <- as.data.frame(nos.log.model2$Sol[,1])
nos.log.MI.sol3 <- as.data.frame(nos.log.model3$Sol[,1])
nos.log.MI.sol4 <- as.data.frame(nos.log.model4$Sol[,1])
nos.log.MI.sol5 <- as.data.frame(nos.log.model5$Sol[,1])
nos.log.MI.sol6 <- as.data.frame(nos.log.model6$Sol[,1])
nos.log.MI.sol7 <- as.data.frame(nos.log.model7$Sol[,1])
nos.log.MI.sol8 <- as.data.frame(nos.log.model8$Sol[,1])
nos.log.MI.sol9 <- as.data.frame(nos.log.model9$Sol[,1])
nos.log.MI.sol10 <- as.data.frame(nos.log.model10$Sol[,1])
nos.log.MI.sol11 <- as.data.frame(nos.log.model11$Sol[,1])
nos.log.MI.sol12 <- as.data.frame(nos.log.model12$Sol[,1])
nos.log.MI.sol13 <- as.data.frame(nos.log.model13$Sol[,1])
nos.log.MI.sol14 <- as.data.frame(nos.log.model14$Sol[,1])
nos.log.MI.sol15 <- as.data.frame(nos.log.model15$Sol[,1])
nos.log.MI.sol16 <- as.data.frame(nos.log.model16$Sol[,1])
nos.log.MI.sol17 <- as.data.frame(nos.log.model17$Sol[,1])
nos.log.MI.sol18 <- as.data.frame(nos.log.model18$Sol[,1])
nos.log.MI.sol19 <- as.data.frame(nos.log.model19$Sol[,1])
nos.log.MI.sol20 <- as.data.frame(nos.log.model20$Sol[,1])

#pool posterior estimates
nos.log.MI.comb.sol1 <- rbind(nos.log.MI.sol1, nos.log.MI.sol2, nos.log.MI.sol3, nos.log.MI.sol4, nos.log.MI.sol5, nos.log.MI.sol6, nos.log.MI.sol7, nos.log.MI.sol8, nos.log.MI.sol9, nos.log.MI.sol10,
                              nos.log.MI.sol11, nos.log.MI.sol12, nos.log.MI.sol13, nos.log.MI.sol14, nos.log.MI.sol15, nos.log.MI.sol16, nos.log.MI.sol17, nos.log.MI.sol18, nos.log.MI.sol19, 
                              nos.log.MI.sol20)
posterior.mode(nos.log.MI.comb.sol1) #posterior mode of pooled estimates
hdi(nos.log.MI.comb.sol1, credMass=0.95) #95% HPD CI of pooled estimates

##### Phylogenetic model (with MI data)

#update tree - extra species included with MI data
data4$Scientific.name <- as.character(data4$Scientific.name)

#change species names in es to match those of rotl tree
data4$Scientific.name[data4$Scientific.name == "Cersus eldi thamin"] <- "Rucervus eldii"
data4$Scientific.name[data4$Scientific.name == "Choreopsis liberiensis"] <- "Hexaprotodon liberiensis"
data4$Scientific.name[data4$Scientific.name == "Clethrionymus glareolus"] <- "Myodes glareolus"
data4$Scientific.name[data4$Scientific.name == "Equus burchelli"] <- "Equus burchelii"
data4$Scientific.name[data4$Scientific.name == "Fenneropenaeus merguiensis"] <- "Penaeus merguiensis"
data4$Scientific.name[data4$Scientific.name == "Gorilla gorilla gorilla"] <- "Gorilla gorilla"
data4$Scientific.name[data4$Scientific.name == "Pan troglodytes"] <- "Pan troglodytes troglodytes"
data4$Scientific.name[data4$Scientific.name == "Saguinus fuscicollis illigeri"] <- "Saguinus fuscicollis"
data4$Scientific.name[data4$Scientific.name == "Eulemur mongoz, formerly Lemur mongoz "] <- "Eulemur mongoz"

species <- unique(data4$Scientific.name)
species <- as.data.frame(species)
species[,1] <- as.character(species[,1]) #48 unique species with missing data included

#Add outgroup (box jellyfish) to root tree
outgroup <- 'Chironex fleckeri' 
species[49,1] <- outgroup

taxa <- tnrs_match_names(names=species[,1], context_name = "All life")
tr <- tol_induced_subtree(taxa$ott_id)
taxon_map <- structure(taxa$search_string, names=as.character(taxa$unique_name))
tr$tip.label
otl_tips <- strip_ott_ids(tr$tip.label, remove_underscores = TRUE)
tr$tip.label
tr$tip.label <- taxon_map[otl_tips]
tr$tip.label <- capitalize(tr$tip.label)
any(duplicated(tr$node.label))
tr$node.label <- NULL
plot(tr, show.tip.label=TRUE, show.node.label = FALSE)

#Phylogenetic VCV matrix (with MI data)

data4$animal <- data4$Scientific.name
CorMatrix <- vcv(compute.brlen(tr, corr = T))
CorExt <- as.matrix(CorMatrix[match(data4$animal, rownames(CorMatrix)), match(data4$animal, colnames(CorMatrix))])
levelplot(CorMatrix, xlab = '', ylab = 'Species')
CorMatrix1 <- CorMatrix[-49, -49]
levelplot(CorMatrix1)
Cinv <- solve(CorMatrix1)
Cinv2 <- as(Cinv, "dgCMatrix")

prior.phylo <- list(R=list(V=1,nu=0.002),G=list(G1=list(V=1, nu=0.002), G2=list(V=1, nu=0.002)))

o.modelphylo <- function(i) {
  data4$Scientific.name <- as.character(data4$Scientific.name)
  data4$Scientific.name[data4$Scientific.name == "Cersus eldi thamin"] <- "Rucervus eldii"
  data4$Scientific.name[data4$Scientific.name == "Choreopsis liberiensis"] <- "Hexaprotodon liberiensis"
  data4$Scientific.name[data4$Scientific.name == "Clethrionymus glareolus"] <- "Myodes glareolus"
  data4$Scientific.name[data4$Scientific.name == "Equus burchelli"] <- "Equus burchelii"
  data4$Scientific.name[data4$Scientific.name == "Fenneropenaeus merguiensis"] <- "Penaeus merguiensis"
  data4$Scientific.name[data4$Scientific.name == "Gorilla gorilla gorilla"] <- "Gorilla gorilla"
  data4$Scientific.name[data4$Scientific.name == "Pan troglodytes"] <- "Pan troglodytes troglodytes"
  data4$Scientific.name[data4$Scientific.name == "Saguinus fuscicollis illigeri"] <- "Saguinus fuscicollis"
  data4$Scientific.name[data4$Scientific.name == "Eulemur mongoz, formerly Lemur mongoz "] <- "Eulemur mongoz"
  data4$animal <- data4$Scientific.name
  MCMCglmm(yi ~ 1, random = ~animal + ID, mev = MEV, data = data4, verbose=T,
           nitt=5000000, thin=3000, burnin=150000, prior=prior.phylo, pr=T, 
           ginverse=list(animal = Cinv2))
}

MImodel(1)
nos.log.phylomodel1 <- o.modelphylo(1)
MImodel(2)
nos.log.phylomodel2 <- o.modelphylo(2)
MImodel(3)
nos.log.phylomodel3 <- o.modelphylo(3)
MImodel(4)
nos.log.phylomodel4 <- o.modelphylo(4)
MImodel(5)
nos.log.phylomodel5 <- o.modelphylo(5)
MImodel(6)
nos.log.phylomodel6 <- o.modelphylo(6)
MImodel(7)
nos.log.phylomodel7 <- o.modelphylo(7)
MImodel(8)
nos.log.phylomodel8 <- o.modelphylo(8)
MImodel(9)
nos.log.phylomodel9 <- o.modelphylo(9)
MImodel(10)
nos.log.phylomodel10 <- o.modelphylo(10)
MImodel(11)
nos.log.phylomodel11 <- o.modelphylo(11)
MImodel(12)
nos.log.phylomodel12 <- o.modelphylo(12)
MImodel(13)
nos.log.phylomodel13 <- o.modelphylo(13)
MImodel(14)
nos.log.phylomodel14 <- o.modelphylo(14)
MImodel(15)
nos.log.phylomodel15 <- o.modelphylo(15)
MImodel(16)
nos.log.phylomodel16 <- o.modelphylo(16)
MImodel(17)
nos.log.phylomodel17 <- o.modelphylo(17)
MImodel(18)
nos.log.phylomodel18 <- o.modelphylo(18)
MImodel(19)
nos.log.phylomodel19 <- o.modelphylo(19)
MImodel(20)
nos.log.phylomodel20 <- o.modelphylo(20)

#VCV = variance components
nos.log.phylo.MI.comb.VCV <- mcmc.list(nos.log.phylomodel1$VCV, nos.log.phylomodel2$VCV, nos.log.phylomodel3$VCV, nos.log.phylomodel4$VCV, nos.log.phylomodel5$VCV, nos.log.phylomodel6$VCV, nos.log.phylomodel7$VCV,
                                       nos.log.phylomodel8$VCV, nos.log.phylomodel9$VCV, nos.log.phylomodel10$VCV, nos.log.phylomodel11$VCV, nos.log.phylomodel12$VCV, nos.log.phylomodel13$VCV,
                                       nos.log.phylomodel14$VCV, nos.log.phylomodel15$VCV, nos.log.phylomodel16$VCV, nos.log.phylomodel17$VCV, nos.log.phylomodel18$VCV, nos.log.phylomodel19$VCV,
                                       nos.log.phylomodel20$VCV)
summary(nos.log.phylo.MI.comb.VCV)

#Sol = solutions
nos.log.phylo.MI.comb.Sol <- mcmc.list(nos.log.phylomodel1$Sol, nos.log.phylomodel2$Sol, nos.log.phylomodel3$Sol, nos.log.phylomodel4$Sol, nos.log.phylomodel5$Sol, nos.log.phylomodel6$Sol, nos.log.phylomodel7$Sol, nos.log.phylomodel8$Sol,
                                       nos.log.phylomodel9$Sol, nos.log.phylomodel10$Sol, nos.log.phylomodel11$Sol, nos.log.phylomodel12$Sol, nos.log.phylomodel13$Sol, nos.log.phylomodel14$Sol, nos.log.phylomodel15$Sol, 
                                       nos.log.phylomodel16$Sol, nos.log.phylomodel17$Sol, nos.log.phylomodel18$Sol, nos.log.phylomodel19$Sol, nos.log.phylomodel20$Sol)
plot(mcmc.list(nos.log.phylomodel1$Sol[,1], nos.log.phylomodel2$Sol[,1], nos.log.phylomodel3$Sol[,1])) 

autocorr.diag(nos.log.phylo.MI.comb.VCV) #passes autocorrelation
heidel.diag(nos.log.phylo.MI.comb.VCV) #all passed

nos.log.phylo.MI.sol1 <- as.data.frame(nos.log.phylomodel1$Sol[,1])
nos.log.phylo.MI.sol2 <- as.data.frame(nos.log.phylomodel2$Sol[,1])
nos.log.phylo.MI.sol3 <- as.data.frame(nos.log.phylomodel3$Sol[,1])
nos.log.phylo.MI.sol4 <- as.data.frame(nos.log.phylomodel4$Sol[,1])
nos.log.phylo.MI.sol5 <- as.data.frame(nos.log.phylomodel5$Sol[,1])
nos.log.phylo.MI.sol6 <- as.data.frame(nos.log.phylomodel6$Sol[,1])
nos.log.phylo.MI.sol7 <- as.data.frame(nos.log.phylomodel7$Sol[,1])
nos.log.phylo.MI.sol8 <- as.data.frame(nos.log.phylomodel8$Sol[,1])
nos.log.phylo.MI.sol9 <- as.data.frame(nos.log.phylomodel9$Sol[,1])
nos.log.phylo.MI.sol10 <- as.data.frame(nos.log.phylomodel10$Sol[,1])
nos.log.phylo.MI.sol11 <- as.data.frame(nos.log.phylomodel11$Sol[,1])
nos.log.phylo.MI.sol12 <- as.data.frame(nos.log.phylomodel12$Sol[,1])
nos.log.phylo.MI.sol13 <- as.data.frame(nos.log.phylomodel13$Sol[,1])
nos.log.phylo.MI.sol14 <- as.data.frame(nos.log.phylomodel14$Sol[,1])
nos.log.phylo.MI.sol15 <- as.data.frame(nos.log.phylomodel15$Sol[,1])
nos.log.phylo.MI.sol16 <- as.data.frame(nos.log.phylomodel16$Sol[,1])
nos.log.phylo.MI.sol17 <- as.data.frame(nos.log.phylomodel17$Sol[,1])
nos.log.phylo.MI.sol18 <- as.data.frame(nos.log.phylomodel18$Sol[,1])
nos.log.phylo.MI.sol19 <- as.data.frame(nos.log.phylomodel19$Sol[,1])
nos.log.phylo.MI.sol20 <- as.data.frame(nos.log.phylomodel20$Sol[,1])

nos.log.phylo.MI.comb.sol1 <- rbind(nos.log.phylo.MI.sol1, nos.log.phylo.MI.sol2, nos.log.phylo.MI.sol3, nos.log.phylo.MI.sol4, nos.log.phylo.MI.sol5, nos.log.phylo.MI.sol6, nos.log.phylo.MI.sol7, nos.log.phylo.MI.sol8, nos.log.phylo.MI.sol9, nos.log.phylo.MI.sol10,
                                    nos.log.phylo.MI.sol11, nos.log.phylo.MI.sol12, nos.log.phylo.MI.sol13, nos.log.phylo.MI.sol14, nos.log.phylo.MI.sol15, nos.log.phylo.MI.sol16, nos.log.phylo.MI.sol17, nos.log.phylo.MI.sol18, nos.log.phylo.MI.sol19, 
                                    nos.log.phylo.MI.sol20)
posterior.mode(nos.log.phylo.MI.comb.sol1)
hdi(nos.log.phylo.MI.comb.sol1, credMass=0.95)

### Study environment model (with MI data)
ce.model <- function(i) {
  MCMCglmm(yi ~ factor(Captive.environment)-1, random = ~ ID, mev = MEV, 
           data = data4, verbose=T, nitt=5000000, thin=3000, burnin=150000, 
           prior=prior, pr=T)
}

MImodel(1)
nos.log.cemodel1 <- ce.model(1)
MImodel(2)
nos.log.cemodel2 <- ce.model(2)
MImodel(3)
nos.log.cemodel3 <- ce.model(3)
MImodel(4)
nos.log.cemodel4 <- ce.model(4)
MImodel(5)
nos.log.cemodel5 <- ce.model(5)
MImodel(6)
nos.log.cemodel6 <- ce.model(6)
MImodel(7)
nos.log.cemodel7 <- ce.model(7)
MImodel(8)
nos.log.cemodel8 <- ce.model(8)
MImodel(9)
nos.log.cemodel9 <- ce.model(9)
MImodel(10)
nos.log.cemodel10 <- ce.model(10)
MImodel(11)
nos.log.cemodel11 <- ce.model(11)
MImodel(12)
nos.log.cemodel12 <- ce.model(12)
MImodel(13)
nos.log.cemodel13 <- ce.model(13)
MImodel(14)
nos.log.cemodel14 <- ce.model(14)
MImodel(15)
nos.log.cemodel15 <- ce.model(15)
MImodel(16)
nos.log.cemodel16 <- ce.model(16)
MImodel(17)
nos.log.cemodel17 <- ce.model(17)
MImodel(18)
nos.log.cemodel18 <- ce.model(18)
MImodel(19)
nos.log.cemodel19 <- ce.model(19)
MImodel(20)
nos.log.cemodel20 <- ce.model(20)

#VCV = variance components
nos.log.ce.MI.comb.VCV <- mcmc.list(nos.log.cemodel1$VCV, nos.log.cemodel2$VCV, nos.log.cemodel3$VCV, nos.log.cemodel4$VCV, nos.log.cemodel5$VCV, nos.log.cemodel6$VCV, nos.log.cemodel7$VCV,
                                    nos.log.cemodel8$VCV, nos.log.cemodel9$VCV, nos.log.cemodel10$VCV, nos.log.cemodel11$VCV, nos.log.cemodel12$VCV, nos.log.cemodel13$VCV,
                                    nos.log.cemodel14$VCV, nos.log.cemodel15$VCV, nos.log.cemodel16$VCV, nos.log.cemodel17$VCV, nos.log.cemodel18$VCV, nos.log.cemodel19$VCV,
                                    nos.log.cemodel20$VCV)
summary(nos.log.ce.MI.comb.VCV)

#Sol = solutions
nos.log.ce.MI.comb.Sol <- mcmc.list(nos.log.cemodel1$Sol, nos.log.cemodel2$Sol, nos.log.cemodel3$Sol, nos.log.cemodel4$Sol, nos.log.cemodel5$Sol, nos.log.cemodel6$Sol, nos.log.cemodel7$Sol, nos.log.cemodel8$Sol,
                                    nos.log.cemodel9$Sol, nos.log.cemodel10$Sol, nos.log.cemodel11$Sol, nos.log.cemodel12$Sol, nos.log.cemodel13$Sol, nos.log.cemodel14$Sol, nos.log.cemodel15$Sol, 
                                    nos.log.cemodel16$Sol, nos.log.cemodel17$Sol, nos.log.cemodel18$Sol, nos.log.cemodel19$Sol, nos.log.cemodel20$Sol)
plot(mcmc.list(nos.log.cemodel1$Sol[,1], nos.log.cemodel2$Sol[,1], nos.log.cemodel3$Sol[,1])) 

autocorr.diag(nos.log.ce.MI.comb.VCV) #passes autocorrelation
heidel.diag(nos.log.ce.MI.comb.VCV) #all passed

nos.log.ce.MI.sol1 <- as.data.frame(nos.log.cemodel1$Sol[,1:4])
nos.log.ce.MI.sol2 <- as.data.frame(nos.log.cemodel2$Sol[,1:4])
nos.log.ce.MI.sol3 <- as.data.frame(nos.log.cemodel3$Sol[,1:4])
nos.log.ce.MI.sol4 <- as.data.frame(nos.log.cemodel4$Sol[,1:4])
nos.log.ce.MI.sol5 <- as.data.frame(nos.log.cemodel5$Sol[,1:4])
nos.log.ce.MI.sol6 <- as.data.frame(nos.log.cemodel6$Sol[,1:4])
nos.log.ce.MI.sol7 <- as.data.frame(nos.log.cemodel7$Sol[,1:4])
nos.log.ce.MI.sol8 <- as.data.frame(nos.log.cemodel8$Sol[,1:4])
nos.log.ce.MI.sol9 <- as.data.frame(nos.log.cemodel9$Sol[,1:4])
nos.log.ce.MI.sol10 <- as.data.frame(nos.log.cemodel10$Sol[,1:4])
nos.log.ce.MI.sol11 <- as.data.frame(nos.log.cemodel11$Sol[,1:4])
nos.log.ce.MI.sol12 <- as.data.frame(nos.log.cemodel12$Sol[,1:4])
nos.log.ce.MI.sol13 <- as.data.frame(nos.log.cemodel13$Sol[,1:4])
nos.log.ce.MI.sol14 <- as.data.frame(nos.log.cemodel14$Sol[,1:4])
nos.log.ce.MI.sol15 <- as.data.frame(nos.log.cemodel15$Sol[,1:4])
nos.log.ce.MI.sol16 <- as.data.frame(nos.log.cemodel16$Sol[,1:4])
nos.log.ce.MI.sol17 <- as.data.frame(nos.log.cemodel17$Sol[,1:4])
nos.log.ce.MI.sol18 <- as.data.frame(nos.log.cemodel18$Sol[,1:4])
nos.log.ce.MI.sol19 <- as.data.frame(nos.log.cemodel19$Sol[,1:4])
nos.log.ce.MI.sol20 <- as.data.frame(nos.log.cemodel20$Sol[,1:4])

nos.log.ce.MI.comb.sol1 <- rbind(nos.log.ce.MI.sol1, nos.log.ce.MI.sol2, nos.log.ce.MI.sol3, nos.log.ce.MI.sol4, nos.log.ce.MI.sol5, nos.log.ce.MI.sol6, nos.log.ce.MI.sol7, nos.log.ce.MI.sol8, nos.log.ce.MI.sol9, nos.log.ce.MI.sol10,
                                 nos.log.ce.MI.sol11, nos.log.ce.MI.sol12, nos.log.ce.MI.sol13, nos.log.ce.MI.sol14, nos.log.ce.MI.sol15, nos.log.ce.MI.sol16, nos.log.ce.MI.sol17, nos.log.ce.MI.sol18, nos.log.ce.MI.sol19, 
                                 nos.log.ce.MI.sol20)
posterior.mode(nos.log.ce.MI.comb.sol1)
hdi(nos.log.ce.MI.comb.sol1, credMass=0.95)

#### Trait type (with MI data)
t.model <- function(i) {
  MCMCglmm(yi ~ factor(Trait)-1, random = ~ ID, mev = MEV, 
           data = data4, verbose=T, nitt=5000000, thin=3000, burnin=150000, 
           prior=prior, pr=T)
}

MImodel(1)
nos.log.tmodel1 <- t.model(1)
MImodel(2)
nos.log.tmodel2 <- t.model(2)
MImodel(3)
nos.log.tmodel3 <- t.model(3)
MImodel(4)
nos.log.tmodel4 <- t.model(4)
MImodel(5)
nos.log.tmodel5 <- t.model(5)
MImodel(6)
nos.log.tmodel6 <- t.model(6)
MImodel(7)
nos.log.tmodel7 <- t.model(7)
MImodel(8)
nos.log.tmodel8 <- t.model(8)
MImodel(9)
nos.log.tmodel9 <- t.model(9)
MImodel(10)
nos.log.tmodel10 <- t.model(10)
MImodel(11)
nos.log.tmodel11 <- t.model(11)
MImodel(12)
nos.log.tmodel12 <- t.model(12)
MImodel(13)
nos.log.tmodel13 <- t.model(13)
MImodel(14)
nos.log.tmodel14 <- t.model(14)
MImodel(15)
nos.log.tmodel15 <- t.model(15)
MImodel(16)
nos.log.tmodel16 <- t.model(16)
MImodel(17)
nos.log.tmodel17 <- t.model(17)
MImodel(18)
nos.log.tmodel18 <- t.model(18)
MImodel(19)
nos.log.tmodel19 <- t.model(19)
MImodel(20)
nos.log.tmodel20 <- t.model(20)

#VCV = variance components
nos.log.t.MI.comb.VCV <- mcmc.list(nos.log.tmodel1$VCV, nos.log.tmodel2$VCV, nos.log.tmodel3$VCV, nos.log.tmodel4$VCV, nos.log.tmodel5$VCV, nos.log.tmodel6$VCV, nos.log.tmodel7$VCV,
                                   nos.log.tmodel8$VCV, nos.log.tmodel9$VCV, nos.log.tmodel10$VCV, nos.log.tmodel11$VCV, nos.log.tmodel12$VCV, nos.log.tmodel13$VCV,
                                   nos.log.tmodel14$VCV, nos.log.tmodel15$VCV, nos.log.tmodel16$VCV, nos.log.tmodel17$VCV, nos.log.tmodel18$VCV, nos.log.tmodel19$VCV,
                                   nos.log.tmodel20$VCV)
summary(nos.log.t.MI.comb.VCV)

#Sol = solutions
nos.log.t.MI.comb.Sol <- mcmc.list(nos.log.tmodel1$Sol, nos.log.tmodel2$Sol, nos.log.tmodel3$Sol, nos.log.tmodel4$Sol, nos.log.tmodel5$Sol, nos.log.tmodel6$Sol, nos.log.tmodel7$Sol, nos.log.tmodel8$Sol,
                                   nos.log.tmodel9$Sol, nos.log.tmodel10$Sol, nos.log.tmodel11$Sol, nos.log.tmodel12$Sol, nos.log.tmodel13$Sol, nos.log.tmodel14$Sol, nos.log.tmodel15$Sol, 
                                   nos.log.tmodel16$Sol, nos.log.tmodel17$Sol, nos.log.tmodel18$Sol, nos.log.tmodel19$Sol, nos.log.tmodel20$Sol)
plot(mcmc.list(nos.log.tmodel1$Sol[,1], nos.log.tmodel2$Sol[,1], nos.log.tmodel3$Sol[,1])) 

autocorr.diag(nos.log.t.MI.comb.VCV) #passes autocorrelation
heidel.diag(nos.log.t.MI.comb.VCV) #all passed

nos.log.t.MI.sol1 <- as.data.frame(nos.log.tmodel1$Sol[,1:5])
nos.log.t.MI.sol2 <- as.data.frame(nos.log.tmodel2$Sol[,1:5])
nos.log.t.MI.sol3 <- as.data.frame(nos.log.tmodel3$Sol[,1:5])
nos.log.t.MI.sol4 <- as.data.frame(nos.log.tmodel4$Sol[,1:5])
nos.log.t.MI.sol5 <- as.data.frame(nos.log.tmodel5$Sol[,1:5])
nos.log.t.MI.sol6 <- as.data.frame(nos.log.tmodel6$Sol[,1:5])
nos.log.t.MI.sol7 <- as.data.frame(nos.log.tmodel7$Sol[,1:5])
nos.log.t.MI.sol8 <- as.data.frame(nos.log.tmodel8$Sol[,1:5])
nos.log.t.MI.sol9 <- as.data.frame(nos.log.tmodel9$Sol[,1:5])
nos.log.t.MI.sol10 <- as.data.frame(nos.log.tmodel10$Sol[,1:5])
nos.log.t.MI.sol11 <- as.data.frame(nos.log.tmodel11$Sol[,1:5])
nos.log.t.MI.sol12 <- as.data.frame(nos.log.tmodel12$Sol[,1:5])
nos.log.t.MI.sol13 <- as.data.frame(nos.log.tmodel13$Sol[,1:5])
nos.log.t.MI.sol14 <- as.data.frame(nos.log.tmodel14$Sol[,1:5])
nos.log.t.MI.sol15 <- as.data.frame(nos.log.tmodel15$Sol[,1:5])
nos.log.t.MI.sol16 <- as.data.frame(nos.log.tmodel16$Sol[,1:5])
nos.log.t.MI.sol17 <- as.data.frame(nos.log.tmodel17$Sol[,1:5])
nos.log.t.MI.sol18 <- as.data.frame(nos.log.tmodel18$Sol[,1:5])
nos.log.t.MI.sol19 <- as.data.frame(nos.log.tmodel19$Sol[,1:5])
nos.log.t.MI.sol20 <- as.data.frame(nos.log.tmodel20$Sol[,1:5])

nos.log.t.MI.comb.sol1 <- rbind(nos.log.t.MI.sol1, nos.log.t.MI.sol2, nos.log.t.MI.sol3, nos.log.t.MI.sol4, nos.log.t.MI.sol5, nos.log.t.MI.sol6, nos.log.t.MI.sol7, nos.log.t.MI.sol8, nos.log.t.MI.sol9, nos.log.t.MI.sol10,
                                nos.log.t.MI.sol11, nos.log.t.MI.sol12, nos.log.t.MI.sol13, nos.log.t.MI.sol14, nos.log.t.MI.sol15, nos.log.t.MI.sol16, nos.log.t.MI.sol17, nos.log.t.MI.sol18, nos.log.t.MI.sol19, 
                                nos.log.t.MI.sol20)
posterior.mode(nos.log.t.MI.comb.sol1)
hdi(nos.log.t.MI.comb.sol1, credMass=0.95)

#compare MI model results to original analysis model results