From 166602f7c682d02dbd512d5294f3df04fc7d3c3c Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Tue, 24 Nov 2026 10:12:46 +0200 Subject: [PATCH 1/8] fix: validate pred_measure inputs: psis_object class and match, dims, posthoc, custom names --- R/diagnostics.R | 3 +- R/pred_measure-compute.R | 132 +++++++++++--------- R/pred_measure-helpers.R | 85 ++++++++++++- R/pred_measure.R | 4 +- R/print.R | 7 +- tests/testthat/test_compare.R | 17 +++ tests/testthat/test_pred_measure.R | 135 +++++++++++++++++++++ tests/testthat/test_pred_measure_helpers.R | 15 ++- tests/testthat/test_print_plot.R | 4 + 9 files changed, 330 insertions(+), 72 deletions(-) diff --git a/R/diagnostics.R b/R/diagnostics.R index f9f27d045..8a97344e9 100644 --- a/R/diagnostics.R +++ b/R/diagnostics.R @@ -430,10 +430,11 @@ min_n_eff_by_k <- function(n_eff, kcut) { #' probability of large error, it is difficult to get accurate MCSE #' estimates as the bias starts to dominate when k > 0.7 (see Section 3.2.3). #' Thus the sample size dependent k-hat threshold is capped at 0.7. +#' An unknown sample size (`NA`) gives the cap. #' @param S sample size #' @param ... unused #' @return threshold #' @noRd ps_khat_threshold <- function(S, ...) { - min(1 - 1 / log10(S), 0.7) + min(1 - 1 / log10(S), 0.7, na.rm = TRUE) } diff --git a/R/pred_measure-compute.R b/R/pred_measure-compute.R index 7479533e0..44314354f 100644 --- a/R/pred_measure-compute.R +++ b/R/pred_measure-compute.R @@ -111,6 +111,11 @@ do_pred_measure <- function( if (length(dim(ylp_test)) == 3) { ylp_test <- llarray_to_matrix(ylp_test) } + dims <- .pred_measure_dims( + source = source, y = y, ypred = ypred, mupred = mupred, ylp = ylp, + ylp_test = ylp_test, psis_object = psis_object, loo = loo, + kfold = kfold, predperf = predperf + ) measures <- .prepare_measures( measures, predperf, supported_measures_list, source @@ -119,13 +124,12 @@ do_pred_measure <- function( needs_elpd <- .any_needs_elpd(measures) if (source == "loo") { if (is.null(predperf)) { - if (!is.null(loo) && is.null(loo$psis_object)) { + if (!is.null(loo) && is.null(loo$psis_object) && is.null(psis_object)) { cli::cli_abort(c( "No {.field psis_object} found in {.arg loo}.", "i" = "Did you run {.code loo(..., save_psis = TRUE)}?" )) } - .warn_posthoc(loo, measures) } else { if (is.null(psis_object) && !is.null(predperf$psis_object)) { cli::cli_inform("Using psis_object for LOO CV from `predperf`") @@ -157,6 +161,12 @@ do_pred_measure <- function( ylp = ylp, r_eff = 1 ) + posthoc <- if (is.null(predperf)) { + .detect_posthoc(loo, psis_object) + } else { + attr(predperf, "posthoc") + } + .warn_posthoc(posthoc, measures) } log_weights <- if (!is.null(psis_object)) psis_object$log_weights else NULL @@ -249,19 +259,19 @@ do_pred_measure <- function( save_psis = save_psis ) - .add_attributes( + predperf_res <- .add_attributes( save_psis, predperf_res, - y, - ypred, - mupred, - ylp, - ylp_test, + dims, kfold, loo, predperf, source ) + if (source == "loo") { + attr(predperf_res, "posthoc") <- posthoc + } + predperf_res } # internal helper functions --------------------------------------------------- @@ -272,14 +282,15 @@ do_pred_measure <- function( #' `diagnostics$pareto_k` to 0 for the refitted observations but does not #' change `psis_object`, so the two sets of Pareto k values differ. #' -#' @param loo A [loo::loo()] result with a `psis_object`. +#' @param loo A [loo::loo()] result, or `NULL`. +#' @param psis_object The `psis` object used for the measures. #' #' @return A character vector of method names, or `NULL`. #' @noRd -.detect_posthoc <- function(loo) { +.detect_posthoc <- function(loo, psis_object) { method <- attr(loo, "posthoc") k_loo <- loo$diagnostics$pareto_k - k_psis <- loo$psis_object$diagnostics$pareto_k + k_psis <- psis_object$diagnostics$pareto_k if (!is.null(k_loo) && !is.null(k_psis) && !isTRUE(all.equal(k_loo, k_psis))) { method <- union(method, "reloo") } @@ -292,13 +303,12 @@ do_pred_measure <- function( #' measures use `psis_object$log_weights` with the original draws in `ypred` #' and `mupred`, so their values are not corrected. #' -#' @param loo A [loo::loo()] result with a `psis_object`. +#' @param method Method names from `.detect_posthoc()`, or `NULL`. #' @param measures Measure entries from `.prepare_measures()`. #' #' @return `NULL`, invisibly. Called for the warning. #' @noRd -.warn_posthoc <- function(loo, measures) { - method <- .detect_posthoc(loo) +.warn_posthoc <- function(method, measures) { if (is.null(method)) { return(invisible(NULL)) } @@ -325,9 +335,11 @@ do_pred_measure <- function( #' Resolution order: #' \enumerate{ #' \item If both `psis_object` and `loo` are provided, return `psis_object` -#' after verifying it matches `loo$psis_object`. +#' after verifying it matches `loo$psis_object`, or the Pareto k values +#' of `loo` when `loo` has no `psis_object`. #' \item Extract from `loo$psis_object` when `loo` is provided. -#' \item Use the supplied `psis_object`. +#' \item Use the supplied `psis_object` after verifying it matches the +#' weights stored in `predperf`. #' \item Reuse `predperf$psis_object` when accumulating measures. #' \item Reuse `predperf$log_weights` when only the weights were stored #' (`save_psis = FALSE`); the result carries no `diagnostics`. @@ -354,21 +366,21 @@ do_pred_measure <- function( ) { # psis_object + loo are both provided -> return psis_object if (!is.null(psis_object) && !is.null(loo)) { - psis_equal_loo <- isTRUE(all.equal( - psis_object$log_weights, - loo$psis_object$log_weights - )) - if (!psis_equal_loo) { - cli::cli_abort( - "Provided `psis_object` and `loo$psis_object` are not identical." - ) - } + pareto_k <- if (is.null(attr(loo, "posthoc"))) loo$diagnostics$pareto_k + .check_psis_match( + psis_object, loo$psis_object$log_weights, pareto_k, "loo" + ) return(psis_object) # loo is provided } else if (!is.null(loo)) { return(loo$psis_object) # psis_object is provided } else if (!is.null(psis_object)) { + log_weights <- predperf$log_weights + if (is.null(log_weights)) { + log_weights <- predperf$psis_object$log_weights + } + .check_psis_match(psis_object, log_weights, NULL, "predperf") return(psis_object) # predperf with psis_object is provided } else if (!is.null(predperf$psis_object)) { @@ -391,6 +403,38 @@ do_pred_measure <- function( )) }} +#' Check that a `psis_object` matches the stored PSIS results +#' +#' Compares the log weights when they are stored. Otherwise compares the +#' Pareto k values. `brms::reloo()` sets k to 0 for the refitted +#' observations, so those observations are not compared. +#' +#' @param psis_object The supplied `psis` object. +#' @param log_weights Stored log weights, or `NULL`. +#' @param pareto_k Stored Pareto k values, or `NULL`. +#' @param arg Name of the argument that holds the stored results. +#' +#' @return `NULL`, invisibly. Called for the error. +#' @noRd +.check_psis_match <- function(psis_object, log_weights, pareto_k, arg) { + if (!is.null(log_weights)) { + same <- isTRUE(all.equal(psis_object$log_weights, log_weights)) + } else if (!is.null(pareto_k)) { + keep <- pareto_k != 0 + same <- isTRUE(all.equal( + psis_object$diagnostics$pareto_k[keep], pareto_k[keep] + )) + } else { + return(invisible(NULL)) + } + if (!same) { + cli::cli_abort( + "{.arg psis_object} does not match the PSIS results in {.arg {arg}}." + ) + } + invisible(NULL) +} + #' Extract estimate and SE from a measure result #' #' `.create_measure_structure()` gives every builtin measure an `estimates` @@ -756,7 +800,7 @@ do_pred_measure <- function( #' measure object. #' #' When updating an existing result (`predperf` is not `NULL`), copies attributes -#' from `predperf` and refreshes `dims` from newly supplied input matrices. +#' from `predperf`. #' Merges `measure_info` from the prior result with any new entries supplied on #' `predperf_res` (from \code{.build_pred_measure()}). #' When `save_psis = FALSE`, clears any stored `psis_object` from the prior @@ -770,12 +814,7 @@ do_pred_measure <- function( #' @param save_psis Logical; when `FALSE` and accumulating, clears stored #' `psis_object` from the prior result. #' @param predperf_res List returned by \code{.build_pred_measure()}. -#' @param y Vector of observed values; used indirectly via matrix `dims`. -#' @param ypred Matrix of posterior predictive draws; used to set `dims`. -#' @param mupred Matrix of posterior expected values; used to set `dims`. -#' @param ylp Matrix of pointwise log predictive densities; used to set `dims`. -#' @param ylp_test Matrix of holdout log predictive densities; sets `dims` for -#' `source = "test"`. +#' @param dims Number of draws and observations from `.pred_measure_dims()`. #' @param kfold Optional `kfold` object whose attributes are inherited. #' @param loo Optional [loo::loo()] object whose attributes are inherited. #' @param predperf Existing object when accumulating measures, or `NULL`. @@ -788,11 +827,7 @@ do_pred_measure <- function( .add_attributes <- function( save_psis, predperf_res, - y, - ypred, - mupred, - ylp, - ylp_test, + dims, kfold, loo, predperf, @@ -809,16 +844,6 @@ do_pred_measure <- function( predperf, setdiff(names(attributes(predperf)), "names") ) - - dims <- if (!is.null(ypred)) { - dim(ypred) - } else if (!is.null(mupred)) { - dim(mupred) - } else if (!is.null(ylp)) { - dim(ylp) - } else { - attr(predperf, "dims") - } attr(predperf_res, "dims") <- dims measure_info <- attr(predperf, "measure_info") if (is.null(measure_info)) { @@ -850,17 +875,8 @@ do_pred_measure <- function( test = , # fall through (same as insample) insample = predperf_res ) - - if (source %in% c("insample", "test") || - (is.null(attr(predperf_res, "dims")) && !is.null(ylp))){ - # make attribute names consistent between pred_measure classes - if (source == "test") { - attr(predperf_res, "dims") <- attr(ylp_test, "dim") - } else { - attr(predperf_res, "dims") <- attr(ylp, "dim") - } - } - + attr(predperf_res, "dims") <- dims + classes <- c( switch( source, diff --git a/R/pred_measure-helpers.R b/R/pred_measure-helpers.R index 25778fa8d..2d973ca46 100644 --- a/R/pred_measure-helpers.R +++ b/R/pred_measure-helpers.R @@ -76,12 +76,11 @@ .measure_entry_custom <- function(fun, name = NULL) { if (is.null(name)) { name <- attr(fun, "measure_name", exact = TRUE) - if (is.null(name) || length(name) != 1L || !nzchar(name)) { - stop( - "A custom measure needs a name. Create it with ", - "custom_measure(fun, name = \"my_metric\").", - call. = FALSE - ) + if (!checkmate::test_string(name, min.chars = 1L)) { + cli::cli_abort(c( + "A custom measure needs a name: a single non-empty string.", + "i" = "Create it with {.code custom_measure(fun, name = \"my_metric\")}." + )) } } else { attr_name <- attr(fun, "measure_name", exact = TRUE) @@ -94,6 +93,12 @@ )) } } + if (name %in% c(supported_measures_list, "p")) { + cli::cli_abort(c( + "Custom measure name {.val {name}} is reserved.", + "i" = "Built-in measure names and {.val p} cannot name a custom measure." + )) + } loss <- attr(fun, "measure_loss", exact = TRUE) if (is.null(loss)) { @@ -309,6 +314,74 @@ invisible(res) } +#' Validate the `psis_object` argument +#' +#' @param psis_object Object to validate, or `NULL`. +#' +#' @return `NULL`, invisibly, on success. +#' @noRd +.validate_psis_object <- function(psis_object) { + if (is.null(psis_object) || is.psis(psis_object)) { + return(invisible(NULL)) + } + cli::cli_abort(c( + "{.arg psis_object} must be a {.cls psis} object, not {.obj_type_friendly {psis_object}}.", + "i" = if (is.loo(psis_object)) { + "Pass a {.cls loo} object to {.arg loo} in {.fn loo_pred_measure}." + } + )) +} + +#' Number of draws and observations of the inputs +#' +#' Reads `S` and `N` from every input and from the stored `dims` of +#' `predperf`. For `source = "test"`, the training `ylp` has another `N` and +#' is not read. +#' +#' @inheritParams pred_measure_params +#' +#' @return Integer vector `c(S, N)`. `S` is `NA` when no input has draws. +#' @noRd +.pred_measure_dims <- function( + source, y, ypred, mupred, ylp, ylp_test, psis_object, loo, kfold, predperf +) { + draws <- list( + ypred = ypred, + mupred = mupred, + ylp = if (source != "test") ylp, + ylp_test = ylp_test, + psis_object = psis_object$log_weights + ) + draws <- draws[!vapply(draws, is.null, logical(1L))] + stored <- attr(predperf, "dims") + sizes <- list( + draws = c( + predperf = stored[1], + loo = dim(loo)[1], + vapply(draws, nrow, integer(1L)) + ), + observations = c( + predperf = stored[2], + loo = dim(loo)[2], + kfold = nrow(kfold$pointwise), + y = if (!is.null(y)) length(y), + vapply(draws, ncol, integer(1L)) + ) + ) + sizes <- lapply(sizes, function(n) n[!is.na(n)]) + for (what in names(sizes)) { + n <- sizes[[what]] + if (length(unique(n)) > 1L) { + inputs <- paste0("{.arg ", names(n), "}: ", n) + cli::cli_abort(c( + "The inputs do not agree on the number of {what}.", + stats::setNames(inputs, rep("x", length(n))) + )) + } + } + unname(c(sizes$draws[1], sizes$observations[1])) +} + #' Validate a numeric matrix argument #' #' @description diff --git a/R/pred_measure.R b/R/pred_measure.R index f4cfeaa89..dfb83f1c6 100644 --- a/R/pred_measure.R +++ b/R/pred_measure.R @@ -226,6 +226,7 @@ loo_pred_measure <- function( save_psis = FALSE, control = list() ) { + .validate_psis_object(psis_object) do_pred_measure( y = y, ypred = ypred, @@ -494,6 +495,7 @@ pred_measure <- function( "i" = "Got an object of class {.cls {class(predperf)[1]}}." )) } + .validate_psis_object(psis_object) do_pred_measure( y = y, @@ -553,7 +555,7 @@ custom_measure <- function( fun, name, se_diff_fun = NULL, loss = FALSE ) { if (!is.function(fun)) { - stop("'fun' must be a function.", call. = FALSE) + cli::cli_abort("{.arg fun} must be a function.") } attr(fun, "measure_name") <- name attr(fun, "measure_loss") <- loss diff --git a/R/print.R b/R/print.R index f8089a3a2..c69656a91 100644 --- a/R/print.R +++ b/R/print.R @@ -336,13 +336,12 @@ convert_old_object <- function(x, digits = 1, ...) { #' @export print.pred_measure <- function(x, digits = NULL, ...) { dims <- attr(x, "dims") - if (is.null(dims) && !is.null(x$log_weights)) { - dims <- dim(x$log_weights) - } source <- .pred_measure_source_label(x) cat("\n") - if (!is.null(dims) && length(dims) == 2) { + if (length(dims) == 2 && is.na(dims[1])) { + cat(sprintf("Computed from %s observations.\n", dims[2])) + } else if (length(dims) == 2) { cat( sprintf( "Computed from %s posterior draws and %s observations.\n", diff --git a/tests/testthat/test_compare.R b/tests/testthat/test_compare.R index 266a436c3..a7facba27 100644 --- a/tests/testthat/test_compare.R +++ b/tests/testthat/test_compare.R @@ -1565,6 +1565,23 @@ test_that("model_compare compares kfold_pred_measure objects", { colnames(comp))) }) +test_that("model_compare compares loo_pred_measure objects made from a psis_object", { + res <- .compare_src_res() + set.seed(4321) + p1 <- loo_pred_measure( + psis_object = res$loo$psis_object, y = res$y, mupred = res$mupred, + measures = "rmse" + ) + p2 <- loo_pred_measure( + psis_object = res$loo$psis_object, y = res$y, + mupred = .jitter_mupred(res$mupred, 3), measures = "rmse" + ) + expect_no_error( + comp <- suppressMessages(model_compare(list(m1 = p1, m2 = p2))) + ) + expect_s3_class(comp, "compare.loo") +}) + test_that("model_compare compares test_pred_measure objects", { res_cv <- readRDS("data-for-tests/test_data_sleep_cv.Rds") set.seed(4321) diff --git a/tests/testthat/test_pred_measure.R b/tests/testthat/test_pred_measure.R index 218424dcf..471435c1b 100644 --- a/tests/testthat/test_pred_measure.R +++ b/tests/testthat/test_pred_measure.R @@ -121,6 +121,28 @@ test_that(".get_psis_object() accepts loo and psis_object together", { ) }) +test_that(".get_psis_object() errors if psis_object does not match loo", { + other <- res$loo$psis_object + other$log_weights <- other$log_weights[rev(seq_len(nrow(other$log_weights))), ] + expect_error( + .get_psis_object( + ylp = NULL, loo = res$loo, predperf = NULL, psis_object = other + ), + regexp = "does not match" + ) + + loo_nosave <- res$loo + loo_nosave$psis_object <- NULL + other <- res$loo$psis_object + other$diagnostics$pareto_k <- other$diagnostics$pareto_k + 0.1 + expect_error( + .get_psis_object( + ylp = NULL, loo = loo_nosave, predperf = NULL, psis_object = other + ), + regexp = "does not match" + ) +}) + ## .merge_matrix() --------------------------- test_that(".merge_matrix() works as expected", { @@ -303,6 +325,119 @@ test_that("pred_measure() keeps dims when the update has no matrix input", { expect_equal(attr(updated, "dims"), attr(predperf_loo, "dims")) }) +test_that("dims is c(S, N) for every source", { + S <- nrow(res$ylp) + N <- length(res$y) + insample <- insample_pred_measure( + y = res$y, mupred = res$mupred, measures = "rmse" + ) + expect_equal(attr(insample, "dims"), c(S, N)) + from_psis <- loo_pred_measure( + psis_object = res$loo$psis_object, y = res$y, mupred = res$mupred, + measures = "rmse" + ) + expect_equal(attr(from_psis, "dims"), c(S, N)) + + kfold_only <- kfold_pred_measure(kfold = res$kfold) + expect_equal(attr(kfold_only, "dims"), c(NA, N)) + expect_output(print(kfold_only), "Computed from 53 observations") + updated <- pred_measure( + y = res$y, mupred = res$mupred, predperf = kfold_only, measures = "rmse" + ) + expect_equal(attr(updated, "dims"), c(S, N)) +}) + +test_that("pred_measure inputs must agree on the number of draws and observations", { + expect_error( + insample_pred_measure(y = res$y, ylp = t(res$ylp)), + regexp = "number of observations" + ) + expect_error( + insample_pred_measure( + y = res$y, ypred = res$ypred[1:100, ], mupred = res$mupred, + measures = c("rmse", "rps") + ), + regexp = "number of draws" + ) + predperf_loo <- loo_pred_measure( + loo = res$loo, y = res$y, mupred = res$mupred, measures = "r2" + ) + expect_error( + pred_measure( + y = res$y, ypred = res$ypred[1:100, ], predperf = predperf_loo, + measures = "rps" + ), + regexp = "number of draws" + ) +}) + +test_that("loo_pred_measure() and pred_measure() error if psis_object is not a psis object", { + expect_error( + loo_pred_measure(ylp = res$ylp, psis_object = res$loo), + regexp = "must be a object.*loo_pred_measure" + ) + predperf_loo <- loo_pred_measure(loo = res$loo) + expect_error( + pred_measure(predperf = predperf_loo, psis_object = list()), + regexp = "must be a object" + ) +}) + +test_that("pred_measure() errors if psis_object does not match the stored weights", { + predperf_loo <- loo_pred_measure( + loo = res$loo, y = res$y, mupred = res$mupred, measures = "r2" + ) + other <- res$loo$psis_object + other$log_weights <- other$log_weights[rev(seq_len(nrow(other$log_weights))), ] + expect_error( + pred_measure( + y = res$y, mupred = res$mupred, predperf = predperf_loo, + psis_object = other, measures = "mae" + ), + regexp = "does not match" + ) + updated <- pred_measure( + y = res$y, mupred = res$mupred, predperf = predperf_loo, + psis_object = res$loo$psis_object, measures = "mae" + ) + expect_true("mae_loo" %in% rownames(updated$estimates)) +}) + +test_that("loo_pred_measure() accepts a loo without psis_object and a psis_object", { + loo_nosave <- res$loo + loo_nosave$psis_object <- NULL + out <- loo_pred_measure( + loo = loo_nosave, psis_object = res$loo$psis_object, + y = res$y, mupred = res$mupred, measures = c("elpd", "r2") + ) + expect_true(all(c("elpd_loo", "r2_loo") %in% rownames(out$estimates))) + + # reloo sets k to 0; those observations are not compared + loo_nosave$diagnostics$pareto_k[which.max(loo_nosave$diagnostics$pareto_k)] <- 0 + expect_warning( + loo_pred_measure( + loo = loo_nosave, psis_object = res$loo$psis_object, + y = res$y, mupred = res$mupred, measures = "r2" + ), + regexp = "reloo" + ) +}) + +test_that("pred_measure() warns for non-elpd measures after moment matching", { + loo_mm <- res$loo + attr(loo_mm, "posthoc") <- "moment_match" + expect_no_warning( + predperf_mm <- loo_pred_measure(loo = loo_mm, measures = "elpd") + ) + expect_equal(attr(predperf_mm, "posthoc"), "moment_match") + expect_warning( + pred_measure( + y = res$y, mupred = res$mupred, predperf = predperf_mm, measures = "mae" + ), + regexp = "moment_match" + ) +}) + test_that("pred_measure() reuses stored log_weights when save_psis = FALSE", { predperf_loo <- loo_pred_measure( loo = res$loo, y = res$y, mupred = res$mupred, ylp = res$ylp, diff --git a/tests/testthat/test_pred_measure_helpers.R b/tests/testthat/test_pred_measure_helpers.R index 3b7f81d82..1f5e03e9a 100644 --- a/tests/testthat/test_pred_measure_helpers.R +++ b/tests/testthat/test_pred_measure_helpers.R @@ -84,14 +84,25 @@ test_that("custom_measure() sets the attributes", { }) test_that("custom_measure() errors on invalid input", { - expect_error(custom_measure("x", name = "m"), regexp = "'fun' must be a function") + expect_error(custom_measure("x", name = "m"), regexp = "must be a function") expect_error(custom_measure(function(y) NULL, name = "m", loss = NA), regexp = "declare loss") expect_error(custom_measure(function(y) NULL, name = "m", se_diff_fun = "median"), regexp = "Invalid") - for (bad in list("", NULL, c("a", "b"))) { + for (bad in list("", NULL, c("a", "b"), 1, NA_character_)) { expect_error(custom_measure(function(y) NULL, name = bad), regexp = "needs a name") } }) +test_that("custom_measure() errors on a reserved name", { + for (reserved in c("elpd", "rmse", "srps", "p")) { + expect_error( + custom_measure(function(y) NULL, name = reserved), + regexp = "is reserved" + ) + } + f <- function(y, mupred) list(estimate = 1, se = 0, pointwise = y) + expect_error(.normalize_measure(list(elpd = f)), regexp = "is reserved") +}) + # .prepare_measures() ----------------------------------------------- test_that(".prepare_measures() errors on invalid built-in names", { diff --git a/tests/testthat/test_print_plot.R b/tests/testthat/test_print_plot.R index 3e8b2dd8d..e8185cdac 100644 --- a/tests/testthat/test_print_plot.R +++ b/tests/testthat/test_print_plot.R @@ -136,6 +136,10 @@ test_that("pareto_k_table gives correct output", { ) }) +test_that("ps_khat_threshold gives the cap for an unknown sample size", { + expect_equal(ps_khat_threshold(NA), 0.7) +}) + # psis_neff and mcse_loo -------------------------------------------------- test_that("psis_n_eff_values extractor works", { From 7939ff765795bd6f6b15fe247a54be994adf0f2a Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Wed, 25 Nov 2026 18:36:27 +0200 Subject: [PATCH 2/8] fix: revert NA handling in ps_khat_threshold --- R/diagnostics.R | 3 +-- tests/testthat/test_print_plot.R | 4 ---- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/R/diagnostics.R b/R/diagnostics.R index 8a97344e9..f9f27d045 100644 --- a/R/diagnostics.R +++ b/R/diagnostics.R @@ -430,11 +430,10 @@ min_n_eff_by_k <- function(n_eff, kcut) { #' probability of large error, it is difficult to get accurate MCSE #' estimates as the bias starts to dominate when k > 0.7 (see Section 3.2.3). #' Thus the sample size dependent k-hat threshold is capped at 0.7. -#' An unknown sample size (`NA`) gives the cap. #' @param S sample size #' @param ... unused #' @return threshold #' @noRd ps_khat_threshold <- function(S, ...) { - min(1 - 1 / log10(S), 0.7, na.rm = TRUE) + min(1 - 1 / log10(S), 0.7) } diff --git a/tests/testthat/test_print_plot.R b/tests/testthat/test_print_plot.R index e8185cdac..3e8b2dd8d 100644 --- a/tests/testthat/test_print_plot.R +++ b/tests/testthat/test_print_plot.R @@ -136,10 +136,6 @@ test_that("pareto_k_table gives correct output", { ) }) -test_that("ps_khat_threshold gives the cap for an unknown sample size", { - expect_equal(ps_khat_threshold(NA), 0.7) -}) - # psis_neff and mcse_loo -------------------------------------------------- test_that("psis_n_eff_values extractor works", { From 74def54bd9c7d4ceca0a3e3c8ca023de30fe4c83 Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Wed, 25 Nov 2026 18:40:14 +0200 Subject: [PATCH 3/8] fix: skip vector mupred and ypred in the dims check --- R/pred_measure-helpers.R | 2 +- tests/testthat/test_pred_measure.R | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/R/pred_measure-helpers.R b/R/pred_measure-helpers.R index 2d973ca46..a918ccab5 100644 --- a/R/pred_measure-helpers.R +++ b/R/pred_measure-helpers.R @@ -352,7 +352,7 @@ ylp_test = ylp_test, psis_object = psis_object$log_weights ) - draws <- draws[!vapply(draws, is.null, logical(1L))] + draws <- Filter(function(x) length(dim(x)) >= 2L, draws) stored <- attr(predperf, "dims") sizes <- list( draws = c( diff --git a/tests/testthat/test_pred_measure.R b/tests/testthat/test_pred_measure.R index 471435c1b..f2d6fa9c4 100644 --- a/tests/testthat/test_pred_measure.R +++ b/tests/testthat/test_pred_measure.R @@ -347,6 +347,19 @@ test_that("dims is c(S, N) for every source", { expect_equal(attr(updated, "dims"), c(S, N)) }) +test_that("a vector mupred or ypred passes the dims check", { + expect_message( + insample_pred_measure( + y = res$y, mupred = colMeans(res$mupred), measures = "mae" + ), + "Coercing" + ) + expect_error( + insample_pred_measure(y = res$y, ypred = res$ypred[1, ], measures = "rps"), + "`ypred` must be a numeric matrix or array" + ) +}) + test_that("pred_measure inputs must agree on the number of draws and observations", { expect_error( insample_pred_measure(y = res$y, ylp = t(res$ylp)), From dc0daeb6250d44f01fbe306324150c146a33e994 Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Wed, 25 Nov 2026 18:46:22 +0200 Subject: [PATCH 4/8] fix: keep the error for a loo without psis_object --- R/pred_measure-compute.R | 36 +++++++++--------------------- tests/testthat/test_pred_measure.R | 27 ++++------------------ 2 files changed, 15 insertions(+), 48 deletions(-) diff --git a/R/pred_measure-compute.R b/R/pred_measure-compute.R index 44314354f..aa9d264f1 100644 --- a/R/pred_measure-compute.R +++ b/R/pred_measure-compute.R @@ -124,7 +124,7 @@ do_pred_measure <- function( needs_elpd <- .any_needs_elpd(measures) if (source == "loo") { if (is.null(predperf)) { - if (!is.null(loo) && is.null(loo$psis_object) && is.null(psis_object)) { + if (!is.null(loo) && is.null(loo$psis_object)) { cli::cli_abort(c( "No {.field psis_object} found in {.arg loo}.", "i" = "Did you run {.code loo(..., save_psis = TRUE)}?" @@ -162,7 +162,7 @@ do_pred_measure <- function( r_eff = 1 ) posthoc <- if (is.null(predperf)) { - .detect_posthoc(loo, psis_object) + .detect_posthoc(loo) } else { attr(predperf, "posthoc") } @@ -282,15 +282,14 @@ do_pred_measure <- function( #' `diagnostics$pareto_k` to 0 for the refitted observations but does not #' change `psis_object`, so the two sets of Pareto k values differ. #' -#' @param loo A [loo::loo()] result, or `NULL`. -#' @param psis_object The `psis` object used for the measures. +#' @param loo A [loo::loo()] result with a `psis_object`. #' #' @return A character vector of method names, or `NULL`. #' @noRd -.detect_posthoc <- function(loo, psis_object) { +.detect_posthoc <- function(loo) { method <- attr(loo, "posthoc") k_loo <- loo$diagnostics$pareto_k - k_psis <- psis_object$diagnostics$pareto_k + k_psis <- loo$psis_object$diagnostics$pareto_k if (!is.null(k_loo) && !is.null(k_psis) && !isTRUE(all.equal(k_loo, k_psis))) { method <- union(method, "reloo") } @@ -366,10 +365,7 @@ do_pred_measure <- function( ) { # psis_object + loo are both provided -> return psis_object if (!is.null(psis_object) && !is.null(loo)) { - pareto_k <- if (is.null(attr(loo, "posthoc"))) loo$diagnostics$pareto_k - .check_psis_match( - psis_object, loo$psis_object$log_weights, pareto_k, "loo" - ) + .check_psis_match(psis_object, loo$psis_object$log_weights, "loo") return(psis_object) # loo is provided } else if (!is.null(loo)) { @@ -380,7 +376,7 @@ do_pred_measure <- function( if (is.null(log_weights)) { log_weights <- predperf$psis_object$log_weights } - .check_psis_match(psis_object, log_weights, NULL, "predperf") + .check_psis_match(psis_object, log_weights, "predperf") return(psis_object) # predperf with psis_object is provided } else if (!is.null(predperf$psis_object)) { @@ -405,29 +401,19 @@ do_pred_measure <- function( #' Check that a `psis_object` matches the stored PSIS results #' -#' Compares the log weights when they are stored. Otherwise compares the -#' Pareto k values. `brms::reloo()` sets k to 0 for the refitted -#' observations, so those observations are not compared. +#' Compares the log weights. Without stored log weights there is no check. #' #' @param psis_object The supplied `psis` object. #' @param log_weights Stored log weights, or `NULL`. -#' @param pareto_k Stored Pareto k values, or `NULL`. #' @param arg Name of the argument that holds the stored results. #' #' @return `NULL`, invisibly. Called for the error. #' @noRd -.check_psis_match <- function(psis_object, log_weights, pareto_k, arg) { - if (!is.null(log_weights)) { - same <- isTRUE(all.equal(psis_object$log_weights, log_weights)) - } else if (!is.null(pareto_k)) { - keep <- pareto_k != 0 - same <- isTRUE(all.equal( - psis_object$diagnostics$pareto_k[keep], pareto_k[keep] - )) - } else { +.check_psis_match <- function(psis_object, log_weights, arg) { + if (is.null(log_weights)) { return(invisible(NULL)) } - if (!same) { + if (!isTRUE(all.equal(psis_object$log_weights, log_weights))) { cli::cli_abort( "{.arg psis_object} does not match the PSIS results in {.arg {arg}}." ) diff --git a/tests/testthat/test_pred_measure.R b/tests/testthat/test_pred_measure.R index f2d6fa9c4..dfa6c744e 100644 --- a/tests/testthat/test_pred_measure.R +++ b/tests/testthat/test_pred_measure.R @@ -130,17 +130,6 @@ test_that(".get_psis_object() errors if psis_object does not match loo", { ), regexp = "does not match" ) - - loo_nosave <- res$loo - loo_nosave$psis_object <- NULL - other <- res$loo$psis_object - other$diagnostics$pareto_k <- other$diagnostics$pareto_k + 0.1 - expect_error( - .get_psis_object( - ylp = NULL, loo = loo_nosave, predperf = NULL, psis_object = other - ), - regexp = "does not match" - ) }) ## .merge_matrix() --------------------------- @@ -416,23 +405,15 @@ test_that("pred_measure() errors if psis_object does not match the stored weight expect_true("mae_loo" %in% rownames(updated$estimates)) }) -test_that("loo_pred_measure() accepts a loo without psis_object and a psis_object", { +test_that("loo_pred_measure() errors for a loo without psis_object and a psis_object", { loo_nosave <- res$loo loo_nosave$psis_object <- NULL - out <- loo_pred_measure( - loo = loo_nosave, psis_object = res$loo$psis_object, - y = res$y, mupred = res$mupred, measures = c("elpd", "r2") - ) - expect_true(all(c("elpd_loo", "r2_loo") %in% rownames(out$estimates))) - - # reloo sets k to 0; those observations are not compared - loo_nosave$diagnostics$pareto_k[which.max(loo_nosave$diagnostics$pareto_k)] <- 0 - expect_warning( + expect_error( loo_pred_measure( loo = loo_nosave, psis_object = res$loo$psis_object, - y = res$y, mupred = res$mupred, measures = "r2" + y = res$y, mupred = res$mupred, measures = c("elpd", "r2") ), - regexp = "reloo" + regexp = "No psis_object found" ) }) From a7180c8e8248c3b1ef3884faa7a75c8a554f99b6 Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Wed, 25 Nov 2026 19:09:56 +0200 Subject: [PATCH 5/8] fix: check psis_object only when the user passes one --- R/pred_measure-compute.R | 1 - tests/testthat/test_pred_measure.R | 13 +++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/R/pred_measure-compute.R b/R/pred_measure-compute.R index aa9d264f1..4e3597b2b 100644 --- a/R/pred_measure-compute.R +++ b/R/pred_measure-compute.R @@ -133,7 +133,6 @@ do_pred_measure <- function( } else { if (is.null(psis_object) && !is.null(predperf$psis_object)) { cli::cli_inform("Using psis_object for LOO CV from `predperf`") - psis_object <- predperf$psis_object } } checkmate::assert_null(ylp_test) diff --git a/tests/testthat/test_pred_measure.R b/tests/testthat/test_pred_measure.R index dfa6c744e..d0bfc767f 100644 --- a/tests/testthat/test_pred_measure.R +++ b/tests/testthat/test_pred_measure.R @@ -405,6 +405,19 @@ test_that("pred_measure() errors if psis_object does not match the stored weight expect_true("mae_loo" %in% rownames(updated$estimates)) }) +test_that("pred_measure() checks psis_object only when the user passes one", { + predperf_loo <- loo_pred_measure( + loo = res$loo, y = res$y, mupred = res$mupred, measures = "r2", + save_psis = TRUE + ) + local_mocked_bindings(.check_psis_match = function(...) stop("checked")) + expect_no_error(suppressMessages( + pred_measure( + predperf = predperf_loo, y = res$y, mupred = res$mupred, measures = "mae" + ) + )) +}) + test_that("loo_pred_measure() errors for a loo without psis_object and a psis_object", { loo_nosave <- res$loo loo_nosave$psis_object <- NULL From 87577d214f899b69f5f91bdc48c8942faa5ee6a3 Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Wed, 25 Nov 2026 21:25:19 +0200 Subject: [PATCH 6/8] docs: drop the Pareto k case from the .get_psis_object() doc --- R/pred_measure-compute.R | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/R/pred_measure-compute.R b/R/pred_measure-compute.R index 4e3597b2b..e26f74d0a 100644 --- a/R/pred_measure-compute.R +++ b/R/pred_measure-compute.R @@ -333,8 +333,7 @@ do_pred_measure <- function( #' Resolution order: #' \enumerate{ #' \item If both `psis_object` and `loo` are provided, return `psis_object` -#' after verifying it matches `loo$psis_object`, or the Pareto k values -#' of `loo` when `loo` has no `psis_object`. +#' after verifying it matches `loo$psis_object`. #' \item Extract from `loo$psis_object` when `loo` is provided. #' \item Use the supplied `psis_object` after verifying it matches the #' weights stored in `predperf`. From 22e80de4ed2e570d38dd9c2c842866c1fcdbc2ce Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Wed, 25 Nov 2026 21:47:56 +0200 Subject: [PATCH 7/8] fix: drop the psis_object message on pred_measure() updates --- R/pred_measure-compute.R | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/R/pred_measure-compute.R b/R/pred_measure-compute.R index e26f74d0a..a8b9a39fa 100644 --- a/R/pred_measure-compute.R +++ b/R/pred_measure-compute.R @@ -123,17 +123,11 @@ do_pred_measure <- function( .validate_control(control, measures) needs_elpd <- .any_needs_elpd(measures) if (source == "loo") { - if (is.null(predperf)) { - if (!is.null(loo) && is.null(loo$psis_object)) { - cli::cli_abort(c( - "No {.field psis_object} found in {.arg loo}.", - "i" = "Did you run {.code loo(..., save_psis = TRUE)}?" - )) - } - } else { - if (is.null(psis_object) && !is.null(predperf$psis_object)) { - cli::cli_inform("Using psis_object for LOO CV from `predperf`") - } + if (is.null(predperf) && !is.null(loo) && is.null(loo$psis_object)) { + cli::cli_abort(c( + "No {.field psis_object} found in {.arg loo}.", + "i" = "Did you run {.code loo(..., save_psis = TRUE)}?" + )) } checkmate::assert_null(ylp_test) } else if (source == "insample") { From b6dfd3ef3039307ddd5fdc489284c313d19cb1a6 Mon Sep 17 00:00:00 2001 From: Florence Bockting Date: Thu, 26 Nov 2026 08:55:58 +0200 Subject: [PATCH 8/8] test: drop suppressMessages() in the psis_object check test --- tests/testthat/test_pred_measure.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/testthat/test_pred_measure.R b/tests/testthat/test_pred_measure.R index d0bfc767f..12501ff2a 100644 --- a/tests/testthat/test_pred_measure.R +++ b/tests/testthat/test_pred_measure.R @@ -411,11 +411,11 @@ test_that("pred_measure() checks psis_object only when the user passes one", { save_psis = TRUE ) local_mocked_bindings(.check_psis_match = function(...) stop("checked")) - expect_no_error(suppressMessages( + expect_no_error( pred_measure( predperf = predperf_loo, y = res$y, mupred = res$mupred, measures = "mae" ) - )) + ) }) test_that("loo_pred_measure() errors for a loo without psis_object and a psis_object", {