#Exer11_2
x = c(-0.86,-0.30,-0.05,0.73)
n = c(5,5,5,5)
y = c(0,1,3,5)
x = x-mean(x)

logdens = function(theta,x=x,y=y,n=n)
{
  alpha=theta[1];beta=theta[2]
  p = exp(alpha+beta*x)/(1+exp(alpha+beta*x))
  l = sum(y*log(p)+(n-y)*log(1-p))
  l
}

#Metropolis algorithm
#Initialization
theta = c(1,1)
l = logdens(theta,x,y,n)
sig.prop = 1.5
S=30000
theta.sim = matrix(nrow=S,ncol=2)
acc = 0
for(s in 1:S)
{
  theta.prop = theta + sig.prop*rnorm(2)
  l.prop = logdens(theta.prop,x,y,n)
  if(runif(1)<exp(l.prop-l))
  {
    theta = theta.prop
    l = l.prop
    acc = acc+1
  }
  theta.sim[s,] = theta
}
cat("Acceptance probability is ",acc/S,"\n")
tab = cbind(colMeans(theta.sim),apply(theta.sim,2,sd),
            t(apply(theta.sim,2,quantile,prob=c(0.025,0.975))))
colnames(tab)[1:2] = c("Mean","sd")
rownames(tab) = c("alpha","beta")
show(tab)
plot.ts(theta.sim)
acf(theta.sim)
burnin = S/2
plot(theta.sim[-c(1:burnin),],
     xlab=expression(alpha),ylab=expression(beta))

#Using stan/rstan
if(FALSE)
{
library(rstan)
dat <- list(n = n, x = x, y = y,N=4); 
m = stan_model(file = 'bioassay.stan')
fit <- stan(file="bioassay.stan", 
            data = dat, iter = 10000, chains = 3, verbose = TRUE,
            sample_file = file.path(tempdir(), 'bioassay.csv')) 
print(fit)

# extract samples 
e <- extract(fit, permuted = FALSE) # return a list of arrays 
str(e)

arr <- as.array(fit) # return an array 
str(arr)

mat <- as.matrix(fit) # return a matrix
str(mat)
plot(mat[,1:2],xlim=c(-2,8),ylim=c(0,50),
     xlab=expression(alpha),ylab=expression(beta))


}
## End(Not run)