#MCMC for hierarchical normal model using stan
library(rstan)
# Data 
rstan_options(auto_write = TRUE)
#options(mc.cores = parallel::detectCores())
y1 = c(62,60,63,59)
y2 = c(63,67,71,64,65,66)
y3 = c(68,66,71,67,68,68)
y4 = c(56,62,60,61,63,64,63,59)
y <- c(y1,y2,y3,y4)

initf = function(chain_id=1){
  list(mu=mean(y),sigma=sd(y),tau=1)
}
n_chains <- 4
init_ll <- lapply(1:n_chains, function(id) initf(chain_id = id))

data = list(n1=length(y1),n2=length(y2),n3=length(y3),n4=length(y4),
            y1=y1,y2=y2,y3=y3,y4=y4)

mod = stan_model("Example_11_6.stan")
fit = stan("Example_11_6.stan",data=data,iter=20000,warmup=10000,chains=4,
           init=initf,control=list(adapt_delta=0.95,max_treedepth=15))

monitor(fit, probs = c(0.1, 0.5, 0.9))

plot(fit)
