diff --git a/NEWS.md b/NEWS.md index d6df0696..02a7c21c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -16,6 +16,7 @@ selected. * Add additional unit tests for `uniformity_test()` * Remove the offset at a tied Pareto tail cutoff in `ps_tail()` and `pareto_pit()` (#468) * Use a tolerance relative to the magnitude of `x` in `is_constant()` (#469) +* Use `x >= q` for the upper tail in `ess_quantile()` (#471) # posterior 1.7.1 diff --git a/R/convergence.R b/R/convergence.R index 26569a99..e13f17df 100644 --- a/R/convergence.R +++ b/R/convergence.R @@ -296,7 +296,11 @@ ess_median <- function(x, ...) { len <- length(x) prob <- (len - 0.5) / len } - I <- x <= quantile(x, prob) + q <- quantile(x, prob) + # the upper-tail indicator mirrors the lower-tail indicator, so that for + # discrete draws the result for x at prob equals the result for -x at + # 1 - prob + I <- if (prob > 0.5) x >= q else x <= q .ess(.split_chains(I)) } diff --git a/tests/testthat/test-convergence.R b/tests/testthat/test-convergence.R index 404bfa90..38786899 100644 --- a/tests/testthat/test-convergence.R +++ b/tests/testthat/test-convergence.R @@ -115,6 +115,30 @@ test_that("convergence diagnostics handle special cases correctly", { # expect_true(is.na(ess_basic(x))) }) +test_that("ess_quantile treats the lower and upper tails of discrete draws alike", { + set.seed(1234) + x <- matrix(rbinom(4000, 1, 0.3), ncol = 4) + # more than 5% of the draws are at the maximum + expect_false(is.na(ess_quantile(x, 0.95))) + expect_false(is.na(ess_tail(x))) + expect_equal( + ess_quantile(x, 0.95, names = FALSE), + ess_quantile(-x, 0.05, names = FALSE) + ) + expect_equal( + ess_quantile(x, 0.05, names = FALSE), + ess_quantile(-x, 0.95, names = FALSE) + ) + expect_equal(ess_tail(x), ess_tail(-x)) + + # for continuous draws, x >= q is the complement of x <= q + y <- matrix(rnorm(4000), ncol = 4) + expect_equal( + ess_quantile(y, 0.95, names = FALSE), + .ess(.split_chains(y <= quantile(y, 0.95))) + ) +}) + test_that("is_constant uses a tolerance relative to the magnitude of x", { eps <- .Machine$double.eps expect_true(is_constant(rep(0, 5)))