Skip to content

Commit

Permalink
Correctly sample points in nndm
Browse files Browse the repository at this point in the history
Fixes #160
  • Loading branch information
mikemahoney218 committed Sep 4, 2024
1 parent 9877514 commit 82e42da
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# spatialsample (development version)

* Fixed bug where passing a polygon to `spatial_nndm_cv()` forced leave-one-out
CV, rather than the intended sampling of prediction points from the polygon.

# spatialsample 0.5.1

* `spatial_block_cv()` now adds an `expand_bbox` attribute to the resulting rset
Expand Down
10 changes: 5 additions & 5 deletions R/spatial_nndm_cv.R
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,15 @@ spatial_nndm_cv <- function(data, prediction_sites, ...,
)

if (use_provided_points) {
sample_points <- prediction_sites
prediction_sites <- prediction_sites
} else if (sample_provided_poly) {
sample_points <- sf::st_sample(
prediction_sites <- sf::st_sample(
x = sf::st_geometry(prediction_sites),
size = prediction_sample_size,
...
)
} else {
sample_points <- sf::st_sample(
prediction_sites <- sf::st_sample(
x = sf::st_as_sfc(sf::st_bbox(prediction_sites)),
size = prediction_sample_size,
...
Expand All @@ -145,9 +145,9 @@ spatial_nndm_cv <- function(data, prediction_sites, ...,
# and will _sometimes_ warn instead (systematic sampling)
# but will _often_ strip CRS from the returned data;
# enforce here that our output prediction sites share a CRS with input data
if (is.na(sf::st_crs(sample_points))) {
if (is.na(sf::st_crs(prediction_sites))) {
prediction_sites <- sf::st_set_crs(
sample_points,
prediction_sites,
sf::st_crs(prediction_sites)
)
}
Expand Down
21 changes: 21 additions & 0 deletions tests/testthat/test-spatial_nndm_cv.R
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,24 @@ test_that("rsplit labels", {
original_id <- rs[, grepl("^id", names(rs))]
expect_equal(all_labs, original_id)
})

test_that("passing a polygon works correctly", {
ames_sf <- sf::st_as_sf(
modeldata::ames,
coords = c("Longitude", "Latitude"),
crs = 4326
)
ch <- st_concave_hull(st_union(ames_sf), ratio = 0.4, allow_holes = TRUE)

withr::with_seed(
123,
pts <- sf::st_sample(ch, 1000)
)
nndm_1 <- spatial_nndm_cv(ames_sf[1:100, ], pts)
attr(nndm_1, "prediction_sites") <- ch
withr::with_seed(
123,
nndm_2 <- spatial_nndm_cv(ames_sf[1:100, ], ch)
)
expect_identical(nndm_1, nndm_2)
})

0 comments on commit 82e42da

Please sign in to comment.