diff --git a/DESCRIPTION b/DESCRIPTION index 7ad7ff87..e0b6e259 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: epipredict Title: Basic epidemiology forecasting methods -Version: 0.2.9 +Version: 0.2.10 Authors@R: c( person("Daniel J.", "McDonald", , "daniel@stat.ubc.ca", role = c("aut", "cre")), person("Ryan", "Tibshirani", , "ryantibs@cmu.edu", role = "aut"), diff --git a/NAMESPACE b/NAMESPACE index 96cf927c..65ef3620 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -242,10 +242,12 @@ importFrom(cli,cli_warn) importFrom(dplyr,"%>%") importFrom(dplyr,across) importFrom(dplyr,all_of) +importFrom(dplyr,anti_join) importFrom(dplyr,any_of) importFrom(dplyr,arrange) importFrom(dplyr,bind_cols) importFrom(dplyr,bind_rows) +importFrom(dplyr,distinct) importFrom(dplyr,everything) importFrom(dplyr,filter) importFrom(dplyr,full_join) diff --git a/NEWS.md b/NEWS.md index 7b5e41b0..8dbd4ea7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,10 @@ Pre-1.0.0 numbering scheme: 0.x will indicate releases, while 0.0.x will indicate PR's. +# epipredict 0.2.10 + +- `layer_residual_quantiles(by_key = )` reports keys with missing training residuals, and warns when unseen prediction keys yield `NA` quantiles. + # epipredict 0.2.9 - `layer_residual_quantiles(by_key = )` now computes residual quantiles within each key and matches them to predictions by key. Before, `flatline_forecaster(quantile_by_key = "geo_value")` pooled residuals across all locations, and grouped quantiles errored when a key had no prediction. @@ -16,7 +20,6 @@ Pre-1.0.0 numbering scheme: 0.x will indicate releases, while 0.0.x will indicat `epiprocess:::autoplot.epi_df(.max_facets = Inf)`. This argument no longer exists there, so it caused an error (noted by rebuilding the `README.Rmd`) - # epipredict 0.2.6 - `arx_forecaster()` and `flatline_forecaster()` now error early when `quantile_by_key` contains columns that are not keys of the input `epi_df`, rather than silently dropping the invalid keys (#229). diff --git a/R/epipredict-package.R b/R/epipredict-package.R index fae8c3c6..f1a19dfd 100644 --- a/R/epipredict-package.R +++ b/R/epipredict-package.R @@ -7,7 +7,7 @@ #' @importFrom cli cli_abort cli_warn #' @importFrom dplyr arrange across all_of any_of bind_cols bind_rows group_by #' @importFrom dplyr full_join relocate summarise everything -#' @importFrom dplyr inner_join +#' @importFrom dplyr inner_join anti_join distinct #' @importFrom dplyr summarize filter mutate select left_join rename ungroup #' @importFrom epiprocess growth_rate growth_rate_params is_epi_df #' @importFrom lifecycle deprecated diff --git a/R/layer_residual_quantiles.R b/R/layer_residual_quantiles.R index 71127337..7bc3c33a 100644 --- a/R/layer_residual_quantiles.R +++ b/R/layer_residual_quantiles.R @@ -103,7 +103,7 @@ slather.layer_residual_quantiles <- r <- grab_residuals(the_fit, components) ## Handle any grouping requests - grps <- character(0L) + common <- character(0L) if (length(object$by_key) > 0L) { key_cols <- bind_cols( geo_value = components$mold$extras$roles$geo_value, @@ -112,25 +112,25 @@ slather.layer_residual_quantiles <- common <- intersect(object$by_key, names(key_cols)) excess <- setdiff(object$by_key, names(key_cols)) if (length(excess) > 0L) { - cli_warn(paste( - "Requested residual grouping key(s) {.val {excess}} are unavailable ", - "in the original data. Grouping by the remainder: {.val {common}}." + cli_warn(c( + "Residual grouping key{?s} {.val {excess}} {?was/were} not found in the training data.", + i = if (length(common) > 0L) { + "Residual quantiles will be grouped by the remaining key{?s}: {.val {common}}." + } else { + "Residual quantiles will be calculated across all observations without grouping." + } )) } if (length(common) > 0L) { r <- r %>% select(any_of(c(common, ".resid"))) - common_in_r <- common[common %in% names(r)] - if (length(common_in_r) == length(common)) { - r <- group_by(r, !!!rlang::syms(common)) - } else { + if (!all(common %in% names(r))) { cli_warn(paste( "Some grouping keys are not in data.frame returned by the", "`residuals()` method. Groupings may not be correct." )) - r <- bind_cols(key_cols, select(r, .resid)) %>% - group_by(!!!rlang::syms(common)) + r <- bind_cols(key_cols, select(r, .resid)) } - grps <- common + r <- group_by(r, !!!rlang::syms(common)) } } @@ -140,20 +140,48 @@ slather.layer_residual_quantiles <- probs = object$quantile_levels, na.rm = TRUE ), nrow = 1), quantile_levels = object$quantile_levels)) # Check for NA - if (anyNA(as.matrix(r$dstn))) { + na_rows <- rowSums(is.na(as.matrix(r$dstn))) > 0 + if (length(common) > 0L && any(na_rows) && !all(na_rows)) { + bad <- do.call(paste, c(r[na_rows, common], sep = " / ")) + cli_abort(c( + "Residual quantiles could not be calculated for some keys.", + x = "All training residuals are missing (`NA`) for: {.val {bad}}.", + i = paste( + "This typically happens when a key has too few training observations", + "for the forecast horizon." + ) + )) + } + if (any(na_rows)) { cli_abort(c( "Residual quantiles could not be calculated due to missing residuals.", - i = "This may be due to `n_train` < `ahead` in your {.cls epi_recipe}." + i = paste( + "This can happen when the training window has fewer observations than", + "the forecast horizon (for example, `n_training` < `ahead` or", + "`n_train` < `ahead`)." + ) )) } estimate <- components$predictions$.pred - if (length(grps) > 0L) { + if (length(common) > 0L) { # match each prediction to the residual quantiles of its own key - r <- left_join( - select(components$predictions, all_of(grps)), r, - by = grps, relationship = "many-to-one" - ) + keys <- select(components$predictions, all_of(common)) + unseen <- anti_join(distinct(keys), r, by = common) + if (nrow(unseen) > 0L) { + unseen_keys <- do.call(paste, c(unseen, sep = " / ")) + cli_warn(c( + paste( + "Prediction data contains {cli::qty(length(unseen_keys))}{?a key/keys}", + "not present in the training data: {.val {unseen_keys}}." + ), + i = paste( + "Because {?this key has/these keys have} no training residuals,", + "predictive distribution quantiles ({.col {object$name}}) will be `NA`." + ) + )) + } + r <- left_join(keys, r, by = common, relationship = "many-to-one") } res <- tibble(.pred_distn = r$dstn + estimate) res <- check_name( @@ -172,28 +200,37 @@ grab_residuals <- function(the_fit, components) { } r <- stats::residuals(the_fit$fit) if (!is.null(r)) { # Got something from the method + cl <- class(the_fit$fit) if (inherits(r, "data.frame")) { if (".resid" %in% names(r)) { # success return(r) } else { # failure cli_warn(c( - "The `residuals()` method for objects of class {.cls {cl}} results in", - "a data frame without a column named `.resid`.", - i = "Residual quantiles will be calculated directly from the", - i = "difference between predictions and observations.", - i = "This may result in unexpected behaviour." + paste( + "The `residuals()` method for objects of class {.cls {cl}} returned", + "a data frame without a column named {.col .resid}." + ), + i = paste( + "Residual quantiles will be calculated directly from the difference", + "between predictions and observations." + ), + i = "This may result in unexpected behavior." )) } } else if (is.vector(drop(r))) { # also success return(tibble(.resid = drop(r))) } else { # failure - cli_warn(paste( - "The `residuals()` method for objects of class {.cls {cl}} results in an", - "object that is neither a data frame with a column named `.resid`,", - "nor something coercible to a vector.", - i = "Residual quantiles will be calculated directly from the", - i = "difference between predictions and observations.", - i = "This may result in unexpected behaviour." + cli_warn(c( + paste( + "The `residuals()` method for objects of class {.cls {cl}} returned", + "an object that is neither a data frame with a column named", + "{.col .resid} nor coercible to a vector." + ), + i = paste( + "Residual quantiles will be calculated directly from the difference", + "between predictions and observations." + ), + i = "This may result in unexpected behavior." )) } } diff --git a/tests/testthat/_snaps/layer_residual_quantiles.md b/tests/testthat/_snaps/layer_residual_quantiles.md index 41aa0448..5948f7d0 100644 --- a/tests/testthat/_snaps/layer_residual_quantiles.md +++ b/tests/testthat/_snaps/layer_residual_quantiles.md @@ -6,6 +6,17 @@ Error in `grab_residuals()`: ! For meaningful residuals, the predictor should be a regression model. +# by_key names the keys without usable residuals + + Code + flatline_forecaster(jhu_short, "death_rate", args_list = flatline_args_list( + quantile_by_key = "geo_value")) + Condition + Error in `slather()`: + ! Residual quantiles could not be calculated for some keys. + x All training residuals are missing (`NA`) for: "tx". + i This typically happens when a key has too few training observations for the forecast horizon. + # flatline_forecaster correctly errors when n_training < ahead Code @@ -14,5 +25,5 @@ Condition Error in `slather()`: ! Residual quantiles could not be calculated due to missing residuals. - i This may be due to `n_train` < `ahead` in your . + i This can happen when the training window has fewer observations than the forecast horizon (for example, `n_training` < `ahead` or `n_train` < `ahead`). diff --git a/tests/testthat/test-layer_residual_quantiles.R b/tests/testthat/test-layer_residual_quantiles.R index 02b36901..e7eb3c42 100644 --- a/tests/testthat/test-layer_residual_quantiles.R +++ b/tests/testthat/test-layer_residual_quantiles.R @@ -77,7 +77,7 @@ test_that("Grouping by keys is supported", { layer_naomit(.pred) %>% layer_residual_quantiles(by_key = "geo_value") wf2 <- wf %>% add_frosting(f2) - expect_warning(p2 <- forecast(wf2)) + expect_warning(p2 <- forecast(wf2), "grouping keys") pivot1 <- pivot_quantiles_wider(p1, .pred_distn) %>% mutate(width = `0.95` - `0.05`) @@ -125,6 +125,62 @@ test_that("by_key matches residual quantiles to predictions by key", { expect_false(anyNA(as.matrix(p$.pred_distn))) }) +test_that("by_key names the keys without usable residuals", { + # tx has too few observations for a single 7-day flatline residual + short <- covid_case_death_rates %>% + dplyr::filter(geo_value == "tx", time_value > max(jhu$time_value) - 3) + jhu_short <- dplyr::bind_rows(jhu, short) %>% as_epi_df() + expect_snapshot( + error = TRUE, + flatline_forecaster(jhu_short, "death_rate", args_list = flatline_args_list( + quantile_by_key = "geo_value" + )) + ) +}) + +test_that("by_key warns for keys that were not in training", { + f <- frosting() %>% + layer_predict() %>% + layer_naomit(.pred) %>% + layer_residual_quantiles(by_key = "geo_value") + wf_no_ak <- epi_workflow(r, parsnip::linear_reg(), f) %>% + fit(dplyr::filter(jhu, geo_value != "ak")) + expect_warning( + expect_warning( + p <- predict(wf_no_ak, get_test_data(r, jhu)), + "no training residuals" + ), + "grouping keys" + ) + expect_true(all(is.na(as.matrix(p$.pred_distn[p$geo_value == "ak"])))) + expect_false(anyNA(as.matrix(p$.pred_distn[p$geo_value != "ak"]))) +}) + +test_that("by_key warns informatively when requested keys are unavailable", { + f_some <- frosting() %>% + layer_predict() %>% + layer_naomit(.pred) %>% + layer_residual_quantiles(by_key = c("nonexistent", "geo_value")) + wf_some <- epi_workflow(r, parsnip::linear_reg(), f_some) %>% fit(jhu) + expect_warning( + expect_warning( + predict(wf_some, get_test_data(r, jhu)), + "Residual grouping key \"nonexistent\" was not found in the training data" + ), + "grouping keys" + ) + + f_none <- frosting() %>% + layer_predict() %>% + layer_naomit(.pred) %>% + layer_residual_quantiles(by_key = "nonexistent") + wf_none <- epi_workflow(r, parsnip::linear_reg(), f_none) %>% fit(jhu) + expect_warning( + predict(wf_none, get_test_data(r, jhu)), + "calculated across all observations without grouping" + ) +}) + test_that("Canned forecasters work with / without", { meta <- attr(jhu, "metadata") meta$as_of <- max(jhu$time_value)