inst/study/study-functions.R

# Reproducible study helpers. These are study code, not exported package APIs.
study_design <- function() {
  data.frame(
    scenario = c("matched_50", "matched_200", "variance_50", "variance_200",
                 "heavy_t5_200", "clusters_8", "clusters_30", "clusters_100",
                 "clusters_unequal", "strong_prior_20"),
    label = c("Matched, N=50", "Matched, N=200", "Variance x4, N=50",
              "Variance x4, N=200", "t5 variance x4, N=200", "8 clusters of 10",
              "30 clusters of 10", "100 clusters of 10", "30 unequal clusters",
              "Strong prior, N=20"),
    n = c(50, 200, 50, 200, 200, 80, 300, 1000, 372, 20),
    clusters = c(0, 0, 0, 0, 0, 8, 30, 100, 30, 0),
    rho = c(rep(0, 5), rep(0.6, 4), 0),
    true_variance = c(1, 1, 4, 4, 4, rep(1, 5)),
    truth = c(rep(0, 9), 1), prior_sd = c(rep(10, 9), 0.25),
    stringsAsFactors = FALSE)
}

study_sample <- function(design, replication) {
  index <- match(design$scenario, study_design()$scenario)
  set.seed(62021L + index * 10000L + replication)
  group <- NULL
  if (design$clusters > 0) {
    sizes <- if (design$scenario == "clusters_unequal") rep(c(2L, 4L, 8L, 16L, 32L), 6) else rep(10L, design$clusters)
    group <- rep(seq_along(sizes), sizes)
    y <- design$truth + sqrt(design$rho) * rnorm(length(sizes))[group] +
      sqrt(1 - design$rho) * rnorm(length(group))
    sampling_sd <- sqrt(design$rho * sum(sizes^2) + (1 - design$rho) * sum(sizes)) /
      (length(y) + 1 / design$prior_sd^2)
  } else {
    errors <- if (design$scenario == "heavy_t5_200") rt(design$n, df = 5) * sqrt(3 / 5) else rnorm(design$n)
    y <- design$truth + sqrt(design$true_variance) * errors
    sampling_sd <- sqrt(design$n * design$true_variance) / (design$n + 1 / design$prior_sd^2)
  }
  list(y = y, group = group, sampling_sd = sampling_sd)
}

normal_oracle <- function(y, prior_sd = 10, group = NULL) {
  v <- 1 / (length(y) + 1 / prior_sd^2)
  m <- v * sum(y)
  independent <- v * sqrt(length(y) * var(y))
  clustered <- NA_real_
  if (!is.null(group)) {
    scores <- v * as.numeric(rowsum(y - m, group, reorder = FALSE))
    j <- length(scores)
    clustered <- sqrt(j / (j - 1) * sum((scores - mean(scores))^2))
  }
  list(mean = m, variance = v, posterior_sd = sqrt(v),
        ij_independent = independent, ij_cluster = clustered)
}

summarize_study <- function(long) {
  keys <- unique(long[c("scenario", "parameter", "method")])
  rows <- lapply(seq_len(nrow(keys)), function(k) {
    key <- keys[k, ]
    z <- long[long$scenario == key$scenario & long$parameter == key$parameter &
                long$method == key$method, , drop = FALSE]
    valid <- is.finite(z$estimate) & is.finite(z$se) & is.finite(z$critical)
    complete <- z[valid, , drop = FALSE]
    b <- nrow(complete)
    attempted <- nrow(z)
    if (b < 2L) stop("Fewer than two completed replications for ", key$scenario)
    empirical_sd <- sd(complete$estimate)
    bias <- mean(complete$estimate - complete$truth)
    covered <- abs(complete$estimate - complete$truth) <= complete$critical * complete$se
    p <- mean(covered)
    zz <- qnorm(0.975)
    wilson_center <- (p + zz^2 / (2 * b)) / (1 + zz^2 / b)
    wilson_half <- zz / (1 + zz^2 / b) * sqrt(p * (1 - p) / b + zz^2 / (4 * b^2))
    fourth <- mean((complete$estimate - mean(complete$estimate))^4)
    sd_mcse <- sqrt(max(0, (fourth - (b - 3) / (b - 1) * empirical_sd^4) / b)) /
      (2 * empirical_sd)
    data.frame(key, attempted = attempted, completed = b,
      bias = bias, bias_mcse = empirical_sd / sqrt(b), empirical_sd = empirical_sd,
      empirical_sd_mcse = sd_mcse, mean_se = mean(complete$se),
      mean_se_mcse = sd(complete$se) / sqrt(b), rms_se = sqrt(mean(complete$se^2)),
      se_ratio = mean(complete$se) / empirical_sd, coverage = p,
      coverage_mcse = sqrt(p * (1 - p) / b),
      coverage_lower = wilson_center - wilson_half,
      coverage_upper = wilson_center + wilson_half,
      all_attempts_coverage_lower = sum(covered) / attempted,
      all_attempts_coverage_upper = (sum(covered) + attempted - b) / attempted,
      mean_interval_length = mean(2 * complete$critical * complete$se),
      stringsAsFactors = FALSE)
  })
  do.call(rbind, rows)
}

paired_coverage <- function(long) {
  keys <- unique(long[c("scenario", "parameter")])
  comparisons <- list(c("IJ independent", "Posterior"),
                        c("IJ cluster", "IJ independent"),
                        c("IJ cluster: t reference", "IJ cluster"))
  rows <- list()
  for (k in seq_len(nrow(keys))) {
    key <- keys[k, ]
    d <- long[long$scenario == key$scenario & long$parameter == key$parameter, ]
    for (pair in comparisons) {
      if (!all(pair %in% d$method)) next
      a <- d[d$method == pair[1], ]
      b <- d[d$method == pair[2], ]
      stopifnot(!anyDuplicated(a$replication), !anyDuplicated(b$replication))
      b <- b[match(a$replication, b$replication), ]
      covered_a <- abs(a$estimate - a$truth) <= a$critical * a$se
      covered_b <- abs(b$estimate - b$truth) <= b$critical * b$se
      valid <- is.finite(a$estimate) & is.finite(a$se) &
        is.finite(b$estimate) & is.finite(b$se)
      difference <- as.numeric(covered_a[valid]) - as.numeric(covered_b[valid])
      rows[[length(rows) + 1L]] <- data.frame(key,
        comparison = paste(pair[1], "minus", pair[2]), pairs = length(difference),
        coverage_difference = mean(difference),
        paired_mcse = sd(difference) / sqrt(length(difference)), stringsAsFactors = FALSE)
    }
  }
  do.call(rbind, rows)
}

fit_accounting <- function(attempts, replicates) {
  keys <- unique(attempts[c("scenario", "replication")])
  last <- do.call(rbind, lapply(seq_len(nrow(keys)), function(i) {
    z <- attempts[attempts$scenario == keys$scenario[i] &
                    attempts$replication == keys$replication[i], ]
    z[which.max(z$attempt), ]
  }))
  do.call(rbind, lapply(unique(attempts$scenario), function(s) {
    z <- last[last$scenario == s, ]
    complete <- vapply(z$replication, function(r) {
      rows <- replicates[replicates$scenario == s & replicates$replication == r &
                           replicates$method == "Posterior", ]
      nrow(rows) == 2L && setequal(rows$parameter, c("Intercept", "Slope")) &&
        all(is.finite(rows$estimate)) && all(is.finite(rows$se))
    }, logical(1))
    # Completion is established by numerical output, not empty error strings:
    # read.csv() can coerce an entirely empty character column to logical NA.
    data.frame(scenario = s, datasets = nrow(z), completed = sum(complete),
      adequate = sum(z$adequate %in% TRUE), retries = sum(z$attempt == 2),
      retained_divergences = sum(z$divergences, na.rm = TRUE),
      maximum_retained_rhat = max(z$max_rhat, na.rm = TRUE),
      minimum_retained_bulk_ess = min(z$min_bulk_ess, na.rm = TRUE),
      total_attempts = sum(attempts$scenario == s))
  }))
}

normal_long <- function(raw, design = study_design()) {
  pieces <- list()
  for (s in unique(raw$scenario)) {
    wide <- raw[raw$scenario == s, ]
    j <- design$clusters[match(s, design$scenario)]
    methods <- c("Posterior", "IJ independent")
    columns <- c("posterior_sd", "ij_independent")
    if (j > 0) {
      methods <- c(methods, "IJ cluster", "IJ cluster: t reference")
      columns <- c(columns, "ij_cluster", "ij_cluster")
    }
    for (k in seq_along(methods)) {
      pieces[[length(pieces) + 1L]] <- data.frame(scenario = s,
        replication = wide$replication, parameter = "mu", method = methods[k],
        estimate = wide$estimate, truth = wide$truth, se = wide[[columns[k]]],
        critical = if (k == 4L) qt(0.975, j - 1) else qnorm(0.975))
    }
  }
  do.call(rbind, pieces)
}

run_normal_study <- function(output, replications = 4000L) {
  dir.create(output, recursive = TRUE, showWarnings = FALSE)
  design <- study_design()
  write.csv(design, file.path(output, "normal-design.csv"), row.names = FALSE)
  records <- vector("list", nrow(design))
  for (i in seq_len(nrow(design))) {
    config <- design[i, ]
    values <- lapply(seq_len(replications), function(r) {
      z <- study_sample(config, r)
      result <- normal_oracle(z$y, config$prior_sd, z$group)
      data.frame(scenario = config$scenario, replication = r, estimate = result$mean,
        truth = config$truth, posterior_sd = result$posterior_sd,
        ij_independent = result$ij_independent, ij_cluster = result$ij_cluster,
        exact_sampling_sd = z$sampling_sd)
    })
    wide <- do.call(rbind, values)
    records[[i]] <- wide
    cat("Normal study:", config$scenario, replications, "replications\n")
  }
  raw <- do.call(rbind, records)
  long <- normal_long(raw, design)
  summary <- summarize_study(long)
  summary$exact_sampling_sd <- vapply(summary$scenario, function(id) {
    raw$exact_sampling_sd[match(id, raw$scenario)]
  }, numeric(1))
  write.csv(raw, file.path(output, "normal-replicates.csv"), row.names = FALSE)
  write.csv(summary, file.path(output, "normal-summary.csv"), row.names = FALSE)
  write.csv(paired_coverage(long), file.path(output, "normal-paired-coverage.csv"), row.names = FALSE)
  invisible(summary)
}

run_draw_audit <- function(output, ensembles = 80L) {
  config <- study_design()[4L, ]
  z <- study_sample(config, 1L)
  exact <- normal_oracle(z$y, config$prior_sd)
  sizes <- c(200L, 1000L, 5000L, 20000L)
  records <- list()
  for (s in sizes) {
    for (r in seq_len(ensembles)) {
      set.seed(98217L + s + r)
      mu <- rnorm(s, exact$mean, sqrt(exact$variance))
      d <- cbind(mu = mu)
      reader <- function(ii) vapply(z$y[ii], function(yi) dnorm(yi, mu, log = TRUE), numeric(s))
      result <- IJSE::ijse_draws(d, reader, n_obs = length(z$y), block_size = 50,
                                 diagnostics = "none")
      ratio <- unname(result$se / exact$ij_independent)
      identity <- var(mu) / exact$variance
      stopifnot(abs(ratio - identity) < 1e-9)
      records[[length(records) + 1L]] <- data.frame(draws = s, ensemble = r,
        se_ratio = ratio, relative_error = ratio - 1, identity_error = ratio - identity)
    }
    cat("Posterior-draw audit:", s, "draws\n")
  }
  raw <- do.call(rbind, records)
  summary <- do.call(rbind, lapply(sizes, function(s) {
    v <- raw$relative_error[raw$draws == s]
    data.frame(draws = s, ensembles = length(v), mean_relative_error = mean(v),
      mean_error_mcse = sd(v) / sqrt(length(v)), relative_rmse = sqrt(mean(v^2)),
      theoretical_relative_sd = sqrt(2 / (s - 1)),
      q025 = unname(quantile(v, 0.025)), q975 = unname(quantile(v, 0.975)))
  }))
  write.csv(raw, file.path(output, "draw-audit-replicates.csv"), row.names = FALSE)
  write.csv(summary, file.path(output, "draw-audit-summary.csv"), row.names = FALSE)
  invisible(summary)
}

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.