library(ggplot2)
theme_set(theme_minimal())
library(gridExtra)
library(tidyr)
library(latex2exp)

# Data
y1 = c(16,9,10,13,19,20,18,17,35,55)
n1 = c(58,90,48,57,103,57,86,112,273,64)
J = length(n1)

#Log-density function for (alpha,beta) (equation (5.8) in the book) 
lp_marg = function(alpha,beta)
{
  lp = -2.5*log(alpha+beta)
  lp = lp + J*(lgamma(alpha+beta)-lgamma(alpha)-lgamma(beta))
  for(j in 1:J)
    lp = lp + lgamma(alpha+y1[j])+lgamma(beta+n1[j]-y1[j])-
                     lgamma(alpha+beta+n1[j])
  lp
}

# (b): Calculating density on a grid 
ndiscr=100
a = seq(0.1,2.5,length=ndiscr)
alpha <- rep(a, each = ndiscr)
b = seq(0.1,6,length=ndiscr)
beta <- rep(b, ndiscr)
lp = lp_marg(alpha,beta)
lp = exp(lp-max(lp))
#Normalize to probability distribution
Dalpha = diff(a[1:2])
Dbeta = diff(b[1:2])
p = lp/(Dalpha*Dbeta*sum(lp))

#Plot, including some simulations
S = 100
ind = sample(1:length(p),S,prob=p,replace=T)
alpha.sim = alpha[ind]
beta.sim = beta[ind]
d.sim = data.frame(alpha.sim=alpha.sim,beta.sim=beta.sim)
#Plotting density
pos <- ggplot(data = data.frame(alpha ,beta, p), aes(alpha, beta)) +
  geom_contour(aes(z = p), colour = 'black', size = 0.2) +
  geom_raster(aes(fill = p, alpha = p), interpolate = T) +
  geom_point(data=d.sim,aes(x=alpha.sim,y=beta.sim)) +
  coord_cartesian(xlim = range(alpha), ylim = range(beta))
pos

#Simulation
S = 10000
ind = sample(1:length(p),S,prob=p,replace=T)
alpha.sim = alpha[ind]
beta.sim = beta[ind]
par(mfrow=c(1,2))
df = data.frame(alpha=alpha.sim,beta=beta.sim)
ggplot(df,aes(x=alpha))+geom_histogram()
ggplot(df,aes(x=beta))+geom_histogram()

# (c): 
theta.sim = matrix(nrow=J,ncol=S)
for(j in 1:J)
{
  theta.sim[j,] = rbeta(S,alpha.sim+y1[j],beta.sim+n1[j]-y1[j])
}
df = data.frame(theta=as.vector(theta.sim),group=rep(1:J,S))
df$group = as.factor(df$group)
ggplot(df,aes(x=theta,color=group))+geom_histogram(fill="white", alpha=0.5, position="identity")

par(mfrow=c(5,2))
for(j in 1:J)
{
  plot(density(theta.sim[j,]),xlim=c(0,1),main=paste("theta",j))
  abline(v=y1[j]/n1[j],col=2)
}

# (d)
#Posterior interval for alpha/(alpha+beta)
x = alpha.sim/(alpha.sim+beta.sim)
show(quantile(x,c(0.025,0.975)))

# (e): Predictions
theta.new = rbeta(S,alpha.sim,beta.sim)
y.new = rbinom(S,100,theta.new)
quantile(y.new,c(0.025,0.975))
hist(theta.new)
theta.mean = apply(theta.sim,2,mean)
quantile(theta.mean,probs=c(0.025,0.975))

# (e): 
block = sample(1:10,S,replace=T)
theta.pred.sim = rep(NA,S)
for(j in 1:J)
{
  nj = sum(block==j)
  theta.pred.sim[block==j] = sample(theta.sim[j,],nj,replace=T)
}
y.pred = rbinom(S,100,prob=theta.pred.sim)
quantile(y.pred,probs=c(0.025,0.975))


# (f): 
plot(density(theta.sim))

#Stan
SEED <- 48927
d = list(y=y1,n=n1,N=J)
initf = function(...){list(alpha=0.3,beta=0.3,theta=y1/n1)}
fit <- stan(file = "Exer5_13.stan", data = d,seed = SEED,init=initf)

