# Checking a bounded-response model
# https://tidyecology.com/posts/checking-a-bounded-response-model/
#
# 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-14

## ---- rq-fit ----
set.seed(4231)
n   <- 300
x   <- round(runif(n, -2, 2), 3)
mu  <- plogis(0.3 + 1.0 * x)
phi <- exp(2.3 - 0.75 * x)                       # precision shrinks as the gradient rises
y   <- rbeta(n, mu * phi, (1 - mu) * phi)
Xd  <- cbind(1, x)
nll_v <- function(p) { m <- plogis(Xd %*% p[1:2]); ph <- exp(Xd %*% p[3:4])
  -sum(dbeta(y, m * ph, (1 - m) * ph, log = TRUE)) }
nll_c <- function(p) { m <- plogis(Xd %*% p[1:2]); ph <- exp(p[3])
  -sum(dbeta(y, m * ph, (1 - m) * ph, log = TRUE)) }
fv <- optim(c(0, 0, 2, 0), nll_v, method = "BFGS")
fc <- optim(c(0, 0, 2),   nll_c, method = "BFGS")
muv <- plogis(Xd %*% fv$par[1:2]); phv <- exp(Xd %*% fv$par[3:4])
muc <- plogis(Xd %*% fc$par[1:2]); phc <- exp(fc$par[3])
rq_v <- qnorm(pbeta(y, muv * phv, (1 - muv) * phv))   # full model
rq_c <- qnorm(pbeta(y, muc * phc, (1 - muc) * phc))   # constant precision
p229_shV <- signif(shapiro.test(rq_v)$p.value, 2)
p229_shC <- signif(shapiro.test(rq_c)$p.value, 2)
p229_trV <- round(abs(cor(x, rq_v^2, method = "spearman")), 3)
p229_trC <- round(abs(cor(x, rq_c^2, method = "spearman")), 3)

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- fig-rq ----
suppressWarnings(suppressMessages(library(ggplot2)))
theme_te <- function() {
  theme_minimal(base_size = 12) + theme(
    panel.grid.minor = element_blank(),
    panel.grid.major = element_line(colour = "#dad9ca", linewidth = 0.3),
    plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
    panel.background = element_rect(fill = "#f5f4ee", colour = NA),
    strip.text = element_text(colour = "#2c3a31", face = "bold"),
    axis.text  = element_text(colour = "#46604a"),
    axis.title = element_text(colour = "#2c3a31"),
    plot.title = element_text(colour = "#16241d", face = "bold"),
    legend.position = "none")
}
dr <- rbind(data.frame(x, r = rq_v, model = "Full: precision submodel"),
            data.frame(x, r = rq_c, model = "Constant precision"))
dr$model <- factor(dr$model, levels = c("Full: precision submodel", "Constant precision"))
ggplot(dr, aes(x, r, colour = model)) +
  geom_hline(yintercept = 0, colour = "#93a87f") +
  geom_point(alpha = 0.5, size = 1.4) +
  facet_wrap(~model) +
  scale_colour_manual(values = c("Full: precision submodel" = "#275139", "Constant precision" = "#b5534e")) +
  labs(x = "Environmental gradient (standardised)", y = "Randomised quantile residual",
       title = "Quantile residuals reveal ignored dispersion") +
  theme_te()

## ---- brant ----
brant_omni <- function(y, x) {
  J <- max(y); Xb <- cbind(1, x)
  bj <- matrix(NA, J - 1, 2); pil <- matrix(NA, length(y), J - 1); Winv <- vector("list", J - 1)
  for (j in 1:(J - 1)) {
    g <- glm((y > j) ~ x, family = binomial); bj[j, ] <- coef(g)
    pj <- fitted(g); pil[, j] <- pj; Winv[[j]] <- solve(t(Xb) %*% (Xb * (pj * (1 - pj))))
  }
  P <- 2 * (J - 1); V <- matrix(0, P, P)
  for (j in 1:(J - 1)) for (l in j:(J - 1)) {                 # Brant's cross-covariance
    Vjl <- t(Xb) %*% (Xb * (pil[, max(j, l)] * (1 - pil[, min(j, l)])))
    blk <- Winv[[j]] %*% Vjl %*% Winv[[l]]
    V[(2 * j - 1):(2 * j), (2 * l - 1):(2 * l)] <- blk
    if (j != l) V[(2 * l - 1):(2 * l), (2 * j - 1):(2 * j)] <- t(blk)
  }
  si <- seq(2, P, by = 2); bs <- bj[, 2]                       # slopes only
  D <- matrix(0, J - 2, length(bs)); for (k in 1:(J - 2)) { D[k, k] <- 1; D[k, k + 1] <- -1 }
  d <- D %*% bs; Cd <- D %*% V[si, si] %*% t(D)
  stat <- as.numeric(t(d) %*% solve(Cd) %*% d)
  c(chisq = stat, df = J - 2, p = pchisq(stat, J - 2, lower.tail = FALSE))
}
set.seed(4227)                                                # proportional-odds data
nO <- 260; xO <- round(runif(nO, -2, 2), 3); th <- c(-1.6, -0.4, 0.9, 2.1)
Pc <- cbind(sapply(th, function(t) plogis(t - 1.25 * xO)), 1)
yO <- apply(cbind(Pc[, 1], t(apply(Pc, 1, diff))), 1, function(p) sample(1:5, 1, prob = p))
set.seed(4228)                                                # a non-proportional counterexample
x2 <- round(runif(nO, -2, 2), 3); bj <- c(0.4, 0.9, 1.6, 2.4)
Pc2 <- cbind(sapply(1:4, function(j) plogis(th[j] - bj[j] * x2)), 1)
Pk2 <- cbind(Pc2[, 1], t(apply(Pc2, 1, diff))); Pk2 <- pmax(Pk2, 0); Pk2 <- Pk2 / rowSums(Pk2)
y2 <- apply(Pk2, 1, function(p) sample(1:5, 1, prob = p))
bpo <- brant_omni(yO, xO); bnp <- brant_omni(y2, x2)
p229_poChi <- round(bpo["chisq"], 2); p229_poP <- round(bpo["p"], 2)
p229_npChi <- round(bnp["chisq"], 1); p229_npP <- signif(bnp["p"], 2)

## ---- heldout ----
set.seed(909)
m  <- 4000
xt <- round(runif(m, -2, 2), 3)
yt <- rbeta(m, plogis(0.3 + xt) * exp(2.3 - 0.75 * xt), (1 - plogis(0.3 + xt)) * exp(2.3 - 0.75 * xt))
muvT <- plogis(cbind(1, xt) %*% fv$par[1:2]); phvT <- exp(cbind(1, xt) %*% fv$par[3:4])
mucT <- plogis(cbind(1, xt) %*% fc$par[1:2]); phcT <- exp(fc$par[3])
covV <- (yt >= qbeta(.05, muvT * phvT, (1 - muvT) * phvT)) & (yt <= qbeta(.95, muvT * phvT, (1 - muvT) * phvT))
covC <- (yt >= qbeta(.05, mucT * phcT, (1 - mucT) * phcT)) & (yt <= qbeta(.95, mucT * phcT, (1 - mucT) * phcT))
wide <- xt > 1; tight <- xt < -1
p229_covV <- round(mean(covV), 3);  p229_covC <- round(mean(covC), 3)
p229_wV   <- round(mean(covV[wide]), 3); p229_wC <- round(mean(covC[wide]), 3)
p229_tC   <- round(mean(covC[tight]), 3)

## ---- fig-calib ----
xs <- seq(-2, 2, length = 160)
mvs <- plogis(cbind(1, xs) %*% fv$par[1:2]); pvs <- exp(cbind(1, xs) %*% fv$par[3:4])
mcs <- plogis(cbind(1, xs) %*% fc$par[1:2]); pcs <- exp(fc$par[3])
db <- data.frame(xs,
  loV = qbeta(.05, mvs * pvs, (1 - mvs) * pvs), hiV = qbeta(.95, mvs * pvs, (1 - mvs) * pvs),
  loC = qbeta(.05, mcs * pcs, (1 - mcs) * pcs), hiC = qbeta(.95, mcs * pcs, (1 - mcs) * pcs))
set.seed(1); idx <- sample(m, 800)
ggplot() +
  geom_point(data = data.frame(xt = xt[idx], yt = yt[idx]), aes(xt, yt), colour = "#46604a", alpha = 0.25, size = 1) +
  geom_ribbon(data = db, aes(xs, ymin = loV, ymax = hiV, fill = "Full: precision submodel"), alpha = 0.22) +
  geom_ribbon(data = db, aes(xs, ymin = loC, ymax = hiC, fill = "Constant precision"), alpha = 0.0,
              colour = "#b5534e", linetype = "dashed", linewidth = 0.7) +
  scale_fill_manual(values = c("Full: precision submodel" = "#275139", "Constant precision" = "#b5534e")) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "Environmental gradient (standardised)", y = "Vegetation cover (proportion)",
       title = "Held-out prediction bands and the changing scatter") +
  theme_te() + theme(legend.position = "top", legend.title = element_blank(),
                     legend.text = element_text(colour = "#2c3a31"))
