
### Model 1: Gamma distribution


# Clear old results

rm(list = ls())


# Set seed

set.seed(88190)


# Directory

setwd("Z:\\My Documents\\Artiklar\\Mariana\\Table 2\\models-gamma")


# Libraries

library(coda)
library(R2WinBUGS)
library(BRugs)
library(lattice)


## Read the dataset

Example <- read.table("data.csv", header = T)

CreepingThistle <- Example$crepe
Treatment <- Example$Treat
Block <- Example$block

Y <- CreepingThistle
Y[Y==0] <- 0.000001


# Number of observations and blocks
n <- length(Y) 
nb <- 8

# Number of iterations for Gibbs sampling

niter <- 100000
thin <- 100
nchains <- 2


# Initial values

inits <- function(){
  list(phi = 1, beta = rep(0.1, 10), alpha = rep(0.1, 10), 
       xsi = 0, tau_eta1 = 10, tau_eta2 = 10, b = matrix(0, nb, 2))
}


# Path to model

model <- file.path("Model-1-gamma.R")


# Run in WinBUGS

datas <- list("Y","Treatment","Block","n","nb")

params <- c("phi", "alpha", "beta","sigmab1", "sigmab2", "rho", "p2", "mu2", "nu2", "p", "nu", "mu")

resu.simGamma <- bugs(datas, inits, params, model,
                      n.chains = 2, n.iter = niter, n.thin = thin,
                      n.burnin = round(0.5*niter), program = "openbugs", 
                      debug = TRUE,
                      codaPkg = FALSE, working.directory = NULL,
                      digits = 5,clearWD = FALSE)                        


# Print and save the results

print(resu.simGamma, 5)

sink("Model-1-gamma-summary.txt")
print(resu.simGamma, 5)
sink()


# Export results for Figure 1

means.nu2 <- apply(resu.simGamma$sims.list$nu2, 2, mean)
lower.nu2 <- apply(resu.simGamma$sims.list$nu2, 2, quantile, probs = c(0.025))
upper.nu2 <- apply(resu.simGamma$sims.list$nu2, 2, quantile, probs = c(0.975))

means.mu2 <- apply(resu.simGamma$sims.list$mu2, 2, mean)
lower.mu2 <- apply(resu.simGamma$sims.list$mu2, 2, quantile, probs = c(0.025))
upper.mu2 <- apply(resu.simGamma$sims.list$mu2, 2, quantile, probs = c(0.975))

means.p2 <- apply(resu.simGamma$sims.list$p2, 2, mean)
lower.p2 <- apply(resu.simGamma$sims.list$p2, 2, quantile, probs = c(0.025))
upper.p2 <- apply(resu.simGamma$sims.list$p2, 2, quantile, probs = c(0.975))


Figure.1 <- rbind(means.nu2, lower.nu2, upper.nu2,
                  means.mu2, lower.mu2, upper.mu2,
                  means.p2, lower.p2, upper.p2)

write.table(Figure.1, file = "Z:\\My Documents\\Artiklar\\Mariana\\Credability interval figures\\Model-1-gamma-Figure-1.txt", col.names = F, row.names = F)
