tests/testthat/test-gaussian-reference.R

test_that("all supported model structures agree with dense Gaussian equations", {
  d <- vam_fixture(nstudent = 24L, nyear = 3L)
  configurations <- expand.grid(persistence = c("GP", "rGP", "CP", "VP", "ZP"),
                                REML = c(FALSE, TRUE), stringsAsFactors = FALSE)
  configurations$student.side <- "R"
  configurations <- rbind(configurations,
                          data.frame(persistence = "GP", REML = c(FALSE, TRUE),
                                     student.side = "G"))
  for (i in seq_len(nrow(configurations))) {
    cfg <- configurations[i, ]
    fit <- suppressWarnings(GPvam(d, ~as.factor(year)+x,
                                  persistence = cfg$persistence,
                                  student.side = cfg$student.side, REML = cfg$REML,
                                  max.iter.EM = 3, verbose = FALSE))
    ref <- dense_reference(fit)
    context <- paste(cfg$student.side, cfg$persistence, cfg$REML)
    expect_equal(as.numeric(fit$ybetas), ref$beta, tolerance = 1e-7, info = context)
    expect_equal(as.numeric(fit$eta.hat), ref$eta, tolerance = 1e-7, info = context)
    expect_equal(as.numeric(fit$loglik), ref$loglik, tolerance = 1e-7, info = context)
    expect_equal(unname(as.matrix(fit$betacov)), unname(ref$betacov), tolerance = 1e-7,
                 info = context)
    expect_equal(unname(as.matrix(fit$vinv)), unname(ref$Vinv), tolerance = 1e-7,
                 info = context)
    expect_equal(as.numeric(fit$yhat), as.vector(fit$X %*% ref$beta + fit$Z %*% ref$eta),
                 tolerance = 1e-7, info = context)
    p <- ncol(fit$X)
    q <- ncol(fit$Z)
    teacher_index <- if (cfg$student.side == "G") seq.int(fit$num.student+1L, q) else seq_len(q)
    sd <- sqrt(diag(ref$C)[p+teacher_index])
    expect_equal(fit$teach.effects$std_error, unname(sd), tolerance = 1e-4, info = context)
    expect_false(fit$converged, info = context)
    expect_true(all(is.finite(fit$loglik_history)), info = context)
    set.seed(1741L+i)
    bias <- bias.test.custom(fit, k_vectors = rep(1, ncol(fit$X)),
                             n_perms = 19, plot = FALSE, verbose = FALSE)
    expect_true(all(bias$permutation_results$Permutation_P_Value >= 1/20 &
                    bias$permutation_results$Permutation_P_Value <= 1), info = context)
    # Independently identify exchangeable blocks from actual teacher labels,
    # rather than reproducing the diagnostic's block-width calculation.
    permutation <- seq_len(ncol(fit$G))
    offset <- if (cfg$student.side == "G") fit$num.student else 0L
    for (year in unique(fit$teach.effects$teacher_year)) {
      effects <- fit$teach.effects
      ids <- unique(effects$teacher[effects$teacher_year == year])
      first <- which(effects$teacher_year == year & effects$teacher == ids[1])
      last <- which(effects$teacher_year == year & effects$teacher == tail(ids, 1))
      permutation[offset+first] <- offset+last
      permutation[offset+last] <- offset+first
    }
    if (offset > 1L) permutation[c(1L, offset)] <- c(offset, 1L)
    expect_equal(unname(as.matrix(fit$G[permutation, permutation])),
                 unname(as.matrix(fit$G)), tolerance = 1e-10, info = context)
  }
})

test_that("a one-year random-intercept fit matches an independent ANOVA solution", {
  # Orthogonal balanced design: ML/REML variance estimates have closed forms.
  # Between/within moments below are exact finite-sample likelihood solutions.
  groups <- 8L
  per_group <- 6L
  group_means <- seq(-2.1, 2.1, length.out = groups)
  within <- c(-0.7, -0.4, -0.1, 0.1, 0.4, 0.7)
  d <- data.frame(student = seq_len(groups*per_group),
                  teacher = rep(seq_len(groups), each = per_group), year = 1,
                  y = 3 + rep(group_means, each = per_group) + rep(within, groups))
  ss_within <- groups * sum(within^2)
  residual_var <- ss_within/(groups*(per_group-1L))
  for (reml in c(FALSE, TRUE)) {
    teacher_var <- sum(group_means^2)/(groups-as.integer(reml)) - residual_var/per_group
    fit <- GPvam(d, ~1, persistence = "CP", REML = reml,
                 max.iter.EM = 1000, tol1 = 1e-11, verbose = FALSE)
    expect_true(fit$converged)
    expect_equal(unname(coef(fit)), 3, tolerance = 1e-8)
    expect_equal(as.numeric(fit$G[1, 1]), teacher_var, tolerance = 1e-4)
    expect_equal(as.numeric(solve(fit$R.inv)[1, 1]), residual_var, tolerance = 1e-4)
    expect_equal(fit$loglik, dense_reference(fit)$loglik, tolerance = 1e-8)
    # CP, ZP, VP, GP and rGP coincide when there are no future periods.
    for (persistence in c("GP", "rGP", "VP", "ZP")) {
      same <- GPvam(d, ~1, persistence = persistence, REML = reml,
                    max.iter.EM = 1000, tol1 = 1e-11, verbose = FALSE)
      expect_equal(same$loglik, fit$loglik, tolerance = 1e-7)
      expect_equal(as.numeric(same$G[1, 1]), teacher_var, tolerance = 1e-4)
    }
  }
  default <- GPvam(d, persistence = "CP", max.iter.EM = 1000,
                   tol1 = 1e-11, verbose = FALSE)
  expect_equal(unname(coef(default)), 3, tolerance = 1e-8)
  expect_error(GPvam(d, student.side = "G"), "repeated observed scores")
})

test_that("ML and REML distinguish fixed-effect uncertainty", {
  d <- vam_fixture(nstudent = 24L, nyear = 2L)
  ml <- suppressWarnings(GPvam(d, ~as.factor(year)+x, persistence = "CP",
                               REML = FALSE, max.iter.EM = 4, verbose = FALSE))
  reml <- suppressWarnings(GPvam(d, ~as.factor(year)+x, persistence = "CP", REML = TRUE,
                                 max.iter.EM = 4, verbose = FALSE))
  expect_false(isTRUE(all.equal(as.matrix(ml$G), as.matrix(reml$G))))
  expect_equal(ml$loglik, dense_reference(ml)$loglik, tolerance = 1e-8)
  expect_equal(reml$loglik, dense_reference(reml)$loglik, tolerance = 1e-8)
})

Try the GPvam package in your browser

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

GPvam documentation built on Oct. 23, 2026, 1:06 a.m.