## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE,
  fig.width = 7, fig.height = 4.2, dpi = 150, fig.align = "center"
)
set.seed(2026)

## -----------------------------------------------------------------------------
library(mixqrgate)
library(ggplot2)

## ----fit----------------------------------------------------------------------
d <- sim_gate2(n = 600, gamma = c(0, 1.5))
fit <- mixqrgate(y ~ x, data = d, gating = ~ z, G = 2, tau = 0.5,
                 variance = "louis")
summary(fit)

## ----vary---------------------------------------------------------------------
dh <- sim_gate2(n = 1000, gamma = c(0, 1), sigma = c(1, 3),
                loc_vary = 2.5, het = TRUE)               # location-coupled gate
fitv <- mixqrgate(y ~ x, data = dh, gating = ~ z, G = 2,
                  tau = c(0.1, 0.25, 0.5, 0.75, 0.9),
                  vary_gating = "discrete")
round(fitv$gate_prob, 3)

## ----gateplot, fig.alt = "Class-average gate probability against the quantile level with uncertainty bands."----
gate_band <- function(fit, comp = 2, R = 400) {
  do.call(rbind, lapply(seq_along(fit$tau_grid), function(g) {
    gam <- as.numeric(fit$gamma[, , g]); V <- fit$gate_vcov[[g]]
    L <- chol(V + 1e-8 * diag(nrow(V)))
    draws <- sapply(seq_len(R), function(r) {
      gd <- matrix(gam + as.numeric(crossprod(L, rnorm(length(gam)))),
                   length(fit$znames))
      mean(mixqrgate:::gate_predict(gd, fit$z)[, comp])
    })
    data.frame(tau = fit$tau_grid[g], prob = mean(draws),
               lo = quantile(draws, .025), hi = quantile(draws, .975))
  }))
}
gb <- gate_band(fitv)

ggplot(gb, aes(tau, prob)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = "#1b6ca8", alpha = 0.2) +
  geom_line(linewidth = 1.1, colour = "#1b6ca8") +
  geom_point(size = 2.4, colour = "#1b6ca8") +
  ylim(0, 1) +
  labs(x = expression(tau), y = "Class-average gate probability (component 2)",
       title = "Is the gate location-varying?",
       subtitle = "Point estimates per quantile, with simulated uncertainty bands") +
  theme_minimal(base_size = 12)

