From c136736611e235940a132c91dc05f6bf6430af97 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 30 Sep 2026 19:00:37 -0700 Subject: [PATCH 1/3] prepClimateLayers: write multi-layer stacks band-interleaved and tiled Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CwcjqqK59FmTJscyi7xUqv --- NEWS.md | 1 + R/prepClimateLayers.R | 45 ++++++++++++++++-- tests/testthat/test-writeClimateStack.R | 62 +++++++++++++++++++++++++ 3 files changed, 104 insertions(+), 4 deletions(-) create mode 100644 tests/testthat/test-writeClimateStack.R diff --git a/NEWS.md b/NEWS.md index 2f3a740..55fd74f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # climateData (development version) +- `prepClimateLayers()` now writes multi-layer climate stacks band-interleaved in 256 x 256 tiles (`INTERLEAVE=BAND`, `TILED=YES`) instead of pixel-interleaved 1-row strips, so reading one year's layer no longer decompresses every layer in the file (about 8.8 s down to 0.14 s for a 90-layer stack). Values are unchanged. The creation options are part of the cache key, so existing stacks are rebuilt the next time `prepClimateLayers()` runs. - When a seasonal variable is needed, monthly and yearly variables now come from the same MSY ("all") archive, which contains all their files. Before, they were also downloaded from their own M and Y archives unless M, S and Y were all needed. Some M archives on the server are incomplete (tile 46's future 2080s diff --git a/R/prepClimateLayers.R b/R/prepClimateLayers.R index 089b6e6..7178f93 100644 --- a/R/prepClimateLayers.R +++ b/R/prepClimateLayers.R @@ -471,6 +471,7 @@ prepClimateLayers <- function( "studyAreaName" ) |> mget(envir = environment()) |> + c(list(gdalOptions = .climateStackGdalOptions)) |> ## so older pixel-interleaved files are rebuilt .robustDigest(object = _) climData <- lapply(names(climDataFun), function(nm) { @@ -479,13 +480,11 @@ prepClimateLayers <- function( var <- stringr::str_remove(nm, paste0(type, "_")) fname <- paste(var, type, studyAreaName, sep = "_") climRast <- - postProcessTo( + .postProcessAndWriteClimate( from = newClimRast, to = rasterToMatch, maskTo = studyArea, - writeTo = file.path(climatePathOut, paste0(fname, ".tif")), - useCache = FALSE, ## use internal cache for postProcessTo - overwrite = TRUE + writeTo = file.path(climatePathOut, paste0(fname, ".tif")) ) |> Cache( omitArgs = c("to", "maskTo", "overwrite"), # don't digest these each time @@ -517,3 +516,41 @@ prepClimateLayers <- function( } unique(types) } + +## GDAL creation options for the multi-layer climate stacks. A yearly layer is read on its own +## (one `year` layer out of ~90), which is slow if the layers are pixel-interleaved in +## 1-row strips (GDAL's default): every read decompresses all layers. Band-interleaved 256 x 256 +## tiles (GDAL's usual tile size: small enough that one layer touches few tiles, big enough to +## compress well) let a single layer be read without touching the others. +## Compression is left to terra's default (LZW), as before. +.climateStackGdalOptions <- c("INTERLEAVE=BAND", "TILED=YES", "BLOCKXSIZE=256", "BLOCKYSIZE=256") + +#' Post-process a climate raster and write it +#' +#' Same as `postProcessTo(writeTo = )`, except that stacks with more than one layer are written +#' with `.climateStackGdalOptions`. `reproducible::postProcessTo(writeTo = )` does not pass +#' `gdal` creation options on to `terra::writeRaster()`, so the write is done here. +#' @noRd +.postProcessAndWriteClimate <- function(from, to, maskTo, writeTo) { + out <- postProcessTo( + from = from, + to = to, + maskTo = maskTo, + useCache = FALSE, ## use internal cache for postProcessTo + overwrite = TRUE + ) + .writeClimateStack(out, writeTo) +} + +.writeClimateStack <- function(x, filename) { + if (file.exists(filename)) { + unlink(filename) + } + ## NUM_THREADS=1 as in reproducible::writeTo(): a default write leaves a GDAL thread pool + ## that makes a later fork() deadlock + gdal <- "NUM_THREADS=1" + if (terra::nlyr(x) > 1) { + gdal <- c(.climateStackGdalOptions, gdal) + } + terra::writeRaster(x, filename = filename, overwrite = TRUE, gdal = gdal) +} diff --git a/tests/testthat/test-writeClimateStack.R b/tests/testthat/test-writeClimateStack.R new file mode 100644 index 0000000..946e3f3 --- /dev/null +++ b/tests/testthat/test-writeClimateStack.R @@ -0,0 +1,62 @@ +test_that(".writeClimateStack writes band-interleaved tiles with identical values", { + skip_if_not_installed("terra") + r <- terra::rast(nrows = 300, ncols = 400, nlyrs = 6, xmin = 0, xmax = 400, ymin = 0, ymax = 300) + set.seed(1) + terra::values(r) <- round(stats::rnorm(terra::ncell(r) * 6, 100, 30), 1) + names(r) <- paste0("year", 2001:2006) + + oldFile <- withr::local_tempfile(fileext = ".tif") + newFile <- withr::local_tempfile(fileext = ".tif") + ## how the stacks were written before: terra default, pixel-interleaved 1-row strips + terra::writeRaster(r, oldFile, gdal = "INTERLEAVE=PIXEL", overwrite = TRUE) + expect_match( + sf::gdal_utils("info", oldFile, quiet = TRUE), + "INTERLEAVE=PIXEL" + ) + + out <- climateData:::.writeClimateStack(r, newFile) + info <- sf::gdal_utils("info", newFile, quiet = TRUE) + expect_match(info, "Block=256x256") + expect_match(info, "Block=256x256") + expect_match(info, "COMPRESSION=LZW") + + expect_identical(names(terra::rast(newFile)), names(r)) + expect_equal(terra::values(terra::rast(newFile)), terra::values(terra::rast(oldFile)), + tolerance = 0) + expect_equal(terra::values(out), terra::values(terra::rast(oldFile)), tolerance = 0) + ## one layer on its own is the same too + expect_equal(terra::values(terra::rast(newFile, lyrs = "year2004")), + terra::values(terra::rast(oldFile, lyrs = "year2004")), tolerance = 0) + + ## a single layer is not given tiling + oneFile <- withr::local_tempfile(fileext = ".tif") + climateData:::.writeClimateStack(r[[1]], oneFile) + expect_no_match(sf::gdal_utils("info", oneFile, quiet = TRUE), "Block=256x256") + + ## overwriting an existing file works + climateData:::.writeClimateStack(r, newFile) + expect_equal(terra::nlyr(terra::rast(newFile)), 6L) +}) + +test_that(".postProcessAndWriteClimate gives the same layers as postProcessTo(writeTo =)", { + skip_if_not_installed("terra") + skip_if_not_installed("reproducible") + r <- terra::rast(nrows = 120, ncols = 160, nlyrs = 4, xmin = 0, xmax = 160, ymin = 0, ymax = 120, + crs = "EPSG:3857") + set.seed(2) + terra::values(r) <- round(stats::rnorm(terra::ncell(r) * 4, 50, 10), 2) + names(r) <- paste0("year", 2001:2004) + to <- terra::rast(terra::ext(20, 120, 10, 90), res = 2, crs = "EPSG:3857") + mask <- terra::as.polygons(terra::ext(30, 100, 20, 80), crs = "EPSG:3857") + + oldFile <- withr::local_tempfile(fileext = ".tif") + newFile <- withr::local_tempfile(fileext = ".tif") + old <- reproducible::postProcessTo(r, to = to, maskTo = mask, writeTo = oldFile, + useCache = FALSE, overwrite = TRUE) + new <- climateData:::.postProcessAndWriteClimate(r, to = to, maskTo = mask, writeTo = newFile) + expect_equal(terra::values(new), terra::values(old), tolerance = 0) + expect_identical(names(new), names(old)) + expect_equal(terra::values(terra::rast(newFile)), terra::values(terra::rast(oldFile)), + tolerance = 0) + expect_match(sf::gdal_utils("info", newFile, quiet = TRUE), "Block=256x256") +}) From 5fb6049585f0664a7dd3744928e84fed7c0d8c69 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 30 Sep 2026 19:12:17 -0700 Subject: [PATCH 2/3] prepClimateLayers: pass stack creation options through postProcessTo(gdal = ) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CwcjqqK59FmTJscyi7xUqv --- NEWS.md | 2 +- R/prepClimateLayers.R | 37 ++----------- tests/testthat/test-writeClimateStack.R | 70 +++++++++---------------- 3 files changed, 31 insertions(+), 78 deletions(-) diff --git a/NEWS.md b/NEWS.md index 55fd74f..df28afe 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # climateData (development version) -- `prepClimateLayers()` now writes multi-layer climate stacks band-interleaved in 256 x 256 tiles (`INTERLEAVE=BAND`, `TILED=YES`) instead of pixel-interleaved 1-row strips, so reading one year's layer no longer decompresses every layer in the file (about 8.8 s down to 0.14 s for a 90-layer stack). Values are unchanged. The creation options are part of the cache key, so existing stacks are rebuilt the next time `prepClimateLayers()` runs. +- `prepClimateLayers()` now writes multi-layer climate stacks band-interleaved in 256 x 256 tiles (`INTERLEAVE=BAND`, `TILED=YES`) through `postProcessTo(writeTo = , gdal = )`, instead of pixel-interleaved 1-row strips, so reading one year's layer no longer decompresses every layer in the file (about 8.8 s down to 0.14 s for a 90-layer stack). Values are unchanged. This needs a `reproducible` in which `writeTo()` honours `gdal` (older versions ignore it and write the old layout). The creation options are part of the cache key, so existing stacks are rebuilt the next time `prepClimateLayers()` runs. - When a seasonal variable is needed, monthly and yearly variables now come from the same MSY ("all") archive, which contains all their files. Before, they were also downloaded from their own M and Y archives unless M, S and Y were all needed. Some M archives on the server are incomplete (tile 46's future 2080s diff --git a/R/prepClimateLayers.R b/R/prepClimateLayers.R index 7178f93..28de8c2 100644 --- a/R/prepClimateLayers.R +++ b/R/prepClimateLayers.R @@ -480,11 +480,14 @@ prepClimateLayers <- function( var <- stringr::str_remove(nm, paste0(type, "_")) fname <- paste(var, type, studyAreaName, sep = "_") climRast <- - .postProcessAndWriteClimate( + postProcessTo( from = newClimRast, to = rasterToMatch, maskTo = studyArea, - writeTo = file.path(climatePathOut, paste0(fname, ".tif")) + writeTo = file.path(climatePathOut, paste0(fname, ".tif")), + gdal = if (terra::nlyr(newClimRast) > 1) .climateStackGdalOptions, ## needs reproducible >= the version with `writeTo(gdal = )` + useCache = FALSE, ## use internal cache for postProcessTo + overwrite = TRUE ) |> Cache( omitArgs = c("to", "maskTo", "overwrite"), # don't digest these each time @@ -524,33 +527,3 @@ prepClimateLayers <- function( ## compress well) let a single layer be read without touching the others. ## Compression is left to terra's default (LZW), as before. .climateStackGdalOptions <- c("INTERLEAVE=BAND", "TILED=YES", "BLOCKXSIZE=256", "BLOCKYSIZE=256") - -#' Post-process a climate raster and write it -#' -#' Same as `postProcessTo(writeTo = )`, except that stacks with more than one layer are written -#' with `.climateStackGdalOptions`. `reproducible::postProcessTo(writeTo = )` does not pass -#' `gdal` creation options on to `terra::writeRaster()`, so the write is done here. -#' @noRd -.postProcessAndWriteClimate <- function(from, to, maskTo, writeTo) { - out <- postProcessTo( - from = from, - to = to, - maskTo = maskTo, - useCache = FALSE, ## use internal cache for postProcessTo - overwrite = TRUE - ) - .writeClimateStack(out, writeTo) -} - -.writeClimateStack <- function(x, filename) { - if (file.exists(filename)) { - unlink(filename) - } - ## NUM_THREADS=1 as in reproducible::writeTo(): a default write leaves a GDAL thread pool - ## that makes a later fork() deadlock - gdal <- "NUM_THREADS=1" - if (terra::nlyr(x) > 1) { - gdal <- c(.climateStackGdalOptions, gdal) - } - terra::writeRaster(x, filename = filename, overwrite = TRUE, gdal = gdal) -} diff --git a/tests/testthat/test-writeClimateStack.R b/tests/testthat/test-writeClimateStack.R index 946e3f3..2ac03f9 100644 --- a/tests/testthat/test-writeClimateStack.R +++ b/tests/testthat/test-writeClimateStack.R @@ -1,62 +1,42 @@ -test_that(".writeClimateStack writes band-interleaved tiles with identical values", { +## needs the `reproducible` version in which `writeTo()` honours `gdal` +test_that("postProcessTo(writeTo, gdal = .climateStackGdalOptions) writes band-interleaved tiles with identical values", { skip_if_not_installed("terra") - r <- terra::rast(nrows = 300, ncols = 400, nlyrs = 6, xmin = 0, xmax = 400, ymin = 0, ymax = 300) + skip_if_not_installed("sf") + skip_if_not_installed("withr") + ## skip with a `reproducible` whose writeTo() ignores `gdal` + probe <- withr::local_tempfile(fileext = ".tif") + p <- terra::rast(nrows = 300, ncols = 400, nlyrs = 2, vals = 1) + reproducible::postProcessTo(p, writeTo = probe, gdal = "TILED=YES", useCache = FALSE) + skip_if_not(grepl("Block=256x256", sf::gdal_utils("info", probe, quiet = TRUE)), + "reproducible::writeTo() ignores `gdal`") + + r <- terra::rast(nrows = 300, ncols = 400, nlyrs = 6, xmin = 0, xmax = 400, ymin = 0, ymax = 300, + crs = "EPSG:3857") set.seed(1) terra::values(r) <- round(stats::rnorm(terra::ncell(r) * 6, 100, 30), 1) names(r) <- paste0("year", 2001:2006) + to <- terra::rast(terra::ext(20, 380, 10, 280), resolution = 1, crs = "EPSG:3857") + mask <- terra::as.polygons(terra::ext(30, 300, 20, 250), crs = "EPSG:3857") oldFile <- withr::local_tempfile(fileext = ".tif") newFile <- withr::local_tempfile(fileext = ".tif") - ## how the stacks were written before: terra default, pixel-interleaved 1-row strips - terra::writeRaster(r, oldFile, gdal = "INTERLEAVE=PIXEL", overwrite = TRUE) - expect_match( - sf::gdal_utils("info", oldFile, quiet = TRUE), - "INTERLEAVE=PIXEL" - ) - - out <- climateData:::.writeClimateStack(r, newFile) + ## how the stacks were written before: no creation options + old <- reproducible::postProcessTo(r, to = to, maskTo = mask, writeTo = oldFile, + useCache = FALSE, overwrite = TRUE) + new <- reproducible::postProcessTo(r, to = to, maskTo = mask, writeTo = newFile, + gdal = climateData:::.climateStackGdalOptions, + useCache = FALSE, overwrite = TRUE) + expect_match(sf::gdal_utils("info", oldFile, quiet = TRUE), "INTERLEAVE=PIXEL") info <- sf::gdal_utils("info", newFile, quiet = TRUE) - expect_match(info, "Block=256x256") + expect_match(info, "INTERLEAVE=BAND") expect_match(info, "Block=256x256") expect_match(info, "COMPRESSION=LZW") - expect_identical(names(terra::rast(newFile)), names(r)) + expect_identical(names(terra::rast(newFile)), names(terra::rast(oldFile))) expect_equal(terra::values(terra::rast(newFile)), terra::values(terra::rast(oldFile)), tolerance = 0) - expect_equal(terra::values(out), terra::values(terra::rast(oldFile)), tolerance = 0) + expect_equal(terra::values(new), terra::values(old), tolerance = 0) ## one layer on its own is the same too expect_equal(terra::values(terra::rast(newFile, lyrs = "year2004")), terra::values(terra::rast(oldFile, lyrs = "year2004")), tolerance = 0) - - ## a single layer is not given tiling - oneFile <- withr::local_tempfile(fileext = ".tif") - climateData:::.writeClimateStack(r[[1]], oneFile) - expect_no_match(sf::gdal_utils("info", oneFile, quiet = TRUE), "Block=256x256") - - ## overwriting an existing file works - climateData:::.writeClimateStack(r, newFile) - expect_equal(terra::nlyr(terra::rast(newFile)), 6L) -}) - -test_that(".postProcessAndWriteClimate gives the same layers as postProcessTo(writeTo =)", { - skip_if_not_installed("terra") - skip_if_not_installed("reproducible") - r <- terra::rast(nrows = 120, ncols = 160, nlyrs = 4, xmin = 0, xmax = 160, ymin = 0, ymax = 120, - crs = "EPSG:3857") - set.seed(2) - terra::values(r) <- round(stats::rnorm(terra::ncell(r) * 4, 50, 10), 2) - names(r) <- paste0("year", 2001:2004) - to <- terra::rast(terra::ext(20, 120, 10, 90), res = 2, crs = "EPSG:3857") - mask <- terra::as.polygons(terra::ext(30, 100, 20, 80), crs = "EPSG:3857") - - oldFile <- withr::local_tempfile(fileext = ".tif") - newFile <- withr::local_tempfile(fileext = ".tif") - old <- reproducible::postProcessTo(r, to = to, maskTo = mask, writeTo = oldFile, - useCache = FALSE, overwrite = TRUE) - new <- climateData:::.postProcessAndWriteClimate(r, to = to, maskTo = mask, writeTo = newFile) - expect_equal(terra::values(new), terra::values(old), tolerance = 0) - expect_identical(names(new), names(old)) - expect_equal(terra::values(terra::rast(newFile)), terra::values(terra::rast(oldFile)), - tolerance = 0) - expect_match(sf::gdal_utils("info", newFile, quiet = TRUE), "Block=256x256") }) From e7f2b01875d4374bf8c938ef10cc8a82c8049c51 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 30 Sep 2026 21:13:01 -0700 Subject: [PATCH 3/3] Imports reproducible (>= 3.2.1.9057), where writeTo() honours gdal; drop the test's skip-if-ignored probe Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CwcjqqK59FmTJscyi7xUqv --- DESCRIPTION | 2 +- tests/testthat/test-writeClimateStack.R | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 1a9e461..38e5daf 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -30,7 +30,7 @@ Imports: parallel, parallelly, purrr, - reproducible (>= 2.0.8), + reproducible (>= 3.2.1.9057), RSQLite, sf, stats, diff --git a/tests/testthat/test-writeClimateStack.R b/tests/testthat/test-writeClimateStack.R index 2ac03f9..ec742f4 100644 --- a/tests/testthat/test-writeClimateStack.R +++ b/tests/testthat/test-writeClimateStack.R @@ -1,15 +1,8 @@ -## needs the `reproducible` version in which `writeTo()` honours `gdal` +## needs reproducible (>= 3.2.1.9057), in which `writeTo()` honours `gdal` (DESCRIPTION Imports) test_that("postProcessTo(writeTo, gdal = .climateStackGdalOptions) writes band-interleaved tiles with identical values", { skip_if_not_installed("terra") skip_if_not_installed("sf") skip_if_not_installed("withr") - ## skip with a `reproducible` whose writeTo() ignores `gdal` - probe <- withr::local_tempfile(fileext = ".tif") - p <- terra::rast(nrows = 300, ncols = 400, nlyrs = 2, vals = 1) - reproducible::postProcessTo(p, writeTo = probe, gdal = "TILED=YES", useCache = FALSE) - skip_if_not(grepl("Block=256x256", sf::gdal_utils("info", probe, quiet = TRUE)), - "reproducible::writeTo() ignores `gdal`") - r <- terra::rast(nrows = 300, ncols = 400, nlyrs = 6, xmin = 0, xmax = 400, ymin = 0, ymax = 300, crs = "EPSG:3857") set.seed(1)