#Example 7.7 Hybrid gibbs
### Data ### 
n.c = c(30,22,29,26,31,32,35)
n.m = c(30,8,17,7,9,8,5)
r = sum(n.m)
I = length(n.c)


N = 500000                        # length of chain 
alpha.sim = matrix(nrow=N,ncol=I) # result vector
N.sim = rep(NA,N)                 # result vector
theta.sim = matrix(nrow=N,ncol=2) # result vector

## Hybrid Gibbs-sampler loop ##
alpha.sim[1,]=rep(0.5,I)        # initialize alpha
theta.sim[1,]=rexp(2,1/1000)    # initialize theta
p = 1-prod(1-alpha.sim[1,])     # compute p from alpha 
N.sim[1] = r + rnbinom(1,r+1,p) # sample N (given alpha and data) 

for(j in 2:N)
{
   alpha.sim[j,] = rbeta(I,n.c+theta.sim[j-1,1],N.sim[j-1]-n.c+theta.sim[j-1,2]) # sample alpha given N, theta  and data
   p = 1-prod(1-alpha.sim[j,])                                                   # compute p from alpha 
   N.sim[j] = r + rnbinom(1,r+1,p)                                               # sample N (given alpha, theta and data) 
   
   ## M-H step for theta  
   theta.prop = rexp(2,1/1000)                                                  ## propose sample from the prior
   l.prop = I*(lgamma(sum(theta.prop))-sum(lgamma(theta.prop)))+  
      sum(theta.prop[1]*log(alpha.sim[j,])+theta.prop[2]*log(1-alpha.sim[j,]))-
            sum(theta.prop)/1000                                                       ## log-Likelihood of proposed theta given alpha and N
   l = I*(lgamma(sum(theta.sim[j-1,]))-sum(lgamma(theta.sim[j-1,])))+
                    sum(theta.sim[j-1,1]*log(alpha.sim[j,])+
                        theta.sim[j-1,2]*log(1-alpha.sim[j,]))-
                    sum(theta.sim[j-1,])/1000                                          ## log-Likelihood of current theta given alpha and N
   R = exp(l.prop-l)*prod(dexp(theta.sim[j-1,],1/1000))/prod(dexp(theta.prop,1/1000))  ## MH-Ratio 
   
   ## MH-acceptance step for theta
   if(runif(1)<R)
     theta.sim[j,] = theta.prop
   else
     theta.sim[j,] = theta.sim[j-1,]
#   show(c(j,N.sim[j],theta.sim[j,],alpha.sim[j,]))
}

### plotting results ###

######################
# Discasrding first 10000 simulations 
# N.sim = N.sim[-c(1:10000)]
# alpha.sim = alpha.sim[-c(1:10000),]
# theta.sim = theta.sim[-c(1:10000),]

alpha.bar = rowMeans(alpha.sim)
par(mfrow=c(2,2))
hist(N.sim)
boxplot(alpha.bar~N.sim)
plot(density(theta.sim[,1]))
plot(density(theta.sim[,2]))
