Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export(sdmApp_TimesRasters)
export(sdmApp_background)
export(sdmApp_boyce)
export(sdmApp_broken_stick)
export(sdmApp_cluster_folds)
export(sdmApp_cmip6)
export(sdmApp_compare)
export(sdmApp_enfa)
Expand Down
10 changes: 10 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# sdmApp (development version)

## Environmental folds with missing values

* Fixed: environmental cross-validation folds failed ("The input raster
layer does not cover all the column points") when an occurrence point
fell on a cell without predictor values, for example on a coast. New
`sdmApp_cluster_folds()` clusters the points that have values and gives
the others no fold, which models ignore; the interface tells how many
points were left out, and the R-Code tab uses the new function. With
complete data the folds are unchanged.

## Example data in one click

* The Data Upload tab has a "Try with example data" button loading five
Expand Down
83 changes: 83 additions & 0 deletions R/sdmApp_folds.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#' Environmental cross-validation folds
#'
#' Groups occurrence points into `k` folds by k-means clustering of their
#' predictor values, with [blockCV::cv_cluster()], so that each test fold
#' holds environmental conditions the model was not fitted on, as when
#' projecting to a future climate (Roberts et al. 2017).
#'
#' Points falling on cells without values in every layer of `env` (for
#' example on coasts) cannot be clustered: they are left out of the
#' clustering and get no fold (`NA` in `folds_ids`), which [sdmApp_fit()]
#' ignores, as it ignores such points anyway. The clustering is seeded with
#' [set.seed()], as `blockCV::cv_cluster()` does not use its `seed`
#' argument for point data.
#'
#' @param occ An `sf` object of presence (1) and absence or background (0)
#' points, for example from [sdmApp_occurrences()].
#' @param env A `SpatRaster` of the predictors.
#' @param column Name of the 0/1 column of `occ`.
#' @param k Number of folds.
#' @param seed Seed of the clustering.
#'
#' @return A `cv_cluster` object of \pkg{blockCV} whose `folds_ids` has one
#' entry per row of `occ` (`NA` for points without predictor values) and
#' whose `folds_list` refers to rows of `occ`, to pass to the `fold_ids`
#' argument of [sdmApp_fit()] or [sdmApp_tune()]. Its `dropped` element
#' gives the number of points without predictor values.
#'
#' @references Roberts, D. R., Bahn, V., Ciuti, S., et al. (2017).
#' Cross-validation strategies for data with temporal, spatial,
#' hierarchical, or phylogenetic structure. *Ecography*, 40, 913--929.
#' \doi{10.1111/ecog.02881}
#'
#' @examples
#' \donttest{
#' if (requireNamespace("blockCV", quietly = TRUE)) {
#' env <- sdmApp_read_layers(system.file("extdata",
#' c("bio1.tif", "bio12.tif"),
#' package = "sdmApp"
#' ))
#' occ <- utils::read.csv2(system.file("extdata", "Niakhar.csv",
#' package = "sdmApp"
#' ))
#' occ <- sdmApp_occurrences(occ[1:500, ], "X_WGS84", "Y_WGS84",
#' "Faidherbia.albida",
#' crs = terra::crs(env)
#' )
#' folds <- sdmApp_cluster_folds(occ, env, "Faidherbia.albida", k = 4)
#' table(folds$folds_ids)
#' }
#' }
#' @export
sdmApp_cluster_folds <- function(occ, env, column, k = 5, seed = 1994) {
if (!requireNamespace("blockCV", quietly = TRUE)) {
stop("Environmental folds need the 'blockCV' package: ",
"install.packages(\"blockCV\")",
call. = FALSE
)
}
if (!inherits(occ, "sf")) {
stop("'occ' must be an sf object of points.", call. = FALSE)
}
values <- terra::extract(env, terra::vect(occ), ID = FALSE)
ok <- which(stats::complete.cases(values))
if (length(ok) < k) {
stop("Fewer points with predictor values (", length(ok), ") than ",
"folds (", k, ").",
call. = FALSE
)
}
set.seed(seed)
cv <- blockCV::cv_cluster(
x = occ[ok, ], column = column, r = env, k = k, biomod2 = FALSE,
progress = FALSE, report = FALSE
)
ids <- rep(NA_integer_, nrow(occ))
ids[ok] <- cv$folds_ids
cv$folds_ids <- ids
cv$folds_list <- lapply(cv$folds_list, function(fold) {
lapply(fold, function(rows) ok[rows])
})
cv$dropped <- nrow(occ) - length(ok)
cv
}
1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ reference:
- sdmApp_mess
- title: Cross-validation
contents:
- sdmApp_cluster_folds
- sdmApp_fold_Explorer

articles:
Expand Down
18 changes: 14 additions & 4 deletions inst/shiny/sdmApp/controllers/ui_spatial_blocks.R
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@ observeEvent(input$block_button, {
biomod2 = FALSE, plot = FALSE, progress = FALSE, report = FALSE
)
} else {
blockCV::cv_cluster(
x = occ_sf(), column = species(), r = env(),
k = input$number_fold, biomod2 = FALSE, progress = FALSE,
report = FALSE
sdmApp::sdmApp_cluster_folds(occ_sf(), env(), species(),
k = input$number_fold
)
}
),
Expand All @@ -54,6 +52,18 @@ observeEvent(input$block_button, {
list(type = "cluster", k = input$number_fold)
}
spatial_state$blocks <- result
if (isTRUE(result$dropped > 0)) {
showNotification(
sprintf(
paste(
"%d points have no predictor values (for example on coasts):",
"they were left out of the folds and of the models."
),
result$dropped
),
type = "warning", duration = 10
)
}
updateSliderInput(session, "test_fold", max = input$number_fold, value = 1)
})

Expand Down
8 changes: 3 additions & 5 deletions inst/shiny/sdmApp/helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -766,11 +766,9 @@ script_blocks <- function(blocks, species) {
if (identical(blocks$type, "cluster")) {
return(c(
r_section("Environmental clusters for cross-validation"),
"set.seed(1994)",
r_call("blockCV::cv_cluster", list(
x = r_code("occ"), column = species, r = r_code("env"),
k = blocks$k, biomod2 = r_code("FALSE"), progress = r_code("FALSE"),
report = r_code("FALSE")
r_call("sdmApp_cluster_folds", list(
r_code("occ"), r_code("env"), species,
k = blocks$k
), assign = "blocks")
))
}
Expand Down
66 changes: 66 additions & 0 deletions man/sdmApp_cluster_folds.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion tests/testthat/test-app-script.R
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ test_that("environmental folds are created and reproduced by the script", {
expect_true(model_fits$glm()$settings$spatial)

code <- current_code()
expect_true(any(grepl("blockCV::cv_cluster(", code, fixed = TRUE)))
expect_true(any(grepl("sdmApp_cluster_folds(", code, fixed = TRUE)))
steps <- steps_done()
expect_match(
steps$Details[steps$Step == "Cross-validation folds"], "environmental"
Expand Down
75 changes: 75 additions & 0 deletions tests/testthat/test-sdmApp_cluster_folds.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
cluster_data <- function() {
path <- function(f) system.file("extdata", f, package = "sdmApp")
env <- sdmApp_read_layers(path(c("bio1.tif", "bio12.tif")))
occ <- utils::read.csv2(path("Niakhar.csv"))[1:400, ]
occ <- sdmApp_occurrences(occ, "X_WGS84", "Y_WGS84", "Faidherbia.albida",
crs = terra::crs(env)
)
list(env = env, occ = occ)
}

test_that("environmental folds match blockCV on complete data", {
skip_on_cran()
skip_if_not_installed("blockCV")
d <- cluster_data()
folds <- sdmApp_cluster_folds(d$occ, d$env, "Faidherbia.albida", k = 3)
set.seed(1994)
direct <- blockCV::cv_cluster(
x = d$occ, column = "Faidherbia.albida", r = d$env, k = 3,
biomod2 = FALSE, progress = FALSE, report = FALSE
)
expect_identical(folds$folds_ids, direct$folds_ids)
expect_identical(folds$folds_list, direct$folds_list)
expect_equal(folds$dropped, 0)
# Reproducible.
expect_identical(
sdmApp_cluster_folds(d$occ, d$env, "Faidherbia.albida", k = 3)$folds_ids,
folds$folds_ids
)
})

test_that("points without predictor values get no fold", {
skip_on_cran()
skip_if_not_installed("blockCV")
skip_if_not(app_deps_available(c("terra", "dismo")))
d <- cluster_data()
# A presence outside the rasters (no predictor values), as on a coast.
outside <- d$occ[1, ]
sf::st_geometry(outside) <- sf::st_sfc(sf::st_point(c(-10, 10)),
crs = sf::st_crs(d$occ)
)
outside$Faidherbia.albida <- 1
occ <- rbind(d$occ[1:200, ], outside, d$occ[201:400, ])

folds <- sdmApp_cluster_folds(occ, d$env, "Faidherbia.albida", k = 3)
expect_length(folds$folds_ids, nrow(occ))
expect_true(is.na(folds$folds_ids[201]))
expect_false(anyNA(folds$folds_ids[-201]))
expect_equal(folds$dropped, 1)
# folds_list refers to rows of `occ`, without the point.
rows <- sort(unlist(lapply(folds$folds_list, `[[`, 2)))
expect_identical(rows, setdiff(seq_len(nrow(occ)), 201L))
for (i in seq_along(folds$folds_list)) {
expect_true(all(folds$folds_ids[folds$folds_list[[i]][[2]]] == i))
}

# Models and the fold explorer use the folds.
fit <- sdmApp_fit(d$env, occ, "Faidherbia.albida", "glm",
fold_ids = folds$folds_ids, uncertainty = FALSE
)
expect_equal(nrow(fit$fold_metrics), 3)
expect_s3_class(sdmApp_fold_Explorer(folds, d$env, occ, 1), "ggplot")
})

test_that("sdmApp_cluster_folds validates its input", {
skip_if_not_installed("blockCV")
d <- cluster_data()
expect_error(
sdmApp_cluster_folds(as.data.frame(d$occ), d$env, "Faidherbia.albida"),
"sf object"
)
expect_error(
sdmApp_cluster_folds(d$occ[1:2, ], d$env, "Faidherbia.albida", k = 3),
"Fewer points"
)
})
14 changes: 6 additions & 8 deletions vignettes/workflow.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ the same kind of script in its R-Code tab, for every step you run there.
|---|---|
| Data | `sdmApp_read_layers()`, `sdmApp_occurrences()`, `sdmApp_gbif()`, `sdmApp_background()`, `sdmApp_worldclim()`, `sdmApp_cmip6()`, `sdmApp_thin()` |
| Screening predictors | `sdmApp_vif()`, `sdmApp_enfa()` |
| Cross-validation folds | `blockCV::cv_spatial()`, `blockCV::cv_cluster()` |
| Cross-validation folds | `blockCV::cv_spatial()`, `sdmApp_cluster_folds()` |
| Settings | `sdmApp_tune()`, `sdmApp_tuning_grid()` |
| Fitting and evaluation | `sdmApp_fit()`, `sdmApp_null()` |
| Interpretation | `sdmApp_importance()`, `sdmApp_response()` |
Expand Down Expand Up @@ -130,8 +130,10 @@ are chosen decides what the evaluation measures:
* **environmental clusters** test transfer to new conditions, which is
what projecting to a future climate requires (Roberts et al. 2017).

blockCV builds the last two. Its random steps are seeded with `set.seed()`
(`cv_cluster()` does not use its `seed` argument for point data):
blockCV builds spatial blocks, seeded with `set.seed()`.
`sdmApp_cluster_folds()` builds environmental clusters with blockCV, seeds
them, and handles points without predictor values (for example on
coasts), which get no fold:

```{r folds}
set.seed(1994)
Expand All @@ -140,11 +142,7 @@ spatial <- blockCV::cv_spatial(occ,
size = 3000, k = 3, biomod2 = FALSE, plot = FALSE, progress = FALSE,
report = FALSE
)
set.seed(1994)
clusters <- blockCV::cv_cluster(occ,
column = "Faidherbia.albida", r = env,
k = 3, biomod2 = FALSE, progress = FALSE, report = FALSE
)
clusters <- sdmApp_cluster_folds(occ, env, "Faidherbia.albida", k = 3)
```

# Choosing the settings
Expand Down
Loading