#Exercise 7.8
#d = read.table("../data/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=100
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)



#Second parametrization
K = 2
muM2 = matrix(nrow=K,ncol=N)
gammaM = array(NA,c(2,N,I))
etaM = array(NA,c(2,N,I,J))
for(k in 1:K)
{


#Initialization
mu = y.bar
gamma = y.dot-y.bar
eta = matrix(0,nrow=I,ncol=J)
y = matrix(d$Moisture,ncol=J,byrow=T)
#Gibbs sampling
for(i in 1:N)
{
  #Sample mu
  mu = rnorm(1,mean(gamma),sqrt(sig2.alpha)/I)
  #Sample gamma
  gamma = rnorm(I,V3*(rowSums(eta)/sig2.beta + mu/sig2.alpha),sqrt(V3))
  #Sample eta
  eta[,1] = rnorm(I,V2*(y[,1]/sig2.eps-+gamma/sig2.beta),sqrt(V2))
  eta[,2] = rnorm(I,V2*(y[,2]/sig2.eps+gamma/sig2.beta),sqrt(V2))

  muM2[k,i] = mu
  gammaM[k,i,] = gamma
  etaM[k,i,,] = eta 
}
#Remove first D iterations
}
muM2 = muM2[,-c(1:D)]
gammaM = gammaM[,-c(1:D),]
etaM = etaM[,-c(1:D),,]

par(mfrow=c(4,4))
plot.ts(muM2[1,])
for(j in 1:I)
plot.ts(gammaM[1,,j])
round(cor(cbind(muM2[1,],gammaM[1,,])),2)

par(mfrow=c(3,2))
plot.ts(muM1[1,]);acf(muM1[1,])
plot.ts(muM2[1,]);acf(muM2[1,])
d1 = density(muM1[1,])
d2 = density(muM2[1,])
matplot(cbind(d1$x,d2$x),cbind(d1$y,d2$y))




par(mfrow=c(2,1))
N1 = ncol(muM1)
plot(1:N1,cumsum(muM1[1,])-c(1:N1)*mean(muM1[1,]),type="l")
plot(1:L,cumsum(muM2[1,])-c(1:L)*mean(muM2[1,]),type="l")

R2.mu = GelmanRubin(muM2)
R2.gamma = GelmanRubin(gammaM[,,1])
for(i in 2:15)
  R2.gamma = cbind(R2.gamma, GelmanRubin(gammaM[,,i]))


par(mfrow=c(4,4),mar=rep(2,4))
matplot(cbind(R1.mu,R2.mu),type="l",log="y",lty=1)
for(i in 1:15)
  matplot(cbind(R1.alpha[,i],R2.gamma[,i]),type="l",log="y",lty=1)

acf(muM2[,1])
for(i in 1:15)
  acf(gammaM[1,,i])
