tools/run-quantile-study.R

# Actual brms simulation, using estimated asymmetric-Laplace scale.
# Usage: Rscript tools/run-quantile-study.R /path/to/IJSE /path/to/output /path/to/model-cache [B]
args <- commandArgs(trailingOnly = TRUE)
stopifnot(length(args) >= 3L)
source(file.path(args[1L], "inst", "study", "study-functions.R"))
output <- normalizePath(args[2L], mustWork = TRUE)
model_dir <- normalizePath(args[3L], mustWork = TRUE)
b <- if (length(args) >= 4L) as.integer(args[4L]) else 200L
options(cmdstanr_write_stan_file_dir = model_dir)
library(brms)
library(IJSE)
stopifnot(packageVersion("IJSE") >= "0.3.0")
make_data <- function(scenario, r) {
  set.seed(182000L + if (scenario == "independent") r else 10000L + r)
  n <- if (scenario == "independent") 200L else 300L
  x <- rnorm(n)
  group <- if (scenario == "independent") seq_len(n) else rep(seq_len(30), each = 10)
  error <- if (scenario == "independent") exp(0.3 * x) * rnorm(n) else {
    sqrt(0.6) * rnorm(30)[group] + sqrt(0.4) * rnorm(n)
  }
  data.frame(y = 0.5 + 0.7 * x + error, x = x, group = group)
}
diagnose <- function(fit) {
  summaries <- posterior::summarise_draws(posterior::as_draws_array(fit))
  active <- is.finite(summaries$sd) & summaries$sd > 0
  summaries <- summaries[active, ]
  nuts <- brms::nuts_params(fit)
  rhat <- if (all(is.finite(summaries$rhat))) max(summaries$rhat) else Inf
  ess <- if (all(is.finite(summaries$ess_bulk))) min(summaries$ess_bulk) else 0
  divergences <- sum(nuts$Value[nuts$Parameter == "divergent__"])
  list(max_rhat = rhat, min_bulk_ess = ess, divergences = divergences,
        adequate = is.finite(rhat) && rhat <= 1.05 && ess >= 200 && divergences == 0)
}
base_fit <- NULL
all_attempts <- list()
all_records <- list()
for (scenario in c("independent", "clustered")) {
  for (r in seq_len(b)) {
    d <- make_data(scenario, r)
    fit <- NULL
    diagnostic <- list(max_rhat = NA_real_, min_bulk_ess = NA_real_,
                        divergences = NA_integer_, adequate = FALSE)
    elapsed <- 0
    for (attempt in 1:2) {
      # A failed retry must not inherit diagnostics from the previous fit.
      diagnostic <- list(max_rhat = NA_real_, min_bulk_ess = NA_real_,
                          divergences = NA_integer_, adequate = FALSE)
      warns <- character()
      problem <- ""
      started <- proc.time()[["elapsed"]]
      seed <- 982000L + if (scenario == "independent") r else 10000L + r
      seed <- seed + (attempt - 1L) * 100000L
      fit <- tryCatch(withCallingHandlers({
        if (is.null(base_fit)) {
          brm(bf(y ~ x, quantile = 0.5), data = d,
              family = asym_laplace(link_quantile = "identity"),
              prior = c(prior(normal(0, 2.5), class = "b"),
                        prior(normal(0, 2.5), class = "Intercept"),
                        prior(exponential(1), class = "sigma")),
              backend = "cmdstanr", chains = 2, cores = 2, seed = seed,
              iter = if (attempt == 1) 1500 else 3000,
              warmup = if (attempt == 1) 750 else 1500,
              control = list(adapt_delta = if (attempt == 1) 0.99 else 0.995,
                             max_treedepth = 12), refresh = 0,
              file = file.path(model_dir, "quantile-study-base"), file_refit = "always")
        } else {
          update(base_fit, newdata = d, recompile = FALSE, file = NULL,
                 chains = 2, cores = 2, seed = seed,
                 iter = if (attempt == 1) 1500 else 3000,
                 warmup = if (attempt == 1) 750 else 1500,
                 control = list(adapt_delta = if (attempt == 1) 0.99 else 0.995,
                                max_treedepth = 12), refresh = 0)
        }
      }, warning = function(w) {
        warns <<- c(warns, conditionMessage(w)); invokeRestart("muffleWarning")
      }), error = function(e) { problem <<- conditionMessage(e); NULL })
      elapsed <- elapsed + proc.time()[["elapsed"]] - started
      if (!is.null(fit)) {
        if (is.null(base_fit)) base_fit <- fit
        diagnostic <- diagnose(fit)
      }
      all_attempts[[length(all_attempts) + 1L]] <- data.frame(
        scenario = scenario, replication = r, attempt = attempt, seed = seed,
        max_rhat = diagnostic$max_rhat, min_bulk_ess = diagnostic$min_bulk_ess,
        divergences = diagnostic$divergences, adequate = diagnostic$adequate,
        fit_returned = !is.null(fit),
        error = problem, warning = paste(unique(warns), collapse = " | "))
      if (!is.null(fit) && diagnostic$adequate) break
    }
    estimates <- posterior_sd <- independent_se <- clustered_se <- rep(NA_real_, 2)
    if (!is.null(fit)) {
      independent <- ijse(fit, diagnostics = "posterior")
      terms <- c("b_Intercept", "b_x")
      estimates <- coef(independent)[terms]
      posterior_sd <- independent$posterior_sd[terms]
      independent_se <- independent$se[terms]
      if (scenario == "clustered") clustered_se <- ijse(fit, cluster_var = d$group,
                                                        diagnostics = "none")$se[terms]
      if (r == 1L) {
        # brms can drop variables unused by the model formula. Keep the
        # sampling-unit IDs needed to reproduce clustered IJ on the saved fit.
        stopifnot(nrow(fit$data) == nrow(d),
                  isTRUE(all.equal(fit$data$x, d$x)),
                  isTRUE(all.equal(fit$data$y, d$y)))
        fit$data$group <- d$group
        saveRDS(fit, file.path(output, paste0("quantile-", scenario, "-example.rds")), compress = "xz")
      }
    }
    methods <- c("Posterior", "IJ independent", if (scenario == "clustered") "IJ cluster")
    standard_errors <- list(posterior_sd, independent_se,
                            if (scenario == "clustered") clustered_se)
    for (j in seq_along(methods)) {
      all_records[[length(all_records) + 1L]] <- data.frame(
        scenario = scenario, replication = r, parameter = c("Intercept", "Slope"),
        method = methods[j], estimate = unname(estimates), truth = c(0.5, 0.7),
        se = unname(standard_errors[[j]]), critical = qnorm(0.975),
        adequate = diagnostic$adequate, elapsed_seconds = elapsed)
    }
    write.csv(do.call(rbind, all_attempts), file.path(output, "quantile-attempts.csv"), row.names = FALSE)
    write.csv(do.call(rbind, all_records), file.path(output, "quantile-replicates.csv"), row.names = FALSE)
    if (r %% 10L == 0L) {
      cat("QUANTILE PROGRESS", scenario, r, "/", b, "\n")
      flush.console(); gc()
    }
  }
}
raw <- do.call(rbind, all_records)
summary <- summarize_study(raw)
write.csv(summary, file.path(output, "quantile-summary.csv"), row.names = FALSE)
adequate_raw <- raw
adequate_raw$estimate[!adequate_raw$adequate] <- NA_real_
adequate_summary <- summarize_study(adequate_raw)
write.csv(adequate_summary, file.path(output, "quantile-summary-adequate.csv"), row.names = FALSE)
writeLines(c(capture.output(sessionInfo()), "", capture.output(cmdstanr::cmdstan_version())),
            file.path(output, "quantile-session.txt"))
cat("Quantile study complete.\n")

Try the IJSE package in your browser

Any scripts or data that you put into this service are public.

IJSE documentation built on Oct. 22, 2026, 5:18 p.m.