Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4eea471
projectedClimateYears defaults to 2017:2100
eliotmcintire Oct 9, 2026
5d8e60e
Merge PR #21 (projected-years-2017) into modsForFireSense
eliotmcintire Oct 9, 2026
bb1caa2
init fails early when times are not calendar years
eliotmcintire Oct 14, 2026
97f7e4e
Use climateData::checkCalendarYears(); canClimateData follow-ups
eliotmcintire Oct 15, 2026
820b4fe
Merge PR #22 (defaults-safe) into modsForFireSense
eliotmcintire Oct 15, 2026
7ce590c
CI: run on modsForFireSense (our integration branch; fixes are PR'd i…
eliotmcintire Oct 21, 2026
26c11db
Merge development into modsForFireSense
eliotmcintire Oct 21, 2026
5487446
init checks the climate year (climateYear) the run is at, not start(s…
eliotmcintire Nov 12, 2026
2a0d92b
Year check of a rerun uses the run's climateYearRecord, not climateYear
eliotmcintire Nov 12, 2026
7d1272a
Rerun: prepare the climate years the record holds for the simulation …
eliotmcintire Nov 12, 2026
11929b3
Merge pull request #30 from PredictiveEcology/fix/check-climateYear
eliotmcintire Nov 14, 2026
459b77f
Re-build canClimateData.Rmd
github-actions[bot] Nov 14, 2026
c155a97
Merge development into modsForFireSense
eliotmcintire Nov 14, 2026
47128a4
Leave outputDir out of the event cache keys (defineParameter cacheKey…
eliotmcintire Nov 16, 2026
af7472b
outputDir: pass asPath(dir, nParentDirs) to key the event on the fold…
eliotmcintire Nov 16, 2026
4e56732
Merge pull request #33 from PredictiveEcology/cache-key-paths
eliotmcintire Nov 16, 2026
ae6cd24
Bump to 1.1.1.9001 (after #33) [skip ci]
eliotmcintire Nov 16, 2026
0596ef6
Re-build canClimateData.Rmd
github-actions[bot] Nov 16, 2026
604cd4b
Require SpaDES.core >= 3.2.1.9070 (inputs(sim)$loadTime in the simula…
eliotmcintire Nov 16, 2026
119d3b8
Merge pull request #34 from PredictiveEcology/chore/spadescore-floor
eliotmcintire Nov 16, 2026
03b71b8
Bump to 1.1.1.9002 (after #34) [skip ci]
eliotmcintire Nov 16, 2026
2030c52
Re-build canClimateData.Rmd
github-actions[bot] Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/render-module-rmd.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ on:
- main
- master
- development
- modsForFireSense
push:
branches:
- main
- master
- development
- modsForFireSense
paths:
- .github/workflows/render-module-rmd.yaml
- canClimateData.Rmd
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/testthat-module.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
87 changes: 79 additions & 8 deletions canClimateData.R
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 `<hindcast>/<ELF>/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.")),
Expand Down Expand Up @@ -91,6 +101,14 @@ defineModule(sim, list(
"are set by module parameters and must be identical for all variables.",
"See also <https://climatena.ca/Help2#_var> 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",
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
16 changes: 11 additions & 5 deletions canClimateData.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -127,6 +127,12 @@ See `?climateData::prepClimateLayers` for examples constructing a custom `climat
<td style="text-align:left;"> 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 &lt;https://climatena.ca/Help2#_var&gt; for all available climate variables. </td>
<td style="text-align:left;"> NA </td>
</tr>
<tr>
<td style="text-align:left;"> climateYearRecord </td>
<td style="text-align:left;"> data.table </td>
<td style="text-align:left;"> 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. </td>
<td style="text-align:left;"> NA </td>
</tr>
<tr>
<td style="text-align:left;"> rasterToMatch </td>
<td style="text-align:left;"> SpatRaster </td>
Expand Down Expand Up @@ -212,7 +218,7 @@ Table \@ref(tab:moduleParams-canClimateData) shows the full list of module param
<td style="text-align:left;"> NA </td>
<td style="text-align:left;"> NA </td>
<td style="text-align:left;"> NA </td>
<td style="text-align:left;"> 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')`. </td>
<td style="text-align:left;"> 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 `&lt;hindcast&gt;/&lt;ELF&gt;/climate`. </td>
<td style="text-align:left;"> TRUE </td>
</tr>
<tr>
Expand All @@ -227,10 +233,10 @@ Table \@ref(tab:moduleParams-canClimateData) shows the full list of module param
<tr>
<td style="text-align:left;"> projectedClimateYears </td>
<td style="text-align:left;"> numeric </td>
<td style="text-align:left;"> 2011, 20.... </td>
<td style="text-align:left;"> 2017, 20.... </td>
<td style="text-align:left;"> NA </td>
<td style="text-align:left;"> NA </td>
<td style="text-align:left;"> range of years captured by the projected climate data if `climateVariables` not supplied. </td>
<td style="text-align:left;"> 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. </td>
<td style="text-align:left;"> TRUE </td>
</tr>
<tr>
Expand Down
3 changes: 3 additions & 0 deletions tests/testthat/helper-module.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading