|
| 1 | +#' Spatial block cross-validation |
| 2 | +#' |
| 3 | +#' Block cross-validation splits the area of your data into a number of |
| 4 | +#' grid cells, or "blocks", and then assigns all data into folds based on the |
| 5 | +#' blocks they fall into. |
| 6 | +#' |
| 7 | +#' @details |
| 8 | +#' The grid blocks can be controlled by passing arguments to |
| 9 | +#' [sf::st_make_grid()] via `...`. Some particularly useful arguments include: |
| 10 | +#' |
| 11 | +#' * `cellsize` Target cellsize, expressed as the "diameter" (shortest |
| 12 | +#' straight-line distance between opposing sides; two times the apothem) |
| 13 | +#' of each block, in map units. |
| 14 | +#' * `n` The number of grid blocks in the x and y direction (columns, rows). |
| 15 | +#' * `square` A logical value indicating whether to create square (`TRUE`) or |
| 16 | +#' hexagonal (`FALSE`) cells. |
| 17 | +#' |
| 18 | +#' If both `cellsize` and `n` are provided, then the number of blocks requested |
| 19 | +#' by `n` of sizes specified by `cellsize` will be returned, likely not |
| 20 | +#' lining up with the bounding box of `data`. If only `cellsize` |
| 21 | +#' is provided, this function will return as many blocks of size |
| 22 | +#' `cellsize` as fit inside the bounding box of `data`. If only `n` is provided, |
| 23 | +#' then `cellsize` will be automatically adjusted to create the requested |
| 24 | +#' number of cells. |
| 25 | +#' |
| 26 | +#' @param data An object of class `sf` or `sfc`. |
| 27 | +#' @param method The method used to sample blocks for cross validation folds. |
| 28 | +#' Currently, only `"random"` is supported. |
| 29 | +#' @inheritParams rsample::vfold_cv |
| 30 | +#' @param ... Arguments passed to [sf::st_make_grid()]. |
| 31 | +#' |
| 32 | +#' @return A tibble with classes `spatial_block_cv`, `rset`, `tbl_df`, `tbl`, |
| 33 | +#' and `data.frame`. The results include a column for the data split objects |
| 34 | +#' and an identification variable `id`. |
| 35 | +#' |
| 36 | +#' @examples |
| 37 | +#' data(Smithsonian, package = "modeldata") |
| 38 | +#' smithsonian_sf <- sf::st_as_sf(Smithsonian, |
| 39 | +#' coords = c("longitude", "latitude"), |
| 40 | +#' # Set CRS to WGS84 |
| 41 | +#' crs = 4326) |
| 42 | +#' |
| 43 | +#' spatial_block_cv(smithsonian_sf, v = 3) |
| 44 | +#' |
| 45 | +#' @references |
| 46 | +#' |
| 47 | +#' D. R. Roberts, V. Bahn, S. Ciuti, M. S. Boyce, J. Elith, G. Guillera-Arroita, |
| 48 | +#' S. Hauenstein, J. J. Lahoz-Monfort, B. Schröder, W. Thuiller, D. I. Warton, |
| 49 | +#' B. A. Wintle, F. Hartig, and C. F. Dormann. "Cross-validation strategies for |
| 50 | +#' data with temporal, spatial, hierarchical, or phylogenetic structure," 2016, |
| 51 | +#' Ecography 40(8), pp. 913-929, doi: 10.1111/ecog.02881. |
| 52 | +#' |
| 53 | +#' @export |
| 54 | +spatial_block_cv <- function(data, method = "random", v = 10, ...) { |
| 55 | + method <- rlang::arg_match(method) |
| 56 | + |
| 57 | + if (!"sf" %in% class(data)) { |
| 58 | + rlang::abort( |
| 59 | + c( |
| 60 | + "`spatial_block_cv()` currently only supports `sf` objects.", |
| 61 | + i = "Try converting `data` to an `sf` object via `sf::st_as_sf()`." |
| 62 | + ) |
| 63 | + ) |
| 64 | + } |
| 65 | + |
| 66 | + if (sf::st_crs(data) == sf::NA_crs_) { |
| 67 | + rlang::abort( |
| 68 | + c( |
| 69 | + "`spatial_block_cv()` requires your data to have an appropriate coordinate reference system (CRS).", |
| 70 | + i = "Try setting a CRS using `sf::st_set_crs()`." |
| 71 | + ) |
| 72 | + ) |
| 73 | + } |
| 74 | + |
| 75 | + grid_box <- sf::st_bbox(data) |
| 76 | + if (sf::st_is_longlat(data)) { |
| 77 | + # cf https://github.com/ropensci/stplanr/pull/467 |
| 78 | + # basically: spherical geometry means sometimes the straight line of the |
| 79 | + # grid will exclude points within the bounding box |
| 80 | + # |
| 81 | + # so here we'll expand our boundary by 0.1% in order to always contain our |
| 82 | + # points within the grid |
| 83 | + grid_box[1] <- grid_box[1] - abs(grid_box[1] * 0.001) |
| 84 | + grid_box[2] <- grid_box[2] - abs(grid_box[2] * 0.001) |
| 85 | + grid_box[3] <- grid_box[3] + abs(grid_box[3] * 0.001) |
| 86 | + grid_box[4] <- grid_box[4] + abs(grid_box[4] * 0.001) |
| 87 | + } |
| 88 | + grid_blocks <- sf::st_make_grid(grid_box, ...) |
| 89 | + split_objs <- switch( |
| 90 | + method, |
| 91 | + "random" = random_block_cv(data, grid_blocks, v) |
| 92 | + ) |
| 93 | + v <- split_objs$v[[1]] |
| 94 | + split_objs$v <- NULL |
| 95 | + |
| 96 | + ## We remove the holdout indices since it will save space and we can |
| 97 | + ## derive them later when they are needed. |
| 98 | + split_objs$splits <- map(split_objs$splits, rm_out) |
| 99 | + |
| 100 | + ## Save some overall information |
| 101 | + cv_att <- list(v = v) |
| 102 | + |
| 103 | + new_rset( |
| 104 | + splits = split_objs$splits, |
| 105 | + ids = split_objs[, grepl("^id", names(split_objs))], |
| 106 | + attrib = cv_att, |
| 107 | + subclass = c("spatial_block_cv", "rset") |
| 108 | + ) |
| 109 | + |
| 110 | +} |
| 111 | + |
| 112 | +random_block_cv <- function(data, grid_blocks, v) { |
| 113 | + n <- nrow(data) |
| 114 | + |
| 115 | + block_contains_points <- purrr::map_lgl( |
| 116 | + sf::st_intersects(grid_blocks, data), |
| 117 | + sgbp_is_not_empty |
| 118 | + ) |
| 119 | + grid_blocks <- grid_blocks[block_contains_points] |
| 120 | + |
| 121 | + n_blocks <- length(grid_blocks) |
| 122 | + if (!is.numeric(v) || length(v) != 1) { |
| 123 | + rlang::abort("`v` must be a single integer.") |
| 124 | + } |
| 125 | + if (v > n_blocks) { |
| 126 | + rlang::warn(paste0( |
| 127 | + "Fewer than ", v, " blocks available for sampling; setting v to ", |
| 128 | + n_blocks, "." |
| 129 | + )) |
| 130 | + v <- n_blocks |
| 131 | + } |
| 132 | + |
| 133 | + grid_blocks <- sf::st_as_sf(grid_blocks) |
| 134 | + grid_blocks$fold <- sample(rep(seq_len(v), length.out = nrow(grid_blocks))) |
| 135 | + grid_blocks <- split_unnamed(grid_blocks, grid_blocks$fold) |
| 136 | + |
| 137 | + # grid_blocks is now a list of sgbp lists (?sf::sgbp) |
| 138 | + # |
| 139 | + # The first map() here iterates through the meta-list, |
| 140 | + # and the second checks each element of the relevant sgbp list |
| 141 | + # to see if it is integer(0) (no intersections) or not |
| 142 | + # |
| 143 | + # Each sgbp sub-list is nrow(data) elements long, so this which() |
| 144 | + # returns the list indices which are not empty, which is equivalent |
| 145 | + # to the row numbers that intersect with blocks in the fold |
| 146 | + indices <- purrr::map( |
| 147 | + grid_blocks, |
| 148 | + function(blocks) which( |
| 149 | + purrr::map_lgl( |
| 150 | + sf::st_intersects(data, blocks), |
| 151 | + sgbp_is_not_empty |
| 152 | + ) |
| 153 | + ) |
| 154 | + ) |
| 155 | + |
| 156 | + indices <- lapply(indices, default_complement, n = n) |
| 157 | + split_objs <- purrr::map( |
| 158 | + indices, |
| 159 | + make_splits, |
| 160 | + data = data, |
| 161 | + class = "spatial_block_split" |
| 162 | + ) |
| 163 | + tibble::tibble( |
| 164 | + splits = split_objs, |
| 165 | + id = names0(length(split_objs), "Fold"), |
| 166 | + v = v |
| 167 | + ) |
| 168 | +} |
| 169 | + |
| 170 | +# Check sparse geometry binary predicate for empty elements |
| 171 | +# See ?sf::sgbp for more information on the data structure |
| 172 | +sgbp_is_not_empty <- function(x) !identical(x, integer(0)) |
0 commit comments