tests/testthat/test-trex_gvs.R

# =======================================================================================
# TRexGVSSelector - Unit tests
# =======================================================================================

# A base control for the GVS selector: a control that is passed names a solver of the track.
.gvs_base <- function(gvs_type = "EN", ...) {
  trex_control(solver = if (gvs_type == "IEN") "TIENET" else "TENET", ...)
}

test_that("TRexGVSSelector instantiation and dimensional validation work", {

  set.seed(42)
  n <- 50
  p <- 20
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)

  # 1. Valid instantiation
  expect_silent(TRexGVSSelector$new(X, y, verbose = FALSE, gvs_control = trex_gvs_control(gvs_type = "EN")))

  # 2. Dimension mismatch (y length != X rows)
  y_bad <- rnorm(n + 10)
  expect_error(
    TRexGVSSelector$new(X, y_bad, verbose = FALSE, gvs_control = trex_gvs_control(gvs_type = "EN")),
    "length equal to the number of rows"
  )

  # 3. Degenerate feature matrix dimensions (n=0 or p=0)
  X_empty <- matrix(numeric(0), nrow = 0, ncol = p)
  y_empty <- numeric(0)
  expect_error(
    TRexGVSSelector$new(X_empty, y_empty, verbose = FALSE, gvs_control = trex_gvs_control(gvs_type = "EN")),
    "non-zero dimensions"
  )

  # 4. Non-finite values in the response vector (NaN or Inf)
  y_na <- y
  y_na[1] <- NA
  expect_error(
    TRexGVSSelector$new(X, y_na, verbose = FALSE, gvs_control = trex_gvs_control(gvs_type = "EN")),
    "NaN or Inf values"
  )

})



test_that("TRexGVSSelector executes correctly with valid data", {
  set.seed(42)
  n <- 50
  p <- 20
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)

  # Inject some strong signals in the first 3 variables
  y <- X[, 1] * 5 + X[, 2] * -4 + X[, 3] * 3 + rnorm(n)

  # Instantiate TRex selector
  selector <- TRexGVSSelector$new(X, y, tFDR = 0.1, verbose = FALSE,
                                  gvs_control = trex_gvs_control(gvs_type = "IEN"),
                                  control = .gvs_base("IEN", K = 5))

  # Execute variable selection
  selector$select()

  # Assert result structure and logic
  res_indices <- selector$selected_indices
  res_T_stop <- selector$T_stop

  expect_type(res_indices, "integer")

  expect_type(res_T_stop, "integer")

  # Bounds check on output selected indices (1 <= index <= p)
  expect_true(all(res_indices >= 1 & res_indices <= p))
})



test_that("TRexGVSSelector handles concurrent execution properly (OpenMP)", {

  set.seed(42)
  n <- 50
  p <- 10
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)

  # Ensure the object can be created and bound appropriately with concurrency settings
  selector_openmp <- expect_no_error(
    TRexGVSSelector$new(X, y,
                        gvs_control = trex_gvs_control(gvs_type = "IEN"),
                        control = .gvs_base("IEN", K = 5, parallel_rnd_experiments = TRUE,
                                            max_inner_threads = 2, max_outer_threads = 2),
                        verbose = FALSE)
  )

  # Run the algorithm targeting out threaded branches; fall back if openMP is disabled
  selector_openmp$select()

  res_openmp_indices <- selector_openmp$selected_indices
  res_openmp_T_stop <- selector_openmp$T_stop


  expect_type(res_openmp_indices, "integer")

  expect_type(res_openmp_T_stop, "integer")
})



test_that("TRexGVSSelector correctly guards against invalid parameters", {
  set.seed(42)
  n <- 50
  p <- 10
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)

  # Unsupported L-Loop Strategy
  expect_error(
    TRexGVSSelector$new(X, y, gvs_control = trex_gvs_control(gvs_type = "EN"),
                        control = .gvs_base("EN", lloop_strategy = "PERMUTATION"), verbose = FALSE),
    "are not supported"
  )

  # Invalid Hierarchical Control Parameters
  expect_error(
    TRexGVSSelector$new(X, y, gvs_control = trex_gvs_control(gvs_type = "EN", corr_max = -0.1), verbose = FALSE),
    "corr_max"
  )
  expect_error(
    TRexGVSSelector$new(X, y, gvs_control = trex_gvs_control(gvs_type = "EN", corr_max = 1.1), verbose = FALSE),
    "corr_max"
  )

  # Invalid linkage triggers Rcpp stop()
  expect_error(
    TRexGVSSelector$new(X, y, gvs_control = trex_gvs_control(gvs_type = "EN", hc_linkage = "UNKNOWN_LINKAGE"),
        verbose = FALSE),
    "Unsupported linkage method for GVS"
  )

  # Negative lambda_2 is the auto-determination sentinel (not an error)
  expect_no_error(
    TRexGVSSelector$new(X, y, gvs_control = trex_gvs_control(gvs_type = "EN", lambda_2 = -1.0), verbose = FALSE)
  )
})


test_that("TRexGVSSelector refuses a base control whose solver does not fit the track", {
  set.seed(42)
  n <- 50
  p <- 10
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)
  X0 <- X + 0
  new_gvs <- function(gvs_control, control = NULL) {
    TRexGVSSelector$new(X, y, gvs_control = gvs_control, control = control, verbose = FALSE)
  }
  en <- trex_gvs_control(gvs_type = "EN")
  aug <- trex_gvs_control(gvs_type = "EN", en_solver = "TENET_AUG")
  ien <- trex_gvs_control(gvs_type = "IEN")

  # EN: the base control keeps "TENET" or names the solver of en_solver. Every
  # other solver is an error, also "TLARS", the default of trex_control()
  for (solver in c("TLARS", "TLASSO", "TOMP", "TIENET", "TENET_AUG")) {
    expect_error(new_gvs(en, trex_control(solver = solver)),
                 "control\\$solver must be \"TENET\" for gvs_type = \"EN\". Got: \"", info = solver)
    expect_error(new_gvs(en, trex_control(solver = solver)), solver, fixed = TRUE, info = solver)
  }
  expect_error(new_gvs(en, trex_control()), "leave control out")
  expect_error(new_gvs(aug, trex_control(solver = "TLARS")),
               "control\\$solver must be \"TENET\" or \"TENET_AUG\" for gvs_type = \"EN\"")

  # IEN: the base control names the solver, so the track needs a base control
  for (solver in c("TLARS", "TOMP", "TENET", "TENET_AUG")) {
    expect_error(new_gvs(ien, trex_control(solver = solver)),
                 "gvs_type = \"IEN\" needs a base control that names its solver", info = solver)
  }
  expect_error(new_gvs(ien), "No control was passed")

  # The power rule takes the two controls the same way
  expect_error(trex_gvs_lambda2_power_rule(X, y, gvs_control = en, control = trex_control(), grid = c(0, 1)),
               "control\\$solver must be \"TENET\"")
  expect_error(trex_gvs_lambda2_power_rule(X, y, gvs_control = ien, grid = c(0, 1)), "No control was passed")

  # No selector was built, so the design is untouched
  expect_identical(X, X0)

  # What fits the track is taken without a warning
  fits <- list(list(en, NULL), list(en, trex_control(solver = "TENET")),
               list(aug, NULL), list(aug, trex_control(solver = "TENET")),
               list(aug, trex_control(solver = "TENET_AUG")),
               list(ien, trex_control(solver = "TIENET")), list(ien, trex_control(solver = "TIENET_AUG")))
  for (case in fits) {
    expect_no_warning(new_gvs(case[[1]], case[[2]])$restore())
  }
  expect_no_warning(quiet_cd(new_gvs(ien, trex_control(solver = "TCDIENET"))$restore()))
  expect_equal(X, X0, tolerance = 1e-12)

  # Without a base control the one of the C++ class applies, whose solver is
  # TENET: the run equals the one with the defaults of trex_control() and TENET
  run <- function(control) {
    s <- TRexGVSSelector$new(X, y, tFDR = 0.2, seed = 3, verbose = FALSE,
                             gvs_control = trex_gvs_control(lambda_2 = 1), control = control)
    s$select()
    s$selected_var
  }
  expect_identical(run(NULL), run(trex_control(solver = "TENET")))
})


test_that("TRexGVSSelector warns when lambda_2 == 0 (degenerate no-ridge)", {
  set.seed(42)
  n <- 50
  p <- 10
  y <- rnorm(n)
  # Each live selector needs its own X buffer (shared-buffer claim guard).
  fresh <- function() matrix(rnorm(n * p), n, p)

  expect_warning(
    TRexGVSSelector$new(fresh(), y,
                        gvs_control = trex_gvs_control(gvs_type = "EN", lambda_2 = 0),
                        verbose = FALSE),
    "degenerate no-ridge"
  )
  # Auto (-1) and fixed positive must not warn
  expect_no_warning(
    TRexGVSSelector$new(fresh(), y,
                        gvs_control = trex_gvs_control(gvs_type = "EN", lambda_2 = -1),
                        verbose = FALSE)
  )
  expect_no_warning(
    TRexGVSSelector$new(fresh(), y,
                        gvs_control = trex_gvs_control(gvs_type = "EN", lambda_2 = 0.05),
                        verbose = FALSE)
  )
})



test_that("TRexGVSSelector handles manual grouping vectors correctly", {
  set.seed(42)
  n <- 50
  p <- 10
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)

  # Wrong length for groups
  expect_error(
    TRexGVSSelector$new(X, y, gvs_control = trex_gvs_control(gvs_type = "EN", groups = c(1, 2)), verbose = FALSE),
    "groups must have one entry per variable (p = 10). Got: 2.", fixed = TRUE
  )

  # The control checks the numbering with the words of the R argument:
  # a gap (1 and 3, no 2), a start at 0, a fraction and a missing value
  numbering <- "groups must number the groups 1 to M without gaps"
  expect_error(trex_gvs_control(groups = rep(c(1, 3), length.out = p)), numbering, fixed = TRUE)
  expect_error(trex_gvs_control(groups = rep(c(0, 1), length.out = p)), numbering, fixed = TRUE)
  expect_error(trex_gvs_control(groups = rep(c(1, 1.5), length.out = p)), numbering, fixed = TRUE)
  expect_error(trex_gvs_control(groups = c(1, NA, 2)), numbering, fixed = TRUE)
  expect_error(trex_gvs_control(groups = "a"), numbering, fixed = TRUE)

  # Valid numberings pass, in any order
  expect_no_error(trex_gvs_control(groups = rep(c(2, 1, 3), length.out = p)))
  expect_no_error(trex_gvs_control(groups = rep(1L, p)))
})



test_that("TRexGVSSelector behaves memory safe with memory mapping enabled", {
  set.seed(42)
  n <- 50
  p <- 20
  X <- matrix(rnorm(n * p), n, p)
  y <- rnorm(n)

  # Use use_memory_mapping = TRUE to confirm tempdir() doesn't crash
  selector <- TRexGVSSelector$new(X, y, verbose = FALSE,
                                  gvs_control = trex_gvs_control(gvs_type = "IEN"),
                                  control = .gvs_base("IEN", K = 3, use_memory_mapping = TRUE))
  selector$select()

  res_indices <- selector$selected_indices
  res_T_stop <- selector$T_stop

  expect_type(res_indices, "integer")

})


test_that("TRexGVSSelector selected_var and selected_indices are consistent (1-based)", {
  set.seed(42)
  n <- 50
  p <- 20
  X <- matrix(rnorm(n * p), n, p)
  y <- X[, 1] * 5 + X[, 2] * -4 + X[, 3] * 3 + rnorm(n)

  for (gvs in c("EN", "IEN")) {
    sel <- TRexGVSSelector$new(X, y, tFDR = 0.1, verbose = FALSE,
                               gvs_control = trex_gvs_control(gvs_type = gvs),
                               control = .gvs_base(gvs, K = 3))
    sel$select()

    idx <- sel$selected_indices
    sv  <- sel$selected_var

    expect_type(idx, "integer")
    expect_length(sv, p)

    expect_true(all(idx >= 1L & idx <= p), label = paste(gvs, "1-based in [1,p]"))
    expect_equal(sort(idx), which(sv), label = paste(gvs, "consistency"))
  }
})


test_that("TRexGVSSelector phi_prime is at most 1 and phi_mat has correct dimensions", {
  set.seed(42)
  n <- 50
  p <- 20
  X <- matrix(rnorm(n * p), n, p)
  y <- X[, 1] * 5 + X[, 2] * -4 + rnorm(n)

  selector <- TRexGVSSelector$new(X, y, tFDR = 0.1, verbose = FALSE,
                                  gvs_control = trex_gvs_control(gvs_type = "IEN"),
                                  control = .gvs_base("IEN", K = 3))
  selector$select()

  phi_p <- selector$phi_prime
  expect_length(phi_p, p)
  expect_true(all(phi_p <= 1.0))  # capped at 1, may be negative

  ts <- selector$T_stop
  pm <- selector$phi_mat
  if (ts > 0L) {
    expect_gte(nrow(pm), 1L)
    expect_equal(ncol(pm), p)
  }
})


test_that("TRexGVSSelector GVS-specific fields have valid values", {
  set.seed(42)
  n <- 50
  p <- 20
  X <- matrix(rnorm(n * p), n, p)
  y <- X[, 1] * 5 + X[, 2] * -4 + rnorm(n)

  for (gvs in c("EN", "IEN")) {
    sel <- TRexGVSSelector$new(X, y, verbose = FALSE,
                               gvs_control = trex_gvs_control(gvs_type = gvs),
                               control = .gvs_base(gvs, K = 3))
    sel$select()

    expect_equal(sel$gvs_type, gvs, label = paste(gvs, "gvs_type roundtrip"))

    mc <- sel$max_clusters
    expect_type(mc, "integer")
    expect_true(mc >= 1L & mc <= p, label = paste(gvs, "max_clusters in [1,p]"))

    expect_true(sel$lambda2_used >= 0.0, label = paste(gvs, "lambda2_used >= 0"))
  }
})


test_that("TRexScreeningSelector correctly executes confidence-based bootstrapping", {
  set.seed(42)
  n <- 50
  p <- 10
  X <- matrix(rnorm(n * p), n, p)

  y <- X[, 1] * 5 + X[, 2] * -4 + rnorm(n)

  # Instantiate with CI Bootstrapping active
  selector_boot <- expect_no_error(
    TRexScreeningSelector$new(
      X, y,
      screen_control = trex_screen_control(use_bootstrap_CI = TRUE, R_boot = 100, ci_grid_step = 0.01),
      verbose = FALSE
    )
  )

  selector_boot$select()

  # Assert result structure includes Bootstrap diagnostics
  res_boot_used <- selector_boot$used_bootstrap
  res_boot_conf <- selector_boot$confidence_level
  res_boot_fdr <- selector_boot$estimated_FDR
  expect_true(res_boot_used)
  expect_type(res_boot_conf, "double")

  # Ensure FDR is bounded properly
  expect_true(res_boot_fdr >= 0.0 && res_boot_fdr <= 1.0)
})


test_that("TRexGVSSelector honors tenet_aug_use_lars (LARS vs LASSO inner path)", {
  set.seed(42)
  n <- 60; p <- 15
  X <- matrix(rnorm(n * p), n, p)
  y <- as.numeric(X[, 1] * 3 + X[, 2] * -2 + X[, 5] * 2 + rnorm(n))

  # tenet_aug_use_lars is the LARS-vs-LASSO inner-path switch for TENET_AUG.
  # (en_solver TENET vs TENET_AUG is an equivalence knob, NOT this distinction.)
  ctrl_lasso <- trex_gvs_control(gvs_type = "EN", en_solver = "TENET_AUG",
                                 tenet_aug_use_lars = FALSE)
  ctrl_lars  <- trex_gvs_control(gvs_type = "EN", en_solver = "TENET_AUG",
                                 tenet_aug_use_lars = TRUE)
  expect_false(ctrl_lasso$tenet_aug_use_lars)
  expect_true(ctrl_lars$tenet_aug_use_lars)

  # Each selector normalizes its X buffer in place, so run them one at a time
  # (a helper that constructs, selects, and returns the result) rather than
  # holding two live selectors on the same matrix (shared-buffer claim guard).
  run <- function(ctrl) {
    s <- TRexGVSSelector$new(X, y, tFDR = 0.2, seed = 1, verbose = FALSE,
                             gvs_control = ctrl)
    s$select()
    sort(s$selected_indices)
  }
  sel_lasso <- run(ctrl_lasso)
  sel_lars  <- run(ctrl_lars)
  expect_type(sel_lasso, "integer")
  expect_type(sel_lars, "integer")
})


test_that("trex_gvs_control exposes and coerces the CV fold controls", {
  ctrl <- trex_gvs_control(cv_n_folds = 5, cv_n_lambda = 200, cv_seed = 123)
  expect_identical(ctrl$cv_n_folds, 5L)
  expect_identical(ctrl$cv_n_lambda, 200L)
  expect_identical(ctrl$cv_seed, 123L)

  # Defaults mirror the C++ core (cv.glmnet-style 10 folds, 1000-point grid,
  # -1 = derive fold seed from the T-Rex seed).
  d <- trex_gvs_control()
  expect_identical(d$cv_n_folds, 10L)
  expect_identical(d$cv_n_lambda, 1000L)
  expect_identical(d$cv_seed, -1L)
})


test_that("cv_seed makes EN-CV lambda_2 selection reproducible per trial", {
  set.seed(42)
  n <- 60; p <- 15
  X <- matrix(rnorm(n * p), n, p)
  y <- as.numeric(X[, 1] * 3 + X[, 2] * -2 + X[, 5] * 2 + rnorm(n))

  # An explicit cv_seed pins the CV fold permutation, so two independent runs
  # with the same cv_seed must select the same variables. Each selector needs
  # its own X copy (shared-buffer claim guard).
  run <- function(cv_seed) {
    s <- TRexGVSSelector$new(
      matrix(X, n, p), y, tFDR = 0.2, seed = 1, verbose = FALSE,
      gvs_control = trex_gvs_control(gvs_type = "EN", lambda_2 = -1.0,
                                     cv_seed = cv_seed)
    )
    s$select()
    sort(s$selected_indices)
  }
  expect_identical(run(777), run(777))
})


test_that("TRexGVSSelector exposes per-variable cluster labels (groups)", {
  set.seed(42)
  n <- 60; p <- 12
  X <- matrix(rnorm(n * p), n, p)
  y <- as.numeric(X[, 1] * 3 + X[, 2] * -2 + X[, 5] * 2 + rnorm(n))

  # Route 1 (prior groups): the exposed labels must round-trip exactly, so the
  # R side can compute real cluster diagnostics (purity) instead of a stand-in.
  prior <- rep(1:4, each = 3)  # 4 clusters of 3, 1-based
  s <- TRexGVSSelector$new(X, y, tFDR = 0.2, seed = 1, verbose = FALSE,
                           gvs_control = trex_gvs_control(gvs_type = "EN",
                                                          groups = prior))
  s$select()

  g <- s$groups
  expect_type(g, "integer")
  expect_length(g, p)
  expect_true(all(g >= 1L))                       # 1-based on the R side
  expect_identical(g, as.integer(prior))          # prior labels preserved
  expect_identical(length(unique(g)), s$max_clusters)

  # Real HAC-style purity is now computable from groups (no fabricated number).
  purity <- max(table(g)) / p
  expect_gte(purity, 0); expect_lte(purity, 1)
})


test_that("TRexGVSSelector names the origin of its groups and the supplied lambda_2", {
  set.seed(42)
  n <- 60
  p <- 12
  X <- matrix(rnorm(n * p), n, p)
  y <- X[, 1] * 3 + X[, 5] * -2 + rnorm(n)

  s <- TRexGVSSelector$new(X, y, seed = 1, verbose = FALSE,
                           gvs_control = trex_gvs_control(groups = rep(1:4, each = 3), lambda_2 = 1),
                           control = .gvs_base(K = 3))
  s$select()
  expect_identical(s$hc_method_used, "prior")
  expect_equal(s$max_clusters, 4)
  expect_identical(s$lambda2_used, 1)
  expect_false(s$lambda2_cv_diagnostics$ran)

  # Without groups the field holds the linkage, spelled as the control takes it
  for (linkage in c("single", "complete", "average", "wpgma")) {
    s <- TRexGVSSelector$new(X, y, seed = 1, verbose = FALSE,
                             gvs_control = trex_gvs_control(hc_linkage = linkage, lambda_2 = 1),
                             control = .gvs_base(K = 3))
    s$select()
    expect_identical(s$hc_method_used, linkage)
    expect_length(s$group_labels, 0L)
  }
})


test_that("the controls take the linkage in lower case and accept the names of 2.0.1", {
  # The default and the stored spelling of the three controls
  expect_identical(trex_da_control()$hc_linkage, "single")
  expect_identical(trex_gvs_control()$hc_linkage, "single")
  expect_identical(trex_tikhonov_control(tikhonov_K = diag(4))$hc_linkage, "single")
  for (old in c("Single", "Complete", "Average", "WPGMA")) {
    expect_identical(trex_da_control(hc_linkage = old)$hc_linkage, tolower(old))
    expect_identical(trex_gvs_control(hc_linkage = old)$hc_linkage, tolower(old))
    expect_identical(trex_tikhonov_control(tikhonov_K = diag(4), hc_linkage = old)$hc_linkage, tolower(old))
  }
  expect_error(trex_tikhonov_control(tikhonov_K = diag(4), hc_linkage = "ward"), "arg")

  # Both spellings give the same run, also for a control list built by hand
  set.seed(42)
  n <- 60
  p <- 12
  X <- matrix(rnorm(n * p), n, p)
  y <- X[, 1] * 3 + X[, 5] * -2 + rnorm(n)
  run_gvs <- function(gc) {
    s <- TRexGVSSelector$new(X, y, seed = 1, verbose = FALSE, gvs_control = gc, control = .gvs_base(K = 3))
    s$select()
    list(s$selected_var, s$groups, s$hc_method_used)
  }
  by_hand <- trex_gvs_control(lambda_2 = 1)
  by_hand$hc_linkage <- "Complete"
  expect_identical(run_gvs(trex_gvs_control(hc_linkage = "complete", lambda_2 = 1)),
                   run_gvs(trex_gvs_control(hc_linkage = "Complete", lambda_2 = 1)))
  expect_identical(run_gvs(trex_gvs_control(hc_linkage = "complete", lambda_2 = 1)), run_gvs(by_hand))

  run_da <- function(dc) {
    s <- TRexDASelector$new(X, y, seed = 1, verbose = FALSE, da_control = dc, control = trex_control(K = 3))
    s$select()
    list(s$selected_var, s$rho_grid)
  }
  expect_identical(run_da(trex_da_control(hc_linkage = "average")), run_da(trex_da_control(hc_linkage = "Average")))

  tik <- function(linkage) {
    s <- TRexTikhonovSelector$new(X, y, seed = 1, verbose = FALSE,
                                  tik_control = trex_tikhonov_control(tikhonov_K = diag(p), lambda_2 = 1,
                                                                      hc_linkage = linkage),
                                  control = trex_control(solver = "TIKNET", K = 3))
    s$select()
    s$selected_var
  }
  expect_identical(tik("complete"), tik("Complete"))
})


test_that("TRexGVSSelector refuses the permutation strategies and reads SEEDED as STANDARD", {
  set.seed(42)
  n <- 60
  p <- 12
  X <- matrix(rnorm(n * p), n, p)
  y <- X[, 1] * 3 + X[, 5] * -2 + rnorm(n)
  run <- function(strategy) {
    s <- TRexGVSSelector$new(X, y, seed = 1, verbose = FALSE,
                             gvs_control = trex_gvs_control(lambda_2 = 1),
                             control = .gvs_base(K = 3, lloop_strategy = strategy))
    s$select()
    s$selected_var
  }
  for (strategy in c("PERMUTATION", "PERMUTATION_SEEDED")) {
    expect_error(run(strategy), "PERMUTATION and PERMUTATION_SEEDED", fixed = TRUE)
  }
  expect_identical(run("SEEDED"), run("STANDARD"))
})


test_that("trex_gvs_control carries the names of the groups (group_labels)", {
  set.seed(42)
  n <- 60
  p <- 12
  X <- matrix(rnorm(n * p), n, p)
  y <- as.numeric(X[, 1] * 3 + X[, 2] * -2 + X[, 5] * 2 + rnorm(n))
  prior <- rep(1:4, each = 3)
  labels <- c("north", "east", "south", "west")

  expect_null(trex_gvs_control()$group_labels)

  s <- TRexGVSSelector$new(X, y, tFDR = 0.2, seed = 1, verbose = FALSE,
                           gvs_control = trex_gvs_control(gvs_type = "EN", groups = prior,
                                                          group_labels = labels))
  s$select()
  expect_identical(s$group_labels, labels)

  # One name per group
  expect_error(
    TRexGVSSelector$new(X, y, verbose = FALSE,
                        gvs_control = trex_gvs_control(gvs_type = "EN", groups = prior,
                                                       group_labels = labels[1:3])),
    "group_labels"
  )
})



test_that("TRexGVSSelector groups reflects HAC assignment for Route 2", {
  set.seed(7)
  n <- 60; p <- 10
  X <- matrix(rnorm(n * p), n, p)
  y <- as.numeric(X[, 1] * 3 + X[, 2] * -2 + rnorm(n))

  # Route 2 (auto-cluster): no prior groups supplied, labels come from HAC.
  s <- TRexGVSSelector$new(X, y, tFDR = 0.2, seed = 1, verbose = FALSE,
                           gvs_control = trex_gvs_control(gvs_type = "EN"))
  s$select()
  g <- s$groups
  expect_length(g, p)
  expect_identical(length(unique(g)), s$max_clusters)
})


test_that("lambda2_method resolves by track and gates the IEN-geometry tuners", {

  # NULL default resolves by track (1SE; MIN pins to the grid floor).
  expect_identical(trex_gvs_control(gvs_type = "EN")$lambda2_method,
                   "CV_1SE_CCD")
  expect_identical(trex_gvs_control(gvs_type = "IEN")$lambda2_method,
                   "CV_1SE_IEN_CCD")

  # Explicit IEN-geometry choices parse for the IEN track.
  for (m in c("CV_1SE_IEN_CCD", "CV_MIN_IEN_CCD",
              "CV_1SE_TIK_SVD", "CV_MIN_TIK_SVD")) {
    expect_identical(
      trex_gvs_control(gvs_type = "IEN", lambda2_method = m)$lambda2_method, m)
  }

  # EN-shaped methods stay allowed on both tracks (legacy behaviour is an
  # explicit opt-in for IEN).
  expect_identical(
    trex_gvs_control(gvs_type = "IEN",
                     lambda2_method = "CV_1SE_CCD")$lambda2_method,
    "CV_1SE_CCD")

  # IEN-geometry tuners consume the group structure: EN track rejects them.
  expect_error(
    trex_gvs_control(gvs_type = "EN", lambda2_method = "CV_1SE_IEN_CCD"),
    "requires\\s+gvs_type = \"IEN\""
  )
})


test_that("GVS-IEN auto-calibrates lambda_2 with the IEN-geometry default", {
  set.seed(42)
  n <- 80
  p <- 20
  z <- matrix(rnorm(n * 4), n, 4)
  X <- matrix(0, n, p)
  for (g in 1:4) {
    for (j in 1:5) {
      X[, (g - 1) * 5 + j] <- 0.85 * z[, g] + sqrt(1 - 0.85^2) * rnorm(n)
    }
  }
  y <- as.vector(rowSums(X[, 1:3]) * 3 + rnorm(n))

  # lambda_2 < 0 triggers the auto path; the IEN default is now the
  # IEN-geometry tuner (CV_1SE_IEN_CCD).
  sel <- TRexGVSSelector$new(
    X, y, tFDR = 0.2, seed = 42, verbose = FALSE,
    gvs_control = trex_gvs_control(gvs_type = "IEN", lambda_2 = -1),
    control = .gvs_base("IEN", K = 5)
  )
  sel$select()
  expect_length(sel$selected_var, p)
  expect_gt(sel$lambda2_used, 0)
})


test_that("the IEN tuner grids pass through and the tuner diagnostics are exposed", {
  set.seed(42)
  n <- 80
  p <- 20
  z <- matrix(rnorm(n * 4), n, 4)
  X <- matrix(0, n, p)
  for (g in 1:4) {
    for (j in 1:5) {
      X[, (g - 1) * 5 + j] <- 0.85 * z[, g] + sqrt(1 - 0.85^2) * rnorm(n)
    }
  }
  y <- as.vector(rowSums(X[, 1:3]) * 3 + rnorm(n))
  groups <- rep(1:4, each = 5)

  # Fixed lambda_2: no tuner ran.
  sel_fixed <- TRexGVSSelector$new(
    X + 0, y, tFDR = 0.2, seed = 42, verbose = FALSE,
    gvs_control = trex_gvs_control(gvs_type = "IEN", lambda_2 = 1.0,
                                   groups = groups),
    control = .gvs_base("IEN", K = 5))
  sel_fixed$select()
  expect_false(sel_fixed$lambda2_cv_diagnostics$ran)

  # Support cap of the IEN tuner: default 0.8, a double, finite only.
  expect_identical(trex_gvs_control()$cv_dfmax_ratio, 0.8)
  expect_error(trex_gvs_control(cv_dfmax_ratio = NA), "cv_dfmax_ratio")
  expect_error(trex_gvs_control(cv_dfmax_ratio = Inf), "cv_dfmax_ratio")

  # IEN-geometry CV with reduced grids: the tuner ran and is reported.
  ctrl <- trex_gvs_control(gvs_type = "IEN", lambda_2 = -1, groups = groups,
                           cv_n_lambda1 = 20, cv_n_lambda2 = 10,
                           cv_dfmax_ratio = 0.9)
  expect_identical(ctrl$cv_n_lambda1, 20L)
  expect_identical(ctrl$cv_n_lambda2, 10L)
  expect_identical(ctrl$cv_dfmax_ratio, 0.9)
  sel_cv <- TRexGVSSelector$new(
    X + 0, y, tFDR = 0.2, seed = 42, verbose = FALSE,
    gvs_control = ctrl, control = .gvs_base("IEN", K = 5))
  sel_cv$select()
  diag <- sel_cv$lambda2_cv_diagnostics
  expect_true(diag$ran)
  expect_gte(diag$seconds, 0)
  expect_true(is.numeric(diag$n_profile_at_edge))
  expect_gt(sel_cv$lambda2_used, 0)
  # The ratio reached the tuner and is recorded as passed.
  expect_identical(diag$dfmax_ratio, 0.9)
  expect_type(diag$profile_at_support_cap, "logical")
  expect_true(diag$profile_at_edge || !diag$profile_at_support_cap)

  # Boundary-pick guard fields: the chosen pick on its grid.
  expect_identical(diag$grid_size, 10L)
  expect_true(diag$grid_index >= 0L && diag$grid_index < diag$grid_size)
  expect_type(diag$at_grid_edge, "logical")
  expect_type(diag$profile_at_edge, "logical")
  expect_identical(diag$boundary_pick, diag$at_grid_edge || diag$profile_at_edge)
  expect_identical(diag$at_grid_edge,
                   diag$grid_index == 0L || diag$grid_index == diag$grid_size - 1L)
  # No tuner: identity defaults.
  d0 <- sel_fixed$lambda2_cv_diagnostics
  expect_identical(d0$grid_index, -1L)
  expect_identical(d0$grid_size, 0L)
  expect_false(d0$boundary_pick)
  expect_identical(d0$dfmax_ratio, 0)
})


test_that("an unconverged coordinate descent is an error and the design comes back", {
  # TCDIENET at a lambda_2 beyond its sweep budget, one group per variable: select() ends with an
  # error instead of a selection from an unconverged path, the design is given back at once and
  # the selector is retired
  set.seed(2718)
  n <- 120
  p <- 60
  X <- matrix(rnorm(n * p), n, p)
  y <- as.numeric(rowSums(X[, 21:30]) + rnorm(n))
  X0 <- X + 0

  sel <- quiet_cd(TRexGVSSelector$new(X, y, tFDR = 0.1, seed = 4, verbose = FALSE,
                                      gvs_control = trex_gvs_control(gvs_type = "IEN", lambda_2 = 3000,
                                                                     groups = seq_len(p)),
                                      control = trex_control(solver = "TCDIENET", K = 10)))
  expect_false(isTRUE(all.equal(X, X0)))          # standardized in place
  expect_error(sel$select(), "sweep budget.*before it converged.*cd_max_sweeps")
  expect_equal(X, X0, tolerance = 1e-12)          # given back
  expect_error(sel$select(), "can no longer run") # retired
})


# =============================================================================
# The lambda_2 power rule on the GVS selector
# =============================================================================

test_that("the GVS power rule runs the grid and keeps the contract", {
  set.seed(77)
  n <- 120
  p <- 30
  z <- matrix(rnorm(n * 6), n, 6)
  X <- z[, rep(1:6, each = 5)] * 0.75 + matrix(rnorm(n * p), n, p) * sqrt(1 - 0.75^2)
  y <- as.numeric(rowSums(X[, 1:3]) * 3 + rnorm(n))
  X0 <- X + 0
  gvs <- trex_gvs_control(groups = rep(1:6, each = 5))
  base <- .gvs_base(K = 5, max_dummy_multiplier = 2)
  grid <- c(10, 0, 1, 10)
  rule <- function(seed = 3, ...) {
    trex_gvs_lambda2_power_rule(X, y, tFDR = 0.2, gvs_control = gvs, control = base,
                                seed = seed, grid = grid, ...)
  }

  a <- rule()
  expect_identical(a$grid, c(0, 1, 10))                 # sorted, de-duplicated
  expect_identical(a$grid_scale, 1)
  expect_length(a$probes, 3)
  expect_identical(a$counts, vapply(a$probes, function(pr) length(pr$selected), 1))
  expect_identical(a$max_selected, max(a$counts))
  expect_identical(a$lambda2, a$grid[a$index])
  expect_identical(a$selected, a$probes[[a$index]]$selected)
  expect_identical(a$index, which(a$counts >= max(a$counts) - 1)[1])    # the knee
  expect_equal(X, X0, tolerance = 1e-12)                # every probe hands X back
  expect_identical(gvs$lambda_2, -1)                    # the control of the caller is not changed

  # The same seed reproduces the profile
  b <- rule()
  expect_identical(lapply(b$probes, `[[`, "selected"), lapply(a$probes, `[[`, "selected"))

  # The contract: a selector at the pick with the same seed selects the same variables
  fixed <- gvs
  fixed$lambda_2 <- a$lambda2
  sel <- suppressWarnings(TRexGVSSelector$new(X, y, tFDR = 0.2, seed = 3, verbose = FALSE,
                                              gvs_control = fixed, control = base))
  sel$select()
  expect_identical(sort(sel$selected_indices), a$selected)

  # Under ZSCORE the probes run at the grid times n - 1 (the equal selections are pinned in C++)
  z_rule <- trex_gvs_lambda2_power_rule(X, y, tFDR = 0.2, gvs_control = gvs, seed = 3, grid = grid,
                                        control = .gvs_base(K = 5, max_dummy_multiplier = 2,
                                                            scaling_mode = "ZSCORE"))
  expect_identical(z_rule$grid_scale, n - 1)
  expect_equal(z_rule$grid, c(0, 1, 10) * (n - 1))
  expect_identical(z_rule$lambda2, z_rule$grid[z_rule$index])

  # The gates of the Tikhonov rule
  expect_error(rule(seed = -1), "seed")
  expect_error(rule(knee_tolerance = -1), "knee_tolerance")
  expect_error(trex_gvs_lambda2_power_rule(X, y, grid = c(-1, 1)), "grid")
  expect_error(trex_gvs_lambda2_power_rule(X, y, gvs_control = trex_gvs_control(groups = rep(1, p - 1))),
               "gvs_control\\$groups must have one entry per variable")

  # A memory-mapped design gives the run in memory
  f <- tempfile(fileext = ".bin")
  on.exit(unlink(f), add = TRUE)
  mem_matrix_from(X, f)
  on_file <- trex_gvs_lambda2_power_rule(mem_matrix(f, rows = n, cols = p, mode = "readwrite"), y,
                                         tFDR = 0.2, gvs_control = gvs, control = base, seed = 3,
                                         grid = grid)
  expect_identical(on_file$counts, a$counts)
  expect_identical(on_file$selected, a$selected)
  expect_equal(as.matrix(mem_matrix(f, rows = n, cols = p, mode = "readonly")), X0, tolerance = 1e-12)
})

Try the TRexSelector package in your browser

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

TRexSelector documentation built on Nov. 20, 2026, 5:09 p.m.