#Exercise 7.6
coal = read.table("coal.dat",header=T)
plot(coal)
coal$num = 1:112
n = 112
par(mfrow=c(3,4))

N = 10000
theta = 41
lambda1 = 3
lambda2 = 0.5

#Calculating sum_xi for all values of theta
xsum = rep(NA,n-1)
for(i in 1:(n-1))
  xsum[i] = sum(coal$disasters[1:i])
Xsum = sum(coal$disasters)
alpha = 1

thetaM = NULL
alphaM = NULL
lambdaM1 = NULL
lambdaM2 = NULL
for(i in 1:N)
{
  #Sample theta
  logp = xsum*log(lambda1)-lambda1*seq(1,n-1) + (Xsum-xsum)*log(lambda2)-lambda2*seq(n-1,1)
  p = exp(logp)/sum(exp(logp))
  theta = sample(1:(n-1),1,prob=p)
  #Sample lambda
  lambda1 = rgamma(1,shape=3+xsum[theta],rate=alpha+theta)
  lambda2 = rgamma(1,shape=3+Xsum-xsum[theta],rate=alpha+n-theta)
  #Sample alpha
  alpha = rgamma(1,shape=16,rate=10+lambda1+lambda2)
  thetaM = c(thetaM,theta)
  lambdaM1 = c(lambdaM1,lambda1)
  lambdaM2 = c(lambdaM2,lambda2)
  alphaM = c(alphaM,alpha)
}
#Discard first J simulations
J = 1000
lambdaM1 = lambdaM1[-c(1:J)]
lambdaM2 = lambdaM2[-c(1:J)]
alphaM = alphaM[-c(1:J)]
thetaM = thetaM[-c(1:J)]
par(mfrow=c(2,2))
plot.ts(lambdaM1)
plot.ts(lambdaM2)
plot.ts(thetaM)
plot.ts(alphaM)

par(mfrow=c(2,2))
plot.ts(cumsum(lambdaM1-mean(lambdaM1)))
plot.ts(cumsum(lambdaM2-mean(lambdaM2)))
plot.ts(cumsum(thetaM-mean(thetaM)))
plot.ts(cumsum(alphaM-mean(alphaM)))

par(mfrow=c(2,2))
plot.ts(cumsum(lambdaM1-mean(lambdaM1))/(1:(N-J)))
plot.ts(cumsum(lambdaM2-mean(lambdaM2))/(1:(N-J)))
plot.ts(cumsum(thetaM-mean(thetaM))/(1:(N-J)))
plot.ts(cumsum(alphaM-mean(alphaM))/(1:(N-J)))


hist(lambdaM1,main="lambda1")
hist(lambdaM2,main="lambda2")
hist(thetaM,main="theta")
hist(alphaM,main="alpha")


par(mfrow=c(1,1))
plot(lambdaM1[seq(1,N-J,by=10)],lambdaM2[seq(1,N-J,by=10)])



