# Choosing priors: flat is not uninformative
# https://tidyecology.com/posts/choosing-priors-flat-not-uninformative/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-01

## ---- setup ----
knitr::opts_chunk$set(message = FALSE, warning = FALSE,
                      fig.width = 7.5, fig.height = 5.4, dpi = 150)
library(ggplot2)
te <- list(ink="#16241d", body="#2c3a31", forest="#275139", label="#46604a",
           sage="#93a87f", paper="#f5f4ee", line="#dad9ca", faint="#5d6b61",
           gold="#cda23f", mown="#2f8f63", terra="#b5534e")
theme_te <- function(base_size = 13) {
  theme_minimal(base_size = base_size) +
    theme(plot.background = element_rect(fill = te$paper, colour = NA),
          panel.background = element_rect(fill = te$paper, colour = NA),
          panel.grid.major = element_line(colour = te$line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          axis.text = element_text(colour = te$faint),
          axis.title = element_text(colour = te$body),
          plot.title = element_text(colour = te$ink, face = "bold"),
          plot.subtitle = element_text(colour = te$label),
          legend.text = element_text(colour = te$body),
          plot.caption = element_text(colour = te$faint, size = base_size * 0.75))
}

## ---- demo1 ----
# implied prior density of p = plogis(theta) when theta ~ N(0, s)
implied_p <- function(p, s) dnorm(qlogis(p), 0, s) / (p * (1 - p))

sig       <- c(1.5, 2.5, 10)
tail_mass <- sapply(sig, function(s) 2 * pnorm(qlogis(0.05), 0, s))  # P(p<.05 or p>.95)
names(tail_mass) <- paste0("N(0,", sig, ")")
round(tail_mass, 3)

## ---- fig-implied ----
pp  <- seq(0.001, 0.999, length.out = 600)
lev <- paste0("N(0, ", sig, ") on logit")
df1 <- do.call(rbind, lapply(seq_along(sig), function(i)
  data.frame(p = pp, dens = implied_p(pp, sig[i]), prior = factor(lev[i], levels = lev))))
ggplot(df1, aes(p, dens, colour = prior)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = setNames(c(te$forest, te$gold, te$terra), lev), name = NULL) +
  coord_cartesian(ylim = c(0, 4)) +
  labs(x = "implied occupancy / detection probability", y = "prior density",
       title = "A flat prior on the logit is a strong prior on probability",
       subtitle = "the same N(0, s) prior, viewed on the scale you actually care about") +
  theme_te() + theme(legend.position = "top")

## ---- hier-sim ----
set.seed(9)
J <- 8; nj <- 5; sigma <- 1; tau_true <- 0.15
theta_true <- rnorm(J, 0, tau_true)
ybar <- sapply(theta_true, function(m) mean(rnorm(nj, m, sigma)))
s2   <- sigma^2
round(ybar, 2)

## ---- gibbs ----
rinvgamma <- function(shape, rate) 1 / rgamma(1, shape = shape, rate = rate)

gibbs_hier <- function(prior = c("ig", "hc"), eps = 0.001, A = 1,
                       iter = 20000, warm = 5000, seed = 1) {
  prior <- match.arg(prior); set.seed(seed)
  theta <- ybar; mu <- mean(ybar); tau2 <- var(ybar); xi <- 1
  keep <- numeric(iter)
  for (t in seq_len(iter)) {
    vj <- 1 / (nj / s2 + 1 / tau2)                       # theta_j | rest
    theta <- rnorm(J, vj * (nj * ybar / s2 + mu / tau2), sqrt(vj))
    mu <- rnorm(1, mean(theta), sqrt(tau2 / J))          # mu | rest (flat prior)
    ss <- sum((theta - mu)^2)
    if (prior == "ig") {                                 # inverse-gamma on tau^2
      tau2 <- rinvgamma(eps + J / 2, eps + 0.5 * ss)
    } else {                                             # half-Cauchy(0,A) on tau
      tau2 <- rinvgamma((1 + J) / 2, 1 / xi + 0.5 * ss)
      xi   <- rinvgamma(1, 1 / tau2 + 1 / A^2)
    }
    keep[t] <- sqrt(tau2)
  }
  keep[(warm + 1):iter]
}

## ---- run ----
post <- list(
  "IG(1, 1)"          = gibbs_hier("ig", eps = 1,     seed = 11),
  "IG(0.001, 0.001)"  = gibbs_hier("ig", eps = 0.001, seed = 12),
  "half-Cauchy(0, 1)" = gibbs_hier("hc", A = 1,       seed = 13))
med <- sapply(post, median)
cri <- sapply(post, quantile, c(.025, .975))
round(rbind(median = med, cri), 3)

## ---- fig-tau ----
lv <- c("IG(1, 1) on variance", "IG(0.001, 0.001) on variance", "half-Cauchy(0, 1) on SD")
df2 <- rbind(
  data.frame(tau = post[["IG(1, 1)"]],          prior = lv[1]),
  data.frame(tau = post[["IG(0.001, 0.001)"]],  prior = lv[2]),
  data.frame(tau = post[["half-Cauchy(0, 1)"]], prior = lv[3]))
df2$prior <- factor(df2$prior, levels = lv)
ggplot(df2, aes(tau, colour = prior)) +
  geom_density(linewidth = 1, bw = 0.02, bounds = c(0, Inf)) +
  geom_vline(xintercept = tau_true, linetype = "dashed", colour = te$sage) +
  annotate("text", x = tau_true, y = Inf, label = "  true tau", hjust = 0, vjust = 1.5,
           colour = te$label, size = 3.6) +
  scale_colour_manual(values = setNames(c(te$gold, te$terra, te$forest), lv), name = NULL) +
  coord_cartesian(xlim = c(0, 1.1)) +
  labs(x = "among-group standard deviation tau", y = "posterior density",
       title = "The 'vague' variance prior is not noninformative",
       subtitle = "same 8-group data: three attempts at a vague prior give three answers") +
  theme_te() + theme(legend.position = "top")
