@@ -755,19 +755,34 @@ test_that("ppg_esim stops when v_norm is numerically zero (lines 728-729)", {
755755# Use G = c(1,-1)c(1,1)': G * c(1,-1) = c(1-1, -1+1) = 0 after normalization.
756756# This is very hard to guarantee analytically, so use the mock-based approach.
757757test_that(" ppg_esim handles sign_corr = 0 by defaulting to 1 (line 749)" , {
758- # Construct G with null space containing likely b_P for d=c(1,-1)
759- # G = c(1,1) * c(1,-1)' — symmetric approx via averaging
760- v1 <- c(1 , - 1 ) / sqrt(2 ) # b_P will be ∝ this
761- G_sing <- outer(v1 , v1 ) # rank-1 G with null space ⊥ to v1
762- # Make it symmetric PSD
763- G_sing <- (G_sing + t(G_sing )) / 2 + 0.001 * diag(2 )
764- P_test <- .P2
765-
766- # With d = c(1, -1), b_P ∝ K_P * P^{-1}G * d;
767- # if G * b_P ends up orthogonal to d, sign_corr = 0, triggering line 749.
768- # In practice the result should complete without error regardless.
769- expect_no_error(
770- suppressWarnings(ppg_esim(P_test , G_sing , d = c(1 , - 1 )))
758+ # It is mathematically impossible for G*b_P = 0 AND v_norm > 0 in exact arithmetic.
759+ # We mock the internal solver to decouple the two checks.
760+ P_test <- diag(2 )
761+ G_test <- matrix (c(0 , 0 , 0 , 1 ), 2 , 2 )
762+ d_test <- c(1 , 0 )
763+
764+ mock_solve <- function (pmat , mat ) {
765+ if (ncol(mat ) == nrow(pmat )) {
766+ # For P_inv_G calculation, return Identity so v_raw = K_P * I * d = c(1,0) -> v_norm = 1
767+ return (diag(2 ))
768+ } else {
769+ # For P_inv_PsiDM calculation, return normal matrix multiplication
770+ return (mat )
771+ }
772+ }
773+
774+ testthat :: with_mocked_bindings(
775+ .esim_solve_sym_multi = mock_solve ,
776+ .package = " selection.index" ,
777+ code = {
778+ # This forces b_P = c(1, 0).
779+ # Then tentative_gain = G_test %*% c(1, 0) = c(0, 0).
780+ # sum(c(0,0) * d_test) == 0, triggering the fallback.
781+ expect_no_error(
782+ res <- ppg_esim(P_test , G_test , d = d_test )
783+ )
784+ expect_equal(as.numeric(res $ b ), c(1 , 0 ), tolerance = 1e-5 )
785+ }
771786 )
772787})
773788
0 commit comments