diff --git a/NAMESPACE b/NAMESPACE index e7c02fe..d044a61 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -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) diff --git a/NEWS.md b/NEWS.md index 7218980..ed0b09f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 diff --git a/R/sdmApp_folds.R b/R/sdmApp_folds.R new file mode 100644 index 0000000..26b9f5b --- /dev/null +++ b/R/sdmApp_folds.R @@ -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 +} diff --git a/_pkgdown.yml b/_pkgdown.yml index f0874f8..d4ad3ca 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -73,6 +73,7 @@ reference: - sdmApp_mess - title: Cross-validation contents: + - sdmApp_cluster_folds - sdmApp_fold_Explorer articles: diff --git a/inst/shiny/sdmApp/controllers/ui_spatial_blocks.R b/inst/shiny/sdmApp/controllers/ui_spatial_blocks.R index 8a10ea7..33e408a 100644 --- a/inst/shiny/sdmApp/controllers/ui_spatial_blocks.R +++ b/inst/shiny/sdmApp/controllers/ui_spatial_blocks.R @@ -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 ) } ), @@ -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) }) diff --git a/inst/shiny/sdmApp/helpers.R b/inst/shiny/sdmApp/helpers.R index 43546fd..71a5ae5 100644 --- a/inst/shiny/sdmApp/helpers.R +++ b/inst/shiny/sdmApp/helpers.R @@ -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") )) } diff --git a/man/sdmApp_cluster_folds.Rd b/man/sdmApp_cluster_folds.Rd new file mode 100644 index 0000000..1b32505 --- /dev/null +++ b/man/sdmApp_cluster_folds.Rd @@ -0,0 +1,66 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/sdmApp_folds.R +\name{sdmApp_cluster_folds} +\alias{sdmApp_cluster_folds} +\title{Environmental cross-validation folds} +\usage{ +sdmApp_cluster_folds(occ, env, column, k = 5, seed = 1994) +} +\arguments{ +\item{occ}{An \code{sf} object of presence (1) and absence or background (0) +points, for example from \code{\link[=sdmApp_occurrences]{sdmApp_occurrences()}}.} + +\item{env}{A \code{SpatRaster} of the predictors.} + +\item{column}{Name of the 0/1 column of \code{occ}.} + +\item{k}{Number of folds.} + +\item{seed}{Seed of the clustering.} +} +\value{ +A \code{cv_cluster} object of \pkg{blockCV} whose \code{folds_ids} has one +entry per row of \code{occ} (\code{NA} for points without predictor values) and +whose \code{folds_list} refers to rows of \code{occ}, to pass to the \code{fold_ids} +argument of \code{\link[=sdmApp_fit]{sdmApp_fit()}} or \code{\link[=sdmApp_tune]{sdmApp_tune()}}. Its \code{dropped} element +gives the number of points without predictor values. +} +\description{ +Groups occurrence points into \code{k} folds by k-means clustering of their +predictor values, with \code{\link[blockCV:cv_cluster]{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). +} +\details{ +Points falling on cells without values in every layer of \code{env} (for +example on coasts) cannot be clustered: they are left out of the +clustering and get no fold (\code{NA} in \code{folds_ids}), which \code{\link[=sdmApp_fit]{sdmApp_fit()}} +ignores, as it ignores such points anyway. The clustering is seeded with +\code{\link[=set.seed]{set.seed()}}, as \code{blockCV::cv_cluster()} does not use its \code{seed} +argument for point data. +} +\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) +} +} +} +\references{ +Roberts, D. R., Bahn, V., Ciuti, S., et al. (2017). +Cross-validation strategies for data with temporal, spatial, +hierarchical, or phylogenetic structure. \emph{Ecography}, 40, 913--929. +\doi{10.1111/ecog.02881} +} diff --git a/tests/testthat/test-app-script.R b/tests/testthat/test-app-script.R index a30b736..439dac6 100644 --- a/tests/testthat/test-app-script.R +++ b/tests/testthat/test-app-script.R @@ -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" diff --git a/tests/testthat/test-sdmApp_cluster_folds.R b/tests/testthat/test-sdmApp_cluster_folds.R new file mode 100644 index 0000000..0d5d5b5 --- /dev/null +++ b/tests/testthat/test-sdmApp_cluster_folds.R @@ -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" + ) +}) diff --git a/vignettes/workflow.Rmd b/vignettes/workflow.Rmd index 597c0df..c65859d 100644 --- a/vignettes/workflow.Rmd +++ b/vignettes/workflow.Rmd @@ -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()` | @@ -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) @@ -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