diff --git a/.github/workflows/render-module-rmd.yaml b/.github/workflows/render-module-rmd.yaml index 5c27f8e..ce7819d 100644 --- a/.github/workflows/render-module-rmd.yaml +++ b/.github/workflows/render-module-rmd.yaml @@ -13,11 +13,13 @@ on: - main - master - development + - modsForFireSense push: branches: - main - master - development + - modsForFireSense paths: - .github/workflows/render-module-rmd.yaml - canClimateData.Rmd diff --git a/.github/workflows/testthat-module.yaml b/.github/workflows/testthat-module.yaml index 05f5653..235c469 100644 --- a/.github/workflows/testthat-module.yaml +++ b/.github/workflows/testthat-module.yaml @@ -5,9 +5,9 @@ name: testthat-module on: pull_request: - branches: [main, master, development] + branches: [main, master, development, modsForFireSense] push: - branches: [main, master, development] + branches: [main, master, development, modsForFireSense] paths: - .github/workflows/testthat-module.yaml - canClimateData.R diff --git a/NEWS.md b/NEWS.md index 3769584..e66ca96 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,12 @@ # canClimateData (development version) +- Requires SpaDES.core >= 3.2.1.9070. A rerun reads the years it serves from `inputs(sim)$loadTime`; before SpaDES.core #527 the rows of objects passed to `simInit(objects = )` held seconds (e.g. 85836672000 for 2720), so the rerun asked the record for years it does not have. +- `outputDir` may be a `reproducible::asPath(dir, nParentDirs)`: the event cache keys then hold only the last `nParentDirs + 1` components of the folder, so a cache built on one machine matches on another where the folder has a different prefix, while a different folder (e.g. another hindcast) still gives a different key. A plain path is keyed in full, as before. Nothing in the module changed; the parameter description says how to pass it. +- Rerunning this module on a finished run whose years are not calendar years (NRV), with that run's `climateYearRecord` (from the climateYear module), now prepares the climate years the record holds for the simulation years the rerun serves (the load times of its inputs, `inputs(sim)`, which `alreadyRun` sets to the finished run's save times), not the years in `climateVariables` or `historicalClimateYears`/`projectedClimateYears`. Variables by period, and `calcCumMDC` ones (which need consecutive years), keep their years. `times` are not checked as calendar years then. `climateYearRecord` is a new optional input; in a normal run climateYear writes it after this module's `init`, and `loadOrder` keeps that order. +- `climateData` is now required from its modsForFireSense branch (>= 2.2.3.9011). `checkCalendarYears()` is only there; climateData development reached 2.2.3.9011 without it, so the old floor installed a climateData whose `init` failed with "could not find function". +- `projectedClimateYears` now defaults to 2017:2100 instead of 2011:2100. The projected archive for tile 39 (CNRM-ESM2-1 ssp370) has no 2013-2016 files, and observed climate now covers 1901-2024, so projections before 2017 are not needed. +- `init` now stops, before preparing any climate data, when the run's start is outside the climate years this module is asked for (`historicalClimateYears` and `projectedClimateYears`, 1991 to 2100 by default), for example the model years 0-10 that `setupProject()` gives without `times`. With a supplied `climateVariables`, whose years are not known here, it stops when the start is not a calendar year from 1901 to 2100. The check is `climateData::checkCalendarYears()` (climateData >= 2.2.3.9009); the message says how to proceed. The run may end after the last year. + # canClimateData 1.1.1 - Fixed: `projectedType = "hindcast"` failed in `Init()` with "object 'projected_yrs' not found", diff --git a/canClimateData.R b/canClimateData.R index 1b3bca5..00511d8 100644 --- a/canClimateData.R +++ b/canClimateData.R @@ -12,19 +12,20 @@ defineModule(sim, list( person("Tati", "Micheletti", email = "tati.micheletti@gmail.com", role = "ctb") ), childModules = character(0), - version = list(canClimateData = "1.1.1.9000"), + version = list(canClimateData = "1.1.1.9002"), timeframe = as.POSIXlt(c(NA, NA)), timeunit = "year", citation = list("citation.bib"), documentation = deparse(list("README.md", "canClimateData.Rmd")), + loadOrder = list(before = "climateYear"), reqdPkgs = list("archive", "digest", "geodata", "googledrive", "httr2", "purrr", "R.utils", "sf", "spatialEco", "terra", "dbplyr", # needed for prepClimateLayers - "PredictiveEcology/climateData@development (>= 2.2.3.9008)", + "PredictiveEcology/climateData@modsForFireSense (>= 2.2.3.9011)", "PredictiveEcology/fireSenseUtils@development (>= 0.0.5.9046)", "PredictiveEcology/LandR@development (>= 1.1.0.9064)", "PredictiveEcology/reproducible@development (>= 3.2.1.9060)", - "PredictiveEcology/SpaDES.core@development (>= 2.1.5)", + "PredictiveEcology/SpaDES.core@development (>= 3.2.1.9070)", "PredictiveEcology/SpaDES.tools@development (>= 2.0.4.9002)"), parameters = rbind( defineParameter("bufferDist", "numeric", 20000, NA, NA, @@ -47,13 +48,22 @@ defineModule(sim, list( "(e.g., when running multiple simulation replicates)", "to avoid multiple copies of the climate data.", "If not specified by the user, a subdirectory of the simulation output", - "directory will be used (i.e., `file.path(outputPath(sim), 'climate')`.")), + "directory will be used (i.e., `file.path(outputPath(sim), 'climate')`.", + "Event cache keys hold this value as given, so a different folder", + "is a different key, and a machine-specific prefix is part of it.", + "To let the same folder match on another machine, pass", + "`reproducible::asPath(dir, nParentDirs)`: the key then holds only", + "`dir`'s last `nParentDirs + 1` components, e.g.", + "`asPath(dir, 2)` for `//climate`.")), defineParameter("projectedClimatePeriod", "character", NULL, NA, NA, paste("period to use for projected climate normals", "if `climateVariables` not supplied.")), - defineParameter("projectedClimateYears", "numeric", 2011:2100, NA, NA, + defineParameter("projectedClimateYears", "numeric", 2017:2100, NA, NA, paste("range of years captured by the projected climate data", - "if `climateVariables` not supplied.")), + "if `climateVariables` not supplied.", + "Starts in 2017 because the projected archive for tile 39", + "(CNRM-ESM2-1 ssp370) lacks 2013-2016, and observed climate", + "now covers 1901-2024, so earlier projections are not needed.")), defineParameter("projectedType", "character", "forecast", NA, NA, paste("one of 'forecast' or 'hindcast' to prepare either projected future,", "or sampled historical data for hindcast studies, respectively.")), @@ -91,6 +101,14 @@ defineModule(sim, list( "are set by module parameters and must be identical for all variables.", "See also for all available climate variables."), sourceURL = NA), + expectsInput("climateYearRecord", "data.table", + desc = paste("Optional, for rerunning this module on a finished run whose simulation years", + "are not calendar years (e.g. NRV): that run's record (`simYear`, `climateYear`)", + "of the climate year used in each simulation year, from the `climateYear` module.", + "When supplied, those climate years, not `times`, are checked against the years", + "this module prepares. In a normal run `climateYear` writes it after this", + "module's `init`, so it is not read."), + sourceURL = NA), expectsInput("rasterToMatch", "SpatRaster", desc = "template raster corresponding to `studyArea`.", sourceURL = NA), expectsInput("studyArea", "sf", @@ -142,6 +160,35 @@ climateRastersToRewrite <- function(projectedType, if (identical(projectedType, "hindcast")) "projected" else character(0) } +## The simulation years a rerun serves: the load times of its inputs (`inputs(sim)`; `alreadyRun` +## loads each saved output of the finished run at its save time) within `start`-`end`; all of +## `start`-`end` if there are none. +rerunSimYears <- function(inputs, start, end) { + lt <- as.numeric(inputs$loadTime) + yrs <- sort(unique(floor(lt[!is.na(lt) & lt >= start & lt <= end]))) + if (length(yrs)) yrs else seq(floor(start), floor(end)) +} + +## `climateVariables` with the years of each element replaced by the climate years `record` +## (`simYear`, `climateYear`) holds for `simYears`: historical up to the latest historical year, +## projected after. Elements by period (normals) are left alone, and so are those whose `fun` needs +## consecutive years from their own first year (`calcCumMDC`: each year starts from the previous +## October's drought code), whose values would otherwise differ from the finished run's. +climateVarsForRecord <- function(climateVariables, record, simYears) { + missingYrs <- setdiff(simYears, record$simYear) + if (length(missingYrs)) + stop("canClimateData: `climateYearRecord` has no climate year for simulation year(s) ", + paste(missingYrs, collapse = ", "), call. = FALSE) + climYrs <- sort(unique(record$climateYear[record$simYear %in% simYears])) + latest <- latestHistoricalYear() + lapply(climateVariables, function(v) { + if (identical(v$fun, quote(calcCumMDC))) return(v) + if (!is.null(v$.dots$historical_years)) v$.dots$historical_years <- climYrs[climYrs <= latest] + if (!is.null(v$.dots$future_years)) v$.dots$future_years <- climYrs[climYrs > latest] + v + }) +} + ## Write each raster to a new file so the file carries the updated layer names. ## Multi-layer stacks are written band-interleaved in 256 x 256 tiles, the layout climateData#33 ## proposes for climateData::prepClimateLayers() (its `climateStackGdalOptions()`), so reading one @@ -157,6 +204,29 @@ writeUpdatedLayerNames <- function(rasters, } Init <- function(sim) { + ## A rerun of a finished run in model years (NRV) supplies that run's `climateYearRecord`: the + ## climate years that run used at the times its outputs are loaded here, and only those, are + ## prepared, whatever years `climateVariables` names. In a normal run the record does not exist yet + ## here (`climateYear` writes it, after this `init`; see `loadOrder`), so it is not read. + climateVars <- sim$climateVariables + rec <- sim$climateYearRecord + if (NROW(rec)) { + climateVars <- climateVarsForRecord(climateVars, rec, rerunSimYears(inputs(sim), start(sim), end(sim))) + } else { + ## When this module builds `climateVariables` it fetches `historicalClimateYears` and + ## `projectedClimateYears`, so the run's start must fall within those. A supplied + ## `climateVariables` has years this module cannot read, so only calendar years are required. + ## (`.inputObjects` sets the flag; it does not run when every input was supplied.) + fromParams <- isTRUE(mod$climateVariablesFromParams) + checkCalendarYears(start(sim), end(sim), module = "canClimateData", + years = if (fromParams) + c(P(sim)$historicalClimateYears, P(sim)$projectedClimateYears), + hint = if (fromParams) { + "Set `times` inside those years, or change `historicalClimateYears`/`projectedClimateYears`." + } else { + "`climateVariables` was supplied, so its years are not known here: set `times` to calendar years." + }) + } stopifnot(P(sim)$projectedType %in% c("forecast", "hindcast")) ## separate intermediate outputs from raw inputs, to reduce file conflicts on shared drives @@ -201,7 +271,7 @@ Init <- function(sim) { SSP <- P(sim)$climateSSP climateRasters <- prepClimateLayers( - climateVarsList = sim$climateVariables, + climateVarsList = climateVars, srcdir = climatePath, ## 'src' is the place for raw inputs, downloaded from Google Drive dstdir = climatePathOut, ## 'dst' is the place for intermediate + final outputs gcm = GCM, @@ -315,7 +385,8 @@ sampleHindcastLayers <- function(rasters, years) { datatype = "INT1U", overwrite = TRUE) } - if (!suppliedElsewhere("climateVariables", sim)) { + mod$climateVariablesFromParams <- !suppliedElsewhere("climateVariables", sim) + if (mod$climateVariablesFromParams) { historical_prd <- P(sim)$historicalClimatePeriod historical_yrs <- P(sim)$historicalClimateYears projected_yrs <- P(sim)$projectedClimateYears diff --git a/canClimateData.md b/canClimateData.md index 5e53258..3bce21d 100644 --- a/canClimateData.md +++ b/canClimateData.md @@ -1,7 +1,7 @@ --- title: "canClimateData Manual" -subtitle: "v.1.1.1.9000" -date: "Last updated: 2026-11-05" +subtitle: "v.1.1.1.9001" +date: "Last updated: 2026-11-16" output: bookdown::html_document2: toc: true @@ -127,6 +127,12 @@ See `?climateData::prepClimateLayers` for examples constructing a custom `climat a list, named by climate variable using `'projected_'` or `'historical_'` prefixes, with each list element containing a list of three arguments: `vars` - the raw variables used to derive the target variable; `fun` - the quoted function used to derive the target variable, where `'quote(calcAsIs)'` denotes target variables that ARE the raw variable; and `dots` - additional arguments passed to `fun`. See `.inputObjects` for examples of how to build this object, and `?climateData::prepClimateLayers` for how it is used. The GCM, SSP, and selected years, whether projected or historical, are set by module parameters and must be identical for all variables. See also <https://climatena.ca/Help2#_var> for all available climate variables. NA + + climateYearRecord + data.table + Optional, for rerunning this module on a finished run whose simulation years are not calendar years (e.g. NRV): that run's record (`simYear`, `climateYear`) of the climate year used in each simulation year, from the `climateYear` module. When supplied, those climate years, not `times`, are checked against the years this module prepares. In a normal run `climateYear` writes it after this module's `init`, so it is not read. + NA + rasterToMatch SpatRaster @@ -212,7 +218,7 @@ Table \@ref(tab:moduleParams-canClimateData) shows the full list of module param NA NA NA - Directory path for prepared climate data rasters. User should specify a shared directory (e.g., when running multiple simulation replicates) to avoid multiple copies of the climate data. If not specified by the user, a subdirectory of the simulation output directory will be used (i.e., `file.path(outputPath(sim), 'climate')`. + Directory path for prepared climate data rasters. User should specify a shared directory (e.g., when running multiple simulation replicates) to avoid multiple copies of the climate data. If not specified by the user, a subdirectory of the simulation output directory will be used (i.e., `file.path(outputPath(sim), 'climate')`. Event cache keys hold this value as given, so a different folder is a different key, and a machine-specific prefix is part of it. To let the same folder match on another machine, pass `reproducible::asPath(dir, nParentDirs)`: the key then holds only `dir`'s last `nParentDirs + 1` components, e.g. `asPath(dir, 2)` for `<hindcast>/<ELF>/climate`. TRUE @@ -227,10 +233,10 @@ Table \@ref(tab:moduleParams-canClimateData) shows the full list of module param projectedClimateYears numeric - 2011, 20.... + 2017, 20.... NA NA - range of years captured by the projected climate data if `climateVariables` not supplied. + range of years captured by the projected climate data if `climateVariables` not supplied. Starts in 2017 because the projected archive for tile 39 (CNRM-ESM2-1 ssp370) lacks 2013-2016, and observed climate now covers 1901-2024, so earlier projections are not needed. TRUE diff --git a/tests/testthat/helper-module.R b/tests/testthat/helper-module.R index 992fbdb..774af97 100644 --- a/tests/testthat/helper-module.R +++ b/tests/testthat/helper-module.R @@ -11,6 +11,7 @@ rm(e) ## a real run gets these from the module's reqdPkgs Cache <- reproducible::Cache .suffix <- reproducible::.suffix +checkCalendarYears <- climateData::checkCalendarYears ## Run the module's real Init() on small file-backed rasters, with stand-ins for the SpaDES accessors ## and for climateData::prepClimateLayers(). The stand-in layer names end in the year or period, as @@ -28,6 +29,8 @@ runInit <- function(path, projectedType = "forecast", params = list(), calls = n mocks <- new.env(parent = environment(Init)) mocks$P <- function(sim, ...) sim$params mocks$inputPath <- mocks$outputPath <- function(sim) path + mocks$start <- function(sim) 2011 + mocks$end <- function(sim) 2012 mocks$checkPath <- function(path, create = FALSE) { dir.create(path, recursive = TRUE, showWarnings = FALSE) path diff --git a/tests/testthat/test-calendarYears.R b/tests/testthat/test-calendarYears.R new file mode 100644 index 0000000..f408c05 --- /dev/null +++ b/tests/testthat/test-calendarYears.R @@ -0,0 +1,66 @@ +## The climate data are by calendar year (see climateData::checkCalendarYears(), which has the rule +## and its unit tests), so a run whose times are model years (setupProject() without `times` gives +## 0 to 10) cannot be served. This module must stop before preparing any climate data. + +test_that("init stops, with a supplied climateVariables, on model-year times before touching any climate data", { + rtm <- terra::rast(nrows = 2, ncols = 2, vals = 1L, crs = "EPSG:3978") + sa <- sf::st_as_sf(terra::as.polygons(rtm)) + sim <- suppressMessages(SpaDES.core::simInit( + times = list(start = 0, end = 10), modules = moduleName, paths = testPaths, + objects = list(studyArea = sa, rasterToMatch = rtm, climateVariables = list(dummy = list())))) + expect_error(suppressMessages(SpaDES.core::spades(sim, debug = FALSE)), + "canClimateData: times are model years 0-10.*calendar years.*climateVariables. was supplied") +}) + +test_that("init stops when the run starts before the climate years this module is asked for", { + rtm <- terra::rast(nrows = 2, ncols = 2, vals = 1L, crs = "EPSG:3978") + sa <- sf::st_as_sf(terra::as.polygons(rtm)) + sim <- suppressMessages(SpaDES.core::simInit( + times = list(start = 1950, end = 2020), modules = moduleName, paths = testPaths, + params = list(canClimateData = list(historicalClimateYears = 1991:2022, projectedClimateYears = 2011:2100)), + objects = list(studyArea = sa, rasterToMatch = rtm))) + expect_error(suppressMessages(SpaDES.core::spades(sim, debug = FALSE)), + "times are model years 1950-2020.*cover 1991-2100.*historicalClimateYears") +}) + +test_that("a rerun serves the simulation years its inputs load at (inputs(sim)), within times", { + inp <- data.frame(objectName = c("a", "b", "a", "a", "a", "a"), + loadTime = c(2720, 2720, 2820, 2920, 3020, 3120)) + expect_identical(rerunSimYears(inp, 2720, 3020), c(2720, 2820, 2920, 3020)) + expect_identical(rerunSimYears(inp, 2720, 2720), 2720) + ## no inputs: every year of times + expect_equal(rerunSimYears(data.frame(loadTime = numeric(0)), 2720, 2722), c(2720, 2721, 2722)) +}) + +test_that("a rerun prepares only the climate years the record holds for those simulation years", { + latest <- climateData::latestHistoricalYear() + rec <- data.table::data.table(simYear = 2719:2821, + climateYear = c(1990, 2001, rep(1995, 99), 1987, latest + 5)) + cv <- list( + historical_CMD = list(vars = "historical_CMD", fun = quote(calcAsIs), .dots = list(historical_years = 1986:2024)), + historical_CMI_normal = list(vars = "historical_CMI_normal", fun = quote(calcAsIs), + .dots = list(historical_period = "1981_2010")), + historical_cumMDC = list(vars = "historical_PPT01", fun = quote(calcCumMDC), .dots = list(historical_years = 1981:2024)), + projected_MDC = list(vars = "future_PPT04", fun = quote(calcMDC), .dots = list(future_years = 2017:2100))) + out <- climateVarsForRecord(cv, rec, c(2720, 2820, 2821)) + expect_identical(out$historical_CMD$.dots$historical_years, c(1987, 2001)) + expect_identical(out$projected_MDC$.dots$future_years, latest + 5) + ## by period, and consecutive-year (calcCumMDC), left alone + expect_identical(out$historical_CMI_normal, cv$historical_CMI_normal) + expect_identical(out$historical_cumMDC, cv$historical_cumMDC) + expect_error(climateVarsForRecord(cv, rec, c(2720, 2900)), "no climate year for simulation year\\(s\\) 2900") +}) + +test_that("with a climateYearRecord, init does not check times (model years) against calendar years", { + rtm <- terra::rast(nrows = 2, ncols = 2, vals = 1L, crs = "EPSG:3978") + sa <- sf::st_as_sf(terra::as.polygons(rtm)) + rec <- data.table::data.table(simYear = 2720, climateYear = 1987) + sim <- suppressMessages(SpaDES.core::simInit( + times = list(start = 2720, end = 2720), modules = moduleName, paths = testPaths, + objects = list(studyArea = sa, rasterToMatch = rtm, climateVariables = list(dummy = list()), + climateYearRecord = rec))) + err <- tryCatch({suppressMessages(SpaDES.core::spades(sim, debug = FALSE)); ""}, + error = function(e) conditionMessage(e)) + ## stops later, on the dummy climateVariables, not on the years + expect_false(grepl("model years|climate year", err)) +}) diff --git a/tests/testthat/test-loadOrder.R b/tests/testthat/test-loadOrder.R new file mode 100644 index 0000000..19e2915 --- /dev/null +++ b/tests/testthat/test-loadOrder.R @@ -0,0 +1,29 @@ +## This module reads `climateYearRecord` (from the climateYear module), and climateYear reads this +## module's climate rasters: a cycle, which SpaDES resolves with climateYear's init first. +## The `loadOrder` metadata keeps this module's init first, in either module order. The stub +## has climateYear's inputs, output and loadOrder; without this module's loadOrder it fails. + +test_that("init is scheduled before climateYear's, in either module order", { + mp <- withr::local_tempdir() + file.symlink(moduleRoot, file.path(mp, moduleName)) + dir.create(file.path(mp, "climateYear")) + writeLines(c( + 'defineModule(sim, list(name = "climateYear", description = "stub", keywords = "",', + ' authors = person("A", "B"), childModules = character(0), version = list(climateYear = "0.0.1"),', + ' timeframe = as.POSIXlt(c(NA, NA)), timeunit = "year", citation = list(), documentation = list(),', + ' loadOrder = list(before = "fireSense_dataPrepPredict"),', + ' reqdPkgs = list(), parameters = rbind(defineParameter(".useCache", "logical", FALSE, NA, NA, "stub")),', + ' inputObjects = bindrows(expectsInput("historicalClimateRasters", "list", "stub"),', + ' expectsInput("projectedClimateRasters", "list", "stub")),', + ' outputObjects = createsOutput("climateYearRecord", "data.table", "stub")))', + 'doEvent.climateYear <- function(sim, eventTime, eventType) sim'), + file.path(mp, "climateYear", "climateYear.R")) + for (mods in list(c(moduleName, "climateYear"), c("climateYear", moduleName))) { + sim <- suppressMessages(SpaDES.core::simInit( + times = list(start = 2000, end = 2001), modules = mods, + paths = modifyList(testPaths, list(modulePath = mp)))) + ev <- SpaDES.core::events(sim) + inits <- ev$moduleName[ev$eventType == "init"] + expect_identical(inits[inits %in% mods], c(moduleName, "climateYear")) + } +}) diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index ce9aa30..0fe5b54 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -18,6 +18,7 @@ test_that("inputs are the expected names and classes", { expect_identical( inputs[order(names(inputs))], c(climateVariables = "list", + climateYearRecord = "data.table", rasterToMatch = "SpatRaster", studyArea = "sf") ) @@ -44,3 +45,9 @@ test_that("parameters are the expected names", { "projectedClimateYears", "projectedType", "quickCheck")) ) }) + +test_that("projected climate years start in 2017", { + md <- SpaDES.core::moduleMetadata(module = moduleName, path = modulePath) + pars <- stats::setNames(md$parameters$default, md$parameters$paramName) + expect_identical(pars[["projectedClimateYears"]], 2017:2100) +}) diff --git a/tests/testthat/test-outputDirKey.R b/tests/testthat/test-outputDirKey.R new file mode 100644 index 0000000..8bb8bf9 --- /dev/null +++ b/tests/testthat/test-outputDirKey.R @@ -0,0 +1,49 @@ +## `outputDir` is part of the event cache keys, so an absolute path with a machine-specific prefix +## (the hindcast climate folder, /outputs/hindcast//climate) made a cache built +## on one machine miss on another. `outputDir` may be `reproducible::asPath(dir, nParentDirs)`, which +## the key holds as only `dir`'s last `nParentDirs + 1` components. A different folder must still miss: +## a hit writes nothing into the new folder. + +test_that("Init() uses a Path outputDir as the folder the climate files go to", { + withr::local_options(reproducible.useCache = FALSE, reproducible.useNewDigestAlgorithm = 2) + root <- withr::local_tempdir() + dir <- file.path(root, "outputs", "hindcastX", "9.1", "climate") + sim <- runInit(path = withr::local_tempdir(), params = list(outputDir = reproducible::asPath(dir, 2))) + expect_true(all(startsWith(normalizePath(terra::sources(sim$historicalClimateRasters[[1]])), + normalizePath(dir)))) +}) + +## a module with this module's parameter and a cached init, to read the key from the cache +writeKeyModule <- function(modulePath) { + dir.create(file.path(modulePath, "m"), recursive = TRUE) + cat(file = file.path(modulePath, "m", "m.R"), sep = "", ' +defineModule(sim, list(name = "m", description = "", keywords = "", authors = person("A", "B"), + childModules = character(0), version = list(m = "0.0.1"), timeframe = as.POSIXlt(c(NA, NA)), + timeunit = "year", citation = list(), documentation = list(), reqdPkgs = list(), + parameters = rbind( + defineParameter("outputDir", "character", NA_character_, NA, NA, "d"), + defineParameter(".useCache", "character", "init", NA, NA, "c")), + inputObjects = bindrows(), outputObjects = bindrows())) +doEvent.m <- function(sim, eventTime, eventType, debug = FALSE) invisible(sim) +') +} + +test_that("a Path outputDir keys the event on its last components: same under another base, different for another folder", { + skip_if_not_installed("SpaDES.core") + withr::local_options(spades.loadReqdPkgs = FALSE, spades.moduleCodeChecks = FALSE, spades.useRequire = FALSE, + reproducible.useMemoise = FALSE, spades.saveSimOnExit = FALSE) + modulePath <- withr::local_tempdir(); cachePath <- withr::local_tempdir() + writeKeyModule(modulePath) + nKeys <- function(outputDir) { + s <- suppressMessages(SpaDES.core::simInit(modules = "m", times = list(start = 0, end = 1), + params = list(m = list(outputDir = outputDir)), + paths = list(modulePath = modulePath, cachePath = cachePath))) + suppressMessages(SpaDES.core::spades(s, debug = FALSE)) + length(unique(reproducible::showCache(cachePath, verbose = -2)$cacheId)) + } + asP <- function(base, hindcast) reproducible::asPath(file.path(base, "outputs", hindcast, "9.1", "climate"), 2) + expect_identical(nKeys(asP("/machineA", "hindcastX")), 1L) + expect_identical(nKeys(asP("/other/machineB", "hindcastX")), 1L) # same relative folder: a hit + expect_identical(nKeys(asP("/machineA", "hindcastY")), 2L) # another folder: a miss + expect_identical(nKeys(file.path("/machineA", "outputs", "hindcastX", "9.1", "climate")), 3L) # a plain path is keyed in full +})