---
title: "Stat. 481 Many Rose Garden Events - Gibbs Sampler - Hierarchical Model"
output: html_notebook
---

# Simualted Data

```{r}
require(rjags) 

source("DBDA2E-utilities.R") 
```

Now simulate the sum assuming a particular probability of a positive test, within each event.  The model of the distribution of the nu's is assumed to center at 0.05 and have a concentration of 100.


```{r}
omega <- 0.05 # mode of the beta

kappa <- 100
```

Simulate different rates for the different events.

```{r}
k <- 5

prob_nu <- rbeta(k, omega*(kappa-2)+1, (1 - omega)*(kappa - 2) + 1)
prob_nu

n <- 300 

y <- rbinom(k, n, prob_nu)
y
```

JAGS need the data to be in a list of values, vectors, and matrices.

```{r}
dataList <- list(
  y = y,
  Ntotal = n,
  k = k,
  kappa = kappa
)

dataList
```

# Model


```{r}
betaABfromModeKappa( mode=0.05, kappa=100 )

```



```{r}
modelString <- "
model {
  for (i in 1:k){
    y[i] ~ dbin( nu[i], Ntotal )                # Likelihood in code
    nu[i] = eta*pi[i] + (1 - theta)*(1-pi[i])
    pi[i] ~ dbeta( omega*(kappa-2)+1, (1 - omega)*(kappa - 2) + 1 ) 
    Py[i] ~ dbin( nu[i], Ntotal )               # Predictive distribution
  }
  omega ~ dbeta( 6, 95)
  eta ~ dbeta( 910 , 90 )            # prior
  theta ~ dbeta( 950 , 50 )          # prior
  Py_tot = sum(Py)
}
"
```

# Inits

```{r}
omega_init <- 0.05
eta_init <- 0.95
theta_init <- 0.95

initsList = list( omega = omega_init,
                  eta = eta_init,
                  theta = theta_init) 
```

# Updates

```{r}
jagsModel <- jags.model( file = textConnection(modelString), 
                         data = dataList, 
                         inits = initsList, 
                         n.chains = 5, 
                         n.adapt = 10000 )

update( jagsModel , n.iter=5000 )  # Burn-in

codaSamples = coda.samples( jagsModel,
                            variable.names=c("nu","pi",
                                             "omega", 
                                             "eta","theta","Py", "Py_tot"),
                            n.iter=5000 )     # Record sampled values
  
save( codaSamples , file=paste0("Mcmc.Rdata") )
```

# Examine the chains:
# Convergence diagnostics:

```{r}
plot(codaSamples)
```

```{r}
diagMCMC( codaObject=codaSamples, parName="omega" )
diagMCMC( codaObject=codaSamples, parName="eta" )
diagMCMC( codaObject=codaSamples, parName="theta" )
```

```{r}
traceplot(codaSamples)
```

```{r}
plotPost( codaSamples[,"omega"], main="omega", xlab=bquote(omega) )
plotPost( codaSamples[,"eta"], main="eta", xlab=bquote(eta) )
plotPost( codaSamples[,"theta"], main="theta", xlab=bquote(theta) )
```

```{r}
plotPost( codaSamples[,"omega"] , main="omega" , xlab=bquote(omega) , 
          cenTend="median"  )
plotPost( codaSamples[,"eta"] , main="eta" , xlab=bquote(eta) , 
          cenTend="median"  )
plotPost( codaSamples[,"theta"] , main="theta" , xlab=bquote(theta) , 
          cenTend="median"  )
```

```{r}
summary(codaSamples)
```









