#Exercise 7.8
d = read.table("pigment.dat",header=T)
#d = read.table("V:/PROMAX/PROMAX-Odd/Lecture/STK4051-9051/Lectures_Odd/Ex15/pigment.dat",header=T)
#d = read.table("V:/PROMAX/PROMAX-Odd/Lecture/STK4051-9051/Lectures_Odd/Ex15/pigment.dat",header=T)


sig2.alpha = 86
sig2.beta = 58
sig2.eps = 1
n = nrow(d)
y.bar = mean(d$Moisture)
y.dot <-with(d, tapply(Moisture, Batch, mean))
J = 2
I = 15
D=1000
L = 1000
N = D+L
V1 = 1/(J/sig2.eps + 1/sig2.alpha)
V2 = 1/(1/sig2.eps+1/sig2.beta)
V3 = 1/(J/sig2.beta+1/sig2.alpha)
y = matrix(d$Moisture,ncol=J,byrow=T)

K = 2

#First parametrization, repeat K times
muM1 = matrix(nrow=K,ncol=N)
alphaM = array(NA,c(2,N,I))
betaM = array(NA,c(2,N,I,J))
for(k in 1:K)
{


#Initialization
mu = y.bar
alpha = y.dot-y.bar
beta = matrix(0,nrow=I,ncol=J)

#Gibbs sampling
for(i in 1:N)
{
  #Sample mu
  mu = rnorm(1,y.bar-sum(J*alpha)/n-sum(beta)/n,sqrt(sig2.eps)/n)  
    #Sample alpha
  alpha = rnorm(I,J*V1*(y.dot-mu-rowSums(beta)/J)/sig2.eps,sqrt(V1))
  #Sample beta
  beta[,1] = rnorm(I,V2*(y[,1]-mu-alpha),sqrt(V2))
  beta[,2] = rnorm(I,V2*(y[,2]-mu-alpha),sqrt(V2))
  #Store simulations
  muM1[k,i] = mu
  alphaM[k,i,] = alpha
  betaM[k,i,,] = beta 
}
}



#Remove first D iterations
muM1 = muM1[,-c(1:D)]
alphaM = alphaM[,-c(1:D),]
betaM = betaM[,-c(1:D),,]

par(mfrow=c(4,4),mar=c(2,2,2,2))
plot.ts(muM1[1,])
for(i in 1:I)
plot.ts(alphaM[1,,i])
round(cor(cbind(muM1[1,],alphaM[1,,])),2)


GelmanRubin = function(x)
{
  L = ncol(x)
  R = rep(NA,L)
  for(l in 2:L)
  {
    x.j = rowMeans(x[,1:l])
    s2.j = apply(x[,1:l],1,var)
    x.bar = mean(x.j)
    B = L*sum((x.j-x.bar)^2)/(J-1)
    W = mean(s2.j)
    R[l] = ((L-1)*W+B)/(L*W)
  }  
  R
}

#Calculate R for each iteration number
R1.mu = GelmanRubin(muM1)
R1.alpha = GelmanRubin(alphaM[,,1])
plot.ts(R1.alpha,ylim=c(0,3))
for(i in 2:15)
{
  R1.alpha = cbind(R1.alpha, GelmanRubin(alphaM[,,i]))
  plot.ts(R1.alpha[,i],ylim=c(0,3))
}

acf(muM1[,1],ylim=c(0,3))
for(i in 1:15)
  acf(alphaM[1,,i],ylim=c(0,3))
