diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 5f5d776..b16718b 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -10,9 +10,9 @@ name: R-CMD-check on: push: - branches: [main, master, development] + branches: [main, master, development, modsForFireSense] pull_request: - branches: [main, master, development] + branches: [main, master, development, modsForFireSense] jobs: R-CMD-check: diff --git a/DESCRIPTION b/DESCRIPTION index d135c4f..81155a7 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -32,7 +32,7 @@ Imports: parallel, parallelly, purrr, - reproducible (>= 2.0.8), + reproducible (>= 3.2.1.9057), RSQLite, sf, stats, diff --git a/NAMESPACE b/NAMESPACE index 6e41c4c..6d05f52 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -12,8 +12,10 @@ export(calcCumMDC) export(calcMDC) export(calcStackLayersType) export(checkCalcStackLayers) +export(checkCalendarYears) export(checksums_sql) export(climateLayers) +export(climateStackGdalOptions) export(climateStacksByPeriod) export(climateStacksByYear) export(extractTimes) diff --git a/NEWS.md b/NEWS.md index f2fc9a9..e164b5f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # climateData (development version) +- `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. +- New exported `checkCalendarYears(start, end, module, hint, years)`: stops with a message saying what to set when a run's start is not a calendar year the climate data cover (1901 to 2100, from `available()`, or the range of `years` when given). For modules such as canClimateData and climateYear, to fail early on model-year times (0-10, as `setupProject()` gives without `times`). +- `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. Needs reproducible >= 3.2.1.9057, in which `writeTo()` honours `gdal`. The options are an argument of the cached `postProcessTo()` call, so existing multi-layer stacks are rebuilt the next time `prepClimateLayers()` runs. New exported `climateStackGdalOptions()` returns them, for code that rewrites the stacks or caches `prepClimateLayers()` (e.g., canClimateData). - `latestHistoricalYear()` and the tile lookup in `ClimateNA_useTiles()` open the bundled tile index read-only and set the SQLite busy timeout before any other statement. Before, many processes opening it together (e.g. parallel hindcast jobs parsing fireSense modules on NFS) could fail with "database is locked". diff --git a/R/checkCalendarYears.R b/R/checkCalendarYears.R new file mode 100644 index 0000000..aeee7c8 --- /dev/null +++ b/R/checkCalendarYears.R @@ -0,0 +1,31 @@ +#' Check that a run's times are calendar years the climate data can serve +#' +#' Climate data are by calendar year, from the first historical year to the last projected year +#' that [available()] reports (1901 to 2100). A run whose start is outside that span, such as +#' the model years 0-10 that `SpaDES.project::setupProject()` gives when `times` is not set, +#' cannot be matched to any climate year. A run may end after the last year. +#' +#' @param start,end Start and end times of the simulation. +#' @param years Optional years the caller will load (e.g. a module's climate-year parameters); the span is then +#' their range instead of the span [available()] reports. +#' @param module Name of the calling module, for the message. +#' @param hint Optional text added to the end of the message, saying how to proceed. +#' +#' @return `NULL`, invisibly; an error if `start` is outside the span of the climate data. +#' +#' @export +#' +#' @examples +#' checkCalendarYears(2020, 2120, module = "myModule") +checkCalendarYears <- function(start, end, module = "this module", hint = NULL, years = NULL) { + if (is.null(years)) { + years <- unlist(lapply(c("historical", "future"), function(type) available(type)[["years"]])) + } + span <- range(years) + if (start < span[1] || start > span[2]) { + stop(module, ": times are model years ", start, "-", end, "; this module needs calendar years ", + "(the climate data cover ", span[1], "-", span[2], ", so `start` must be in that range), ", + "e.g. times = list(start = 2020, end = 2120). ", hint, call. = FALSE) + } + invisible(NULL) +} diff --git a/R/prepClimateLayers.R b/R/prepClimateLayers.R index e2884e2..878159e 100644 --- a/R/prepClimateLayers.R +++ b/R/prepClimateLayers.R @@ -525,6 +525,7 @@ prepClimateLayers <- function( to = rasterToMatch, maskTo = studyArea, writeTo = file.path(climatePathOut, paste0(fname, ".tif")), + gdal = if (terra::nlyr(newClimRast) > 1) climateStackGdalOptions(), ## an argument, so in the Cache() key useCache = FALSE, ## use internal cache for postProcessTo overwrite = TRUE ) |> @@ -558,3 +559,23 @@ 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). +#' +#' `prepClimateLayers()` writes its multi-layer stacks with these options. Code that rewrites +#' those stacks, or caches a call to `prepClimateLayers()`, can use them too: add the value to +#' the cache key (e.g., `.cacheExtra`), because `Cache()` digests a function's source, not the +#' values it refers to. +#' +#' @return character vector of GDAL creation options, for `terra::writeRaster(gdal = )` or +#' `reproducible::postProcessTo(gdal = )`. +#' @export +climateStackGdalOptions <- function() { + c("INTERLEAVE=BAND", "TILED=YES", "BLOCKXSIZE=256", "BLOCKYSIZE=256") +} diff --git a/man/checkCalendarYears.Rd b/man/checkCalendarYears.Rd new file mode 100644 index 0000000..6355ade --- /dev/null +++ b/man/checkCalendarYears.Rd @@ -0,0 +1,36 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/checkCalendarYears.R +\name{checkCalendarYears} +\alias{checkCalendarYears} +\title{Check that a run's times are calendar years the climate data can serve} +\usage{ +checkCalendarYears( + start, + end, + module = "this module", + hint = NULL, + years = NULL +) +} +\arguments{ +\item{start, end}{Start and end times of the simulation.} + +\item{module}{Name of the calling module, for the message.} + +\item{hint}{Optional text added to the end of the message, saying how to proceed.} + +\item{years}{Optional years the caller will load (e.g. a module's climate-year parameters); the span is then +their range instead of the span \code{\link[=available]{available()}} reports.} +} +\value{ +\code{NULL}, invisibly; an error if \code{start} is outside the span of the climate data. +} +\description{ +Climate data are by calendar year, from the first historical year to the last projected year +that \code{\link[=available]{available()}} reports (1901 to 2100). A run whose start is outside that span, such as +the model years 0-10 that \code{SpaDES.project::setupProject()} gives when \code{times} is not set, +cannot be matched to any climate year. A run may end after the last year. +} +\examples{ +checkCalendarYears(2020, 2120, module = "myModule") +} diff --git a/man/climateStackGdalOptions.Rd b/man/climateStackGdalOptions.Rd new file mode 100644 index 0000000..0883bad --- /dev/null +++ b/man/climateStackGdalOptions.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/prepClimateLayers.R +\name{climateStackGdalOptions} +\alias{climateStackGdalOptions} +\title{GDAL creation options for the multi-layer climate stacks} +\usage{ +climateStackGdalOptions() +} +\value{ +character vector of GDAL creation options, for \code{terra::writeRaster(gdal = )} or +\code{reproducible::postProcessTo(gdal = )}. +} +\description{ +A yearly layer is read on its own (one \verb{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). +} +\details{ +\code{prepClimateLayers()} writes its multi-layer stacks with these options. Code that rewrites +those stacks, or caches a call to \code{prepClimateLayers()}, can use them too: add the value to +the cache key (e.g., \code{.cacheExtra}), because \code{Cache()} digests a function's source, not the +values it refers to. +} diff --git a/tests/testthat/test-checkCalendarYears.R b/tests/testthat/test-checkCalendarYears.R new file mode 100644 index 0000000..eb99552 --- /dev/null +++ b/tests/testthat/test-checkCalendarYears.R @@ -0,0 +1,27 @@ +test_that("a start inside the span of the climate data is accepted", { + expect_silent(checkCalendarYears(2020, 2120, module = "m")) + expect_silent(checkCalendarYears(1901, 1950, module = "m")) + expect_silent(checkCalendarYears(2100, 2100, module = "m")) + expect_silent(checkCalendarYears(1985.5, 2020, module = "m")) +}) + +test_that("the span is the one available() reports", { + yrs <- range(unlist(lapply(c("historical", "future"), function(t) available(t)[["years"]]))) + expect_error(checkCalendarYears(yrs[1] - 1, 2000, module = "m"), as.character(yrs[1])) + expect_error(checkCalendarYears(yrs[2] + 1, 2200, module = "m"), as.character(yrs[2])) +}) + +test_that("model-year times fail with the module, both times and an example", { + expect_error(checkCalendarYears(0, 10, module = "canClimateData"), + "canClimateData: times are model years 0-10.*calendar years.*times = list\\(start = 2020, end = 2120\\)") +}) + +test_that("a hint is appended to the message", { + expect_error(checkCalendarYears(0, 10, module = "m", hint = "Do this instead."), "Do this instead\\.") +}) + +test_that("`years` replaces the span of available()", { + expect_silent(checkCalendarYears(1995, 2050, module = "m", years = 1991:2100)) + expect_error(checkCalendarYears(1950, 2050, module = "m", years = 1991:2100), "1991-2100") + expect_error(checkCalendarYears(2101, 2200, module = "m", years = 1991:2100), "1991-2100") +}) diff --git a/tests/testthat/test-writeClimateStack.R b/tests/testthat/test-writeClimateStack.R new file mode 100644 index 0000000..7d5eaa3 --- /dev/null +++ b/tests/testthat/test-writeClimateStack.R @@ -0,0 +1,35 @@ +## 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") + 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: 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 = 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, "INTERLEAVE=BAND") + expect_match(info, "Block=256x256") + expect_match(info, "COMPRESSION=LZW") + + 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(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) +})