
### Model 3: Gamma distribution


# Clear old results

rm(list = ls())


# Set seed

set.seed(91701)


# 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


# Number of iterations for Gibbs sampling

niter <- 100000
thin <- 100
nchains <- 2

# Initial values

inits <- function(){
  list(phi = 0.1, beta = c(1, -2), alpha = rep(0.1, 10),
       b = rep(0.001, 8), z = 0.5, chisq.1 = 1)
}


# Path to model

model <- file.path("Model-3-gamma.R")


# Run in WinBUGS

datas <- list("Y","Treatment","Block")

params <- c("phi", "s.b", "alpha", "beta","p2","mu2","nu2","p",
                   "mu", "nu")

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(resu.simGamma, 5)

sink("Model-3-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-3-gamma-Figure-1.txt", col.names = F, row.names = F)

