tests/testthat/test-make_euclidean.R

test_that("make_euclidean corrects non-Euclidean matrix with Data_MC_contamination", {

  # --- Load and prepare data ---
  data("Data_MC_contamination", package = "dbrobust")
  Data_small <- Data_MC_contamination[1:50, ]
  cont_vars <- names(Data_small)[1:4]
  Data_cont <- Data_small[, cont_vars]

  # --- Squared distance matrix ---
  dist_mat <- as.matrix(dist(Data_cont))^2

  # Introduce a small non-Euclidean distortion
  dist_mat[1, 2] <- dist_mat[1, 2] * 0.5
  dist_mat[2, 1] <- dist_mat[1, 2]

  # Uniform weights
  weights <- rep(1, nrow(Data_cont))

  # --- Apply Euclidean correction ---
  res <- make_euclidean(dist_mat, weights)

  # --- Tests ---
  # 1) Corrected matrix is still square
  expect_equal(dim(res$D_euc), c(50, 50))

  # 2) Eigenvalues of Gw_after are >= -tol
  n <- nrow(dist_mat)
  w <- weights / sum(weights)
  Jw <- diag(n) - rep(1, n) %*% t(w)
  Gw_after <- -0.5 * Jw %*% res$D_euc %*% t(Jw)
  expect_true(all(eigen(Gw_after, symmetric = TRUE)$values >= -1e-10))

  # 3) 'transformed' flag is logical
  expect_true(is.logical(res$transformed))

  # 4) Minimum eigenvalue before correction < 0 (because we distorted)
  expect_true(min(res$eigvals_before) < 0)

  # 5) Minimum eigenvalue after correction >= 0
  expect_true(min(res$eigvals_after) >= -1e-10)

})

Try the dbrobust package in your browser

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

dbrobust documentation built on Nov. 5, 2025, 6:24 p.m.