tests/testthat/test-study.R

test_that("normal-study oracle agrees with exact posterior covariance moments", {
  helpers <- study_helpers()
  design <- helpers$study_design()
  for (i in seq_len(nrow(design))) {
    config <- design[i, ]
    z <- helpers$study_sample(config, 1)
    exact <- helpers$normal_oracle(z$y, config$prior_sd, z$group)
    # A symmetric moment probe, not claimed to be random posterior samples:
    # its sample variance is exactly v and third central moment exactly zero.
    nodes <- exact$mean + sqrt(exact$variance) * c(-1, 0, 1)
    ll <- vapply(z$y, function(yi) dnorm(yi, nodes, log = TRUE), numeric(3))
    result <- ijse_draws(cbind(mu = nodes), ll, diagnostics = "none")
    expect_equal(unname(result$se), exact$ij_independent, tolerance = 1e-10)
    if (!is.null(z$group)) {
      clustered <- ijse_draws(cbind(mu = nodes), ll, cluster_var = z$group,
                               diagnostics = "none")
      expect_equal(unname(clustered$se), exact$ij_cluster, tolerance = 1e-10)
    }
  }
})

test_that("study summaries preserve unavailable fits and Monte Carlo precision", {
  h <- study_helpers()
  d <- data.frame(scenario = "test", parameter = "mu", method = "IJ", truth = 0,
                   estimate = c(-1, 0, 1, NA), se = 1, critical = 1.96)
  s <- h$summarize_study(d)
  expect_equal(s$attempted, 4)
  expect_equal(s$completed, 3)
  expect_equal(s$coverage, 1)
  expect_equal(s$all_attempts_coverage_lower, 0.75)
  expect_equal(s$all_attempts_coverage_upper, 1)
  expect_lt(s$coverage_lower, 1)
  expect_equal(s$bias_mcse, sd(c(-1, 0, 1)) / sqrt(3))
})

test_that("coverage comparisons use paired Monte Carlo errors", {
  h <- study_helpers()
  a <- data.frame(scenario = "test", parameter = "mu", method = "Posterior",
                   replication = 1:4, estimate = c(0, 3, 0, 3), truth = 0, se = 1, critical = 1.96)
  b <- a
  b$method <- "IJ independent"
  b$estimate <- c(0, 0, 3, 3)
  result <- h$paired_coverage(rbind(a, b[4:1, ]))
  expect_equal(result$coverage_difference, 0)
  expect_equal(result$paired_mcse, sd(c(0, 1, -1, 0)) / 2)
  expect_equal(result$pairs, 4)
})

test_that("fit accounting does not confuse empty CSV fields with failed fits", {
  h <- study_helpers()
  attempts <- data.frame(scenario = "test", replication = 1:4, attempt = 1,
    adequate = c(TRUE, TRUE, TRUE, FALSE), error = NA, divergences = 0,
    max_rhat = 1.01, min_bulk_ess = 400)
  d <- data.frame(scenario = "test", replication = rep(1:4, each = 2),
    parameter = rep(c("Intercept", "Slope"), 4), method = "Posterior",
    estimate = c(rep(0, 6), NA, NA), se = 1)
  result <- h$fit_accounting(attempts, d)
  expect_equal(result$completed, 3)
  expect_equal(result$adequate, 3)
  expect_equal(result$total_attempts, 4)
})

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.