---
title: "Using priorsense with JAGS"
vignette: >
  %\VignetteIndexEntry{Using priorsense with JAGS}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
---


```{r}
#| include: false
ggplot2::theme_set(bayesplot::theme_default(base_family = "sans"))

options(priorsense.plot_help_text = FALSE)
```


```{r}
#| message: false
#| warning: false
library(R2jags)
library(posterior)
library(priorsense)

set.seed(123)
```

`priorsense` is compatible with models fit with either `jagsUI` or `R2jags`.

Consider the univariate normal model with unknown mu and sigma available
via`example_powerscale_model("univariate_normal")`. In JAGS, `lprior` and
`log_lik` variables can be defined as below. By also defining separate
`lprior_mu` and `lprior_sigma` variables, it will be possible to check the
sensitivity for each prior separately.

```{r}
model <- example_powerscale_model("univariate_normal", language = "jags")
```

```{r}
#| echo: false
#| results: asis
cat("```\n")
cat(model$model_code)
cat("```")
```

`R2jags::jags()` or `jagsUI::jags()` can be used to fit the model. Ensure that the required variables are monitored.

```{r}
#| message: false
#| warning: false
model_con <- textConnection(model$model_code)
data <- model$data

# monitor parameters of interest along with log-likelihood and log-prior
variables <- c("mu", "sigma", "log_lik", "lprior", "lprior_mu", "lprior_sigma")

fit <- R2jags::jags(
  data = data,
  model.file = model_con,
  parameters.to.save = variables,
  n.chains = 4,
  DIC = FALSE,
  quiet = TRUE,
  progress.bar = "none"
)
```

Then the `priorsense` functions will work as usual.

```{r}
powerscale_sensitivity(fit)
```

```{r}
powerscale_sensitivity(fit, prior_selection = "sigma")
```

```{r}
powerscale_sensitivity(fit, prior_selection = "mu")
```


```{r}
#| message: false
#| warning: false
#| fig-width: 6
#| fig-height: 4
powerscale_plot_dens(fit)
```
