tools/audit-deep.R

# Scale-sensitive independent oracle and joint empirical-reweighting checks.
# Usage after installation: Rscript tools/audit-deep.R output.csv [cases]
args <- commandArgs(trailingOnly = TRUE)
stopifnot(length(args) >= 1L)
library(IJSE)
cases <- if (length(args) > 1L) as.integer(args[2]) else 240L
stopifnot(length(cases) == 1L, is.finite(cases), cases >= 1L)
set.seed(73334)
records <- list()
check <- function(case, category, actual, expected, tolerance = 1e-9) {
  stopifnot(identical(dim(actual), dim(expected)), length(actual) == length(expected))
  error <- max(abs(as.numeric(actual) - as.numeric(expected))) /
    max(1e-12, max(abs(as.numeric(expected))))
  if (!is.finite(error) || error > tolerance) {
    stop("Case ", case, " / ", category, ": relative discrepancy ", error)
  }
  records[[length(records) + 1L]] <<- data.frame(case = as.character(case),
    category = category, relative_error = error, tolerance = tolerance)
}
oracle <- function(d, ll, ids = NULL) {
  p <- ncol(d)
  centered_d <- sweep(d, 2, colMeans(d), "-")
  centered_ll <- sweep(ll, 2, colMeans(ll), "-")
  contributions <- crossprod(centered_d, centered_ll) / (nrow(d) - 1)
  if (!is.null(ids)) {
    contributions <- matrix(vapply(unique(ids), function(id) {
      rowSums(contributions[, which(ids == id), drop = FALSE])
    }, numeric(p)), nrow = p)
  }
  k <- ncol(contributions)
  centered <- sweep(contributions, 1, rowMeans(contributions), "-")
  covariance <- k / (k - 1) * tcrossprod(centered)
  list(vcov = covariance, influence = k * contributions,
       posterior = crossprod(centered_d) / (nrow(d) - 1))
}
for (case in seq_len(cases)) {
  s <- sample(c(2L, 3L, 9L, 36L, 128L), 1)
  n <- sample(c(2L, 3L, 5L, 16L, 39L), 1)
  p <- sample(c(1L, 2L, 3L, 8L), 1)
  d <- matrix(rnorm(s * p), s, p)
  colnames(d) <- paste0("p", seq_len(p))
  if (p > 1 && case %% 4 == 0) d[, p] <- d[, 1] + 1e-6 * d[, p]
  if (p > 1 && case %% 7 == 0) d[, p] <- 3
  ll <- matrix(rnorm(s * n), s, n)
  j <- sample.int(n - 1, 1) + 1
  ids <- sample(rep(seq_len(j), length.out = n))
  ds <- 2^sample(seq(-200, 200, by = 40), 1)
  ls <- 2^sample(seq(-200, 200, by = 40), 1)
  factor <- ds * ls
  scaled_d <- d * ds
  scaled_ll <- ll * ls
  rownames(scaled_ll) <- paste0("s", seq_len(s))
  if (case %% 2 == 0) rownames(scaled_d) <- rownames(scaled_ll)
  for (group in list(NULL, ids)) {
    tag <- if (is.null(group)) "independent" else "clustered"
    expected <- oracle(d, ll, group)
    result <- ijse_draws(scaled_d, scaled_ll, group, save_influence = TRUE,
                         diagnostics = "none")
    check(case, paste(tag, "scaled covariance"), vcov(result) / factor^2, expected$vcov)
    check(case, paste(tag, "scaled SE"), unname(result$se / abs(factor)),
          sqrt(diag(expected$vcov)))
    check(case, paste(tag, "scaled posterior covariance"),
          vcov(result, type = "posterior") / ds^2, expected$posterior)
    check(case, paste(tag, "scaled estimate"), unname(coef(result) / ds), unname(colMeans(d)))
    check(case, paste(tag, "scaled influence"), influence(result) / factor, expected$influence)
    for (block in unique(c(1L, 3L, n + 1L))) {
      streamed <- ijse_draws(scaled_d, function(ii) scaled_ll[, ii, drop = FALSE],
        group, n_obs = n, block_size = block, save_influence = TRUE, diagnostics = "none")
      check(case, paste(tag, "block", block), vcov(streamed) / factor^2, expected$vcov)
      check(case, paste(tag, "block influence", block),
            influence(streamed) / factor, expected$influence)
    }
    perm <- sample.int(s)
    reordered <- ijse_draws(scaled_d[perm, , drop = FALSE],
      scaled_ll[perm, , drop = FALSE], group, diagnostics = "none")
    check(case, paste(tag, "joint draw permutation"), vcov(reordered) / factor^2, expected$vcov)
    a <- matrix(rnorm(2 * p), 2, p)
    transformed <- ijse_draws(scaled_d, scaled_ll, group,
      transform = function(x) x %*% t(a), diagnostics = "none")
    check(case, paste(tag, "joint contrast"), vcov(transformed) / factor^2,
          a %*% expected$vcov %*% t(a))
    eig <- eigen(vcov(result) / factor^2, symmetric = TRUE, only.values = TRUE)$values
    stopifnot(min(eig) >= -1e-10 * max(1, max(abs(eig))))
  }
}

# A simultaneous perturbation of every unit tests joint nonlinear quantities.
# Normalized finite empirical weights use S, whereas IJSE covariance uses S-1.
for (case in seq_len(40L)) {
  d <- cbind(a = rnorm(240, sd = 0.3), b = rnorm(240, sd = 0.4))
  d[, 2] <- 0.6 * d[, 1] + d[, 2]
  y <- rnorm(9)
  x <- seq(-1, 1, length.out = 9)
  ll <- vapply(seq_along(y), function(i) dnorm(y[i], d[, 1] + d[, 2] * x[i], log = TRUE),
               numeric(nrow(d)))
  fun <- function(z) cbind(product = z[, 1] * z[, 2],
                          probability = plogis(z[, 1] + z[, 2]),
                          exponential = exp(0.1 * z[, 1]))
  g <- fun(d)
  for (group in list(NULL, rep(c("a", "b", "c"), 3))) {
    result <- ijse_draws(d, ll, group, transform = fun, save_influence = TRUE,
                         diagnostics = "none")
    expected <- oracle(g, ll, group)
    check(paste0("nonlinear-", case), "full covariance", vcov(result), expected$vcov)
    direction <- rnorm(result$n_units)
    obs_direction <- if (is.null(group)) direction else direction[match(group, unique(group))]
    perturbation <- drop(ll %*% obs_direction)
    weighted_mean <- function(h) {
      logw <- h * perturbation
      w <- exp(logw - max(logw))
      colSums(g * w) / sum(w)
    }
    derivative <- drop(influence(result) %*% direction) / result$n_units *
      (nrow(d) - 1) / nrow(d)
    for (h in c(1e-4, 1e-5)) {
      finite <- (weighted_mean(h) - weighted_mean(-h)) / (2 * h)
      check(paste0("nonlinear-", case), paste("joint derivative", h),
            unname(derivative), unname(finite), tolerance = 2e-6)
    }
  }
}
out <- do.call(rbind, records)
write.csv(out, args[1], row.names = FALSE)
cat("IJSE", as.character(packageVersion("IJSE")), "\n")
cat(cases, "scaled configurations; 40 joint nonlinear perturbation configurations.\n")
cat(nrow(out), "comparisons passed; max relative discrepancy", max(out$relative_error), "\n")
print(aggregate(relative_error ~ category, out, max))

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.