Skip to content

Commit

Permalink
Warn if prediction outside fitted #285
Browse files Browse the repository at this point in the history
  • Loading branch information
seananderson committed Mar 29, 2024
1 parent dae6e92 commit 0253e47
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions R/predict.R
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,20 @@ predict.sdmTMB <- function(object, newdata = NULL,
"Did you miss specifying the argument `xy_cols` to match your data?",
"The newer `make_mesh()` (vs. `make_spde()`) takes care of this for you."))

if (isFALSE(pop_pred) && !no_spatial) {
xy_orig <- object$data[,xy_cols]
xy_nd <- newdata[,xy_cols]
all_outside <- function(x1, x2) {
min(x1) > max(x2) || max(x1) < min(x2)
}
if (all_outside(xy_orig[,1], xy_nd[,1]) || all_outside(xy_orig[,2], xy_nd[,2])) {
cli_warn(c("`newdata` prediction coordinates appear to be ouside the fitted coordinates.",
"This will likely cause all your random field values to be returned as 0.",
"Check your coordinates including any conversions between projections.",
"If working with UTMs, are both in km or m?"))
}
}

if (object$time == "_sdmTMB_time") newdata[[object$time]] <- 0L
if (visreg_df) {
if (!object$time %in% names(newdata)) {
Expand Down
25 changes: 25 additions & 0 deletions tests/testthat/test-2-fit-less-basic.R
Original file line number Diff line number Diff line change
Expand Up @@ -507,4 +507,29 @@ test_that("Time with an NA gets flagged", {
}, regexp = "time")
})

test_that("Prediction outside fitted coordinates gets warned about #285", {
fit <- sdmTMB(
present ~ 1,
family = binomial(),
data = pcod_2011,
mesh = pcod_mesh_2011
)
nd <- qcs_grid
range(nd$X)
nd$X <- nd$X * 10
range(nd$X)
expect_warning(p <- predict(fit, newdata = nd), regexp = "coordinates")

nd <- qcs_grid
nd$X <- nd$X / 10
expect_warning(p <- predict(fit, newdata = nd), regexp = "coordinates")

nd <- qcs_grid
nd$Y <- nd$Y / 10
expect_warning(p <- predict(fit, newdata = nd), regexp = "coordinates")

nd <- qcs_grid
nd$Y <- nd$Y * 10
expect_warning(p <- predict(fit, newdata = nd), regexp = "coordinates")
})

1 change: 1 addition & 0 deletions tests/testthat/test-cross-validation.R
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ test_that("Basic cross validation works", {
})

test_that("Cross validation in parallel with globals", {
skip_on_cran()
# https://github.com/pbs-assess/sdmTMB/issues/127
d <- pcod
spde <- make_mesh(d, c("X", "Y"), cutoff = 15)
Expand Down

0 comments on commit 0253e47

Please sign in to comment.