|
| 1 | +# helper to create a small test raster |
| 2 | +make_raster <- function(outfile, crs = "EPSG:4326") { |
| 3 | + r <- terra::rast(matrix(1:16, 4, 4), |
| 4 | + extent = terra::ext(0, 4, 0, 4), |
| 5 | + crs = crs |
| 6 | + ) |
| 7 | + terra::writeRaster(r, outfile, filetype = "GTiff", overwrite = TRUE) |
| 8 | + return(outfile) |
| 9 | +} |
| 10 | + |
| 11 | +test_that("clip & mask works: output clipped to polygon bbox and masked", { |
| 12 | + in_r <- withr::local_tempfile(fileext = ".tif") |
| 13 | + out_f <- withr::local_tempfile(fileext = ".tif") |
| 14 | + |
| 15 | + make_raster(outfile = in_r) |
| 16 | + |
| 17 | + poly <- terra::as.polygons( |
| 18 | + terra::ext(1, 3, 1, 3), |
| 19 | + crs = "EPSG:4326" |
| 20 | + ) |
| 21 | + |
| 22 | + clip_and_save_raster_file(input_path = in_r, polygon = poly, out_path = out_f, mask = TRUE) |
| 23 | + |
| 24 | + expect_true(file.exists(out_f)) |
| 25 | + |
| 26 | + r_out <- terra::rast(out_f) |
| 27 | + expect_equal(terra::ext(r_out), terra::ext(sf::st_bbox(poly))) |
| 28 | + |
| 29 | + inside_vals <- terra::values(terra::mask(r_out, poly, inverse = FALSE)) |
| 30 | + expect_true(all(!is.na(inside_vals))) |
| 31 | + |
| 32 | + outside_vals <- terra::values(terra::mask(r_out, poly, inverse = TRUE)) |
| 33 | + expect_true(all(is.na(outside_vals))) |
| 34 | +}) |
| 35 | + |
| 36 | +test_that("clip without mask retains all values within bbox", { |
| 37 | + in_r <- withr::local_tempfile(fileext = ".tif") |
| 38 | + make_raster(outfile = in_r) |
| 39 | + |
| 40 | + poly <- sf::st_as_sf( |
| 41 | + sf::st_as_sfc( |
| 42 | + sf::st_bbox(c(xmin = 1, ymin = 1, xmax = 3, ymax = 3), crs = sf::st_crs(4326)) |
| 43 | + ) |
| 44 | + ) |
| 45 | + out_f <- withr::local_tempfile(fileext = ".tif") |
| 46 | + |
| 47 | + clip_and_save_raster_file(in_r, poly, out_f, mask = FALSE) |
| 48 | + r_out <- terra::rast(out_f) |
| 49 | + expect_false(any(is.na(terra::values(r_out)))) |
| 50 | +}) |
| 51 | + |
| 52 | +test_that("preserves CRS and filetype", { |
| 53 | + in_r_path <- withr::local_tempfile(fileext = ".tif") |
| 54 | + make_raster(outfile = in_r_path, crs = "EPSG:3857") |
| 55 | + |
| 56 | + spatvect_raster <- terra::rast(in_r_path) |
| 57 | + |
| 58 | + poly <- sf::st_as_sf( |
| 59 | + sf::st_as_sfc( |
| 60 | + sf::st_bbox(c(xmin = 1, ymin = 1, xmax = 3, ymax = 3), crs = sf::st_crs(3857)) |
| 61 | + ) |
| 62 | + ) |
| 63 | + out_f_path <- withr::local_tempfile(fileext = ".tif") |
| 64 | + |
| 65 | + clip_and_save_raster_file(input_path = in_r_path, polygon = poly, out_path = out_f_path) |
| 66 | + r_out <- terra::rast(out_f_path) |
| 67 | + |
| 68 | + expect_equal( |
| 69 | + tools::file_ext(terra::sources(r_out)[1]), |
| 70 | + tools::file_ext(terra::sources(spatvect_raster)[1]) |
| 71 | + ) |
| 72 | + expect_true(terra::same.crs(r_out, spatvect_raster)) |
| 73 | +}) |
0 commit comments