From a4ce7234e48ef247577bfd599b4e7d7717df6647 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 30 Nov 2026 16:04:57 -0700 Subject: [PATCH 1/4] Stand ages and youngAge from the same disturbance records as Biomass_borealDataPrep With Biomass_borealDataPrep ageDisturbanceSources = "NFDB+NBAC+CanLaD", the per-year standAgeMaps reset age with LandR::prepInputsDisturbanceYear(), and a new disturbancePixelsByYear (fire and harvest by year) replaces firePolysForAge and historicalFireRaster for time since disturbance (youngAge). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXfVqAugcusGHygZGJ3 --- NEWS.md | 2 ++ R/youngAge.R | 20 +++++++++-- fireSense_dataPrepFit.R | 38 ++++++++++++++++++--- tests/testthat/test-disturbanceAgeSources.R | 24 +++++++++++++ tests/testthat/test-metadata.R | 1 + 5 files changed, 78 insertions(+), 7 deletions(-) create mode 100644 tests/testthat/test-disturbanceAgeSources.R diff --git a/NEWS.md b/NEWS.md index e7be3e47..18251c8f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) +* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) when Biomass_borealDataPrep's `ageDisturbanceSources` is `"NFDB+NBAC+CanLaD"` (its default), so they match the simulation's own starting ages. With `"NFDB"`, or without Biomass_borealDataPrep in the simulation, NFDB fires as before. Changes the vegetation the fits are made with. + * New parameter `saveFitTables` (default `character(0)`: nothing is written). `"ignition"` and/or `"escape"` write `fireSense_ignitionCovariates` and `fireSense_escapeCovariates`, the exact tables the fits are trained on, to `outputPath(sim)` as `_.qs2` (qs2) and list them in `outputs(sim)`, so an analysis outside the fit can use them. They are written by a new event `saveFitTables` after the prep events: it is never cached (`.neverCache`) and reads the tables from the simList, so a cached `prepIgnitionFitData` still writes them. No table changes, and the parameter is not in the cache keys (`cacheKey = FALSE`). * New parameter `spreadClimateCurve` (`FALSE` by default: nothing changes). `TRUE` adds a covariate `_curve = softplus(C - k, s)` (smooth, no corner) for each spread climate variable `C`, with its own coefficient, so the climate response can steepen in dry years; `k` and `s` are the ELF's median and sd of `C` over the burnable pixels of all the fit years. They are in `sim$climateCurvePars`, which `fireSense_spreadFit` writes to the ledger row, and `fireSense_spreadPredict` builds the term from them. A negative coefficient flattens the dry side. A reused ledger fit keeps its own curve terms and their `k` and `s`. The code is `fireSenseUtils::climateCurvePars()`, `addClimateCurve()`, `softplus()` and `climateTermCols()`, in the `prepSpreadFitData` cache key. Needs `fireSense_spreadFit`, `fireSense_spreadPredict` and fireSenseUtils with the curve (fireSenseUtils >= 0.2.3.9196). diff --git a/R/youngAge.R b/R/youngAge.R index e03a9db0..63b78496 100644 --- a/R/youngAge.R +++ b/R/youngAge.R @@ -1,12 +1,14 @@ #' Every fire, as the pixels burned in each year #' #' All fires, not only those being fitted, because any of them resets `youngAge`. From -#' `historicalFireRaster` when supplied (as `fireSenseUtils::makeTSD()` does), otherwise from -#' `firePolysForAge`. +#' `disturbancePixelsByYear` when there is one (fire and harvest, the records the stand ages use), else +#' `historicalFireRaster` when supplied (as `fireSenseUtils::makeTSD()` does), otherwise `firePolysForAge`. #' -#' @param sim a `simList` with `firePolysForAge` or `historicalFireRaster`, and `flammableRTMs`. +#' @param sim a `simList` with `disturbancePixelsByYear`, `firePolysForAge` or `historicalFireRaster`, and +#' `flammableRTMs`. #' @return list named by year of integer `pixelID`s, see `fireSenseUtils::firePixelsByYear()`. allFirePixelsByYear <- function(sim) { + if (!is.null(sim$disturbancePixelsByYear)) return(sim$disturbancePixelsByYear) fireSenseUtils::firePixelsByYear(firePolys = sim$firePolysForAge, fireRaster = sim$historicalFireRaster, template = sim$flammableRTMs[[1]]) } @@ -37,3 +39,15 @@ addAnnualYoungAge <- function(annualCovariates, tsds, firePixelsByYear, cutoffFo } annualCovariates } + +#' The year of each pixel's last disturbance at or before a data year, for `fireSenseUtils::makeTSD()` +#' +#' @param sim a `simList`; uses `disturbancePixelsByYear` (on `rasterToMatch`) when there is one. +#' @param year the data year. +#' @return a `SpatRaster` on `rasterToMatch` of disturbance years (`NA`: none), from `disturbancePixelsByYear`; +#' else `historicalFireRaster` (which may be `NULL`, and then `makeTSD()` uses `firePolysForAge`). +disturbanceYearRaster <- function(sim, year) { + if (is.null(sim$disturbancePixelsByYear)) return(sim$historicalFireRaster) + terra::rast(sim$rasterToMatch, + vals = LandR::lastDisturbanceYear(terra::ncell(sim$rasterToMatch), year, sim$disturbancePixelsByYear)) +} diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index b4e5f41c..c98cf00a 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -20,7 +20,7 @@ defineModule(sim, list( "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9196)", # 9196 (fireSenseUtils#265): climateCurvePars(), addClimateCurve(), softplus(), climateTermCols(), isClimateTermCol(), ledgerClimateCurvePars(); 9190: modelledFires() (fireSenseUtils#261; set to the real version after merge); 9186: splitSpreadClimate(), climateSplitCols(), climateSplitRefPixels(), isClimateSplitCol() (fireSenseUtils#244); 9184: addCoreFraction(), coreFractionByYear() (moved from this module); 9179: readSpreadFitLedger(escapeDefinition); 9169: fitDataNeeded() (#234); 9161: coreFractionTxt; 9159: climateCovRanges Tmaxsm, PPTsm (#224); 9141: spreadFitLedgerInputs(), spreadFitLedgerInputLists(); 9135: fireSenseFireCauses; 9131: fireCauseCodes(); 9130: climateRasterToDataTable(Index) reads only those cells; 9128: burnableHaTxt "FOR-CAST/fireregimetools@main (>= 0.1.0.9008)", "ggplot2", "methods", "parallel", "purrr", "raster", "sf", "sp", "stats", "utils", - "PredictiveEcology/LandR@development (>= 1.2.0.9015)", + "PredictiveEcology/LandR@development (>= 1.2.0.9067)", # prepInputsDisturbanceYear() "PredictiveEcology/SpaDES.core@development (>= 3.2.1.9073)", "PredictiveEcology/SpaDES.project@development", "PredictiveEcology/SpaDES.tools@development (>= 2.1.1.9000)", @@ -271,7 +271,7 @@ defineModule(sim, list( fireSenseUtils::assessFuelClasses, fireSenseUtils::dataYearElement, fireSenseUtils::dataYearFor, fireSenseUtils::fuelClassPrep, fireSenseUtils::lccFlammableShare, fireSenseUtils::makeLandcoverDT, - fireSenseUtils::makeTSD, spreadFitPreRun = sim$spreadFitPreRun))), + fireSenseUtils::makeTSD, LandR::lastDisturbanceYear, spreadFitPreRun = sim$spreadFitPreRun))), prepIgnitionFitData = list(.cacheExtra = quote(c( list(fireSenseUtils::addCoreFraction, fireSenseUtils::coreFractionByYear, fireSenseUtils::inELFCore, spreadFitPreRun = sim$spreadFitPreRun), fireSenseUtils::escapeFireSetDeps()))), @@ -332,6 +332,12 @@ defineModule(sim, list( expectsInput("firePolysForAge", "list", sourceURL = NA, paste("List of annual fire polygons used for time since disturbance; as `firePolys`, but", "starting `cutoffForYoungAge` years before the first of `fireYears`.")), + expectsInput("disturbancePixelsByYear", "list", sourceURL = NA, + paste("List named by year of the pixels (of `rasterToMatch`) with a stand-replacing fire or harvest", + "that year, from `LandR::prepInputsDisturbanceYear(byYear = TRUE)`. Made when Biomass_borealDataPrep's", + "`ageDisturbanceSources` is `\"NFDB+NBAC+CanLaD\"`; then it replaces `firePolysForAge` and", + "`historicalFireRaster` for time since disturbance (`youngAge`), so `youngAge` follows the same", + "disturbances as the stand ages.")), expectsInput("historicalFireRaster", "SpatRaster", sourceURL = "https://opendata.nfis.org/downloads/forest_change/CA_Forest_Fire_1985-2020.zip", paste("Optional raster of fire year, 1985-2020. If supplied it replaces `firePolysForAge` for time since", @@ -918,7 +924,7 @@ dataPrepBuild <- function(sim) { sim$nonForest_timeSinceDisturbances <- Map(dy = mod$dyChars, dyNum = mod$dys, function(dy, dyNum) { tsd <- makeTSD( year = dyNum, - fireRaster = sim$historicalFireRaster, ## can be NULL + fireRaster = disturbanceYearRaster(sim, dyNum), ## can be NULL firePolys = sim$firePolysForAge, standAgeMap = standAgeMaps[[dy]], lcc = sim$landcoverDTs[[dy]], @@ -2002,9 +2008,21 @@ runBorealDP_forCohortData <- function(sim) { } if (doStandAgeMaps) { + ## the last stand-replacing disturbance that resets age, from the records Biomass_borealDataPrep uses + ## (its ageDisturbanceSources); NULL: prepInputsStandAgeMap() reads the NFDB fires itself, as before + bbdp <- params(sim)$Biomass_borealDataPrep + distYear <- if (identical(bbdp$ageDisturbanceSources, "NFDB+NBAC+CanLaD")) { + LandR::prepInputsDisturbanceYear(rasterToMatch = sim$rasterToMatch_biomassParam, latestYear = dy, + destinationPath = dPath, + earliestYear = if (is.null(bbdp$earliestFireYear)) 1950L else bbdp$earliestFireYear) |> + Cache(omitArgs = "destinationPath", .functionName = paste0("prepInputsDisturbanceYear", dy), + userTags = c(cacheTags, "prepInputsDisturbanceYear"), + ## Cache digests only prepInputsDisturbanceYear's own code; the rule is this function + .cacheExtra = list(LandR::disturbancesByYear, LandR::lastDisturbanceYear)) + } standAgeMap <- prepInputsStandAgeMap(rasterToMatch = sim$rasterToMatch_biomassParam, destinationPath = dPath, - dataYear = dy) |> + dataYear = dy, firePerimeters = distYear) |> Cache(.functionName = paste0("prepInputsStandAgeMap", dy), userTags = c(cacheTags, "prepInputsStandAgeMap"), ## Cache digests only prepInputsStandAgeMap's own code; it adjusts ages in fires with this function @@ -2023,6 +2041,18 @@ runBorealDP_forCohortData <- function(sim) { }) outsRev <- Require::invertList(outs) list2env(outsRev, envir = envir(sim)) # nolint: vars standAgeMaps propFlammables rstLCCs + + ## every stand-replacing disturbance by year, for youngAge, from the records the stand ages use + if (!suppliedElsewhere("disturbancePixelsByYear", sim) && + identical(params(sim)$Biomass_borealDataPrep$ageDisturbanceSources, "NFDB+NBAC+CanLaD")) { + bbdp <- params(sim)$Biomass_borealDataPrep + sim$disturbancePixelsByYear <- LandR::prepInputsDisturbanceYear( + rasterToMatch = sim$rasterToMatch, latestYear = max(P(sim)$fireYears), destinationPath = dPath, + earliestYear = if (is.null(bbdp$earliestFireYear)) 1950L else bbdp$earliestFireYear, byYear = TRUE) |> + Cache(omitArgs = "destinationPath", .functionName = "prepInputsDisturbanceYear_byYear", + userTags = c(cacheTags, "disturbancePixelsByYear"), + .cacheExtra = list(LandR::disturbancesByYear)) + } mod$dyChars <- sapply(mod$dys, function(dy) grep(dy, names(sim$rstLCCs), value = TRUE)) diff --git a/tests/testthat/test-disturbanceAgeSources.R b/tests/testthat/test-disturbanceAgeSources.R new file mode 100644 index 00000000..1f20429c --- /dev/null +++ b/tests/testthat/test-disturbanceAgeSources.R @@ -0,0 +1,24 @@ +## The per-year stand age maps reset age with the same disturbance records as Biomass_borealDataPrep (its +## ageDisturbanceSources), so the fits' vegetation and the simulation's starting vegetation agree. + +test_that(".inputObjects builds the per-year age maps from Biomass_borealDataPrep's ageDisturbanceSources", { + io <- paste(deparse(moduleDefs()[[".inputObjects"]], width.cutoff = 500L), collapse = "\n") + expect_match(io, 'identical(bbdp$ageDisturbanceSources, "NFDB+NBAC+CanLaD")', fixed = TRUE) + expect_match(io, "LandR::prepInputsDisturbanceYear(rasterToMatch = sim$rasterToMatch_biomassParam, latestYear = dy", + fixed = TRUE) + expect_match(io, "dataYear = dy, firePerimeters = distYear)", fixed = TRUE) +}) + +test_that("youngAge follows disturbancePixelsByYear when there is one", { + rtm <- terra::rast(nrows = 1, ncols = 4, vals = 1) + sim <- list(rasterToMatch = rtm, disturbancePixelsByYear = list(`1990` = 1:2, `2005` = 2L), + firePolysForAge = "not used", historicalFireRaster = NULL) + expect_identical(allFirePixelsByYear(sim), sim$disturbancePixelsByYear) + ## the data year's time since disturbance starts from the last disturbance at or before it + expect_identical(as.integer(terra::values(disturbanceYearRaster(sim, 2000L), mat = FALSE)), c(1990L, 1990L, NA, NA)) + expect_identical(as.integer(terra::values(disturbanceYearRaster(sim, 2010L), mat = FALSE)), c(1990L, 2005L, NA, NA)) + ## without it, as before: historicalFireRaster (NULL here, so makeTSD uses firePolysForAge) + expect_null(disturbanceYearRaster(list(historicalFireRaster = NULL), 2000L)) + src <- paste(readLines(testthat::test_path("..", "..", "fireSense_dataPrepFit.R")), collapse = "\n") + expect_match(src, "sim$disturbancePixelsByYear <- LandR::prepInputsDisturbanceYear(", fixed = TRUE) +}) diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index 80c003cb..627aed0a 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -21,6 +21,7 @@ test_that("inputs are the expected names and classes", { climateVariables = "list", climateVariablesForFire = "list", cohortDatas = "list", + disturbancePixelsByYear = "list", firePolys = "list", firePolysForAge = "list", historicalClimateRasters = "list", From c11baebbb7dd529f552969e6c989458ddb44f71d Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 30 Nov 2026 16:21:57 -0700 Subject: [PATCH 2/4] NEWS: the new disturbance records are opt in (Biomass_borealDataPrep default "NFDB") Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXfVqAugcusGHygZGJ3 --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 18251c8f..6e3a00fe 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) -* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) when Biomass_borealDataPrep's `ageDisturbanceSources` is `"NFDB+NBAC+CanLaD"` (its default), so they match the simulation's own starting ages. With `"NFDB"`, or without Biomass_borealDataPrep in the simulation, NFDB fires as before. Changes the vegetation the fits are made with. +* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) when Biomass_borealDataPrep's `ageDisturbanceSources` is `"NFDB+NBAC+CanLaD"` (opt in), so they match the simulation's own starting ages; `youngAge` then follows the same fires and cuts (new `disturbancePixelsByYear`). With `"NFDB"` (Biomass_borealDataPrep's default), or without Biomass_borealDataPrep in the simulation, nothing changes. Opting in changes the vegetation the fits are made with. * New parameter `saveFitTables` (default `character(0)`: nothing is written). `"ignition"` and/or `"escape"` write `fireSense_ignitionCovariates` and `fireSense_escapeCovariates`, the exact tables the fits are trained on, to `outputPath(sim)` as `
_.qs2` (qs2) and list them in `outputs(sim)`, so an analysis outside the fit can use them. They are written by a new event `saveFitTables` after the prep events: it is never cached (`.neverCache`) and reads the tables from the simList, so a cached `prepIgnitionFitData` still writes them. No table changes, and the parameter is not in the cache keys (`cacheKey = FALSE`). From 96e57aec897b1275001515cfcee8ddcf31674904 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 30 Nov 2026 16:22:56 -0700 Subject: [PATCH 3/4] Opt-in value of ageDisturbanceSources is "all"; the docs say what "all" uses now Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXfVqAugcusGHygZGJ3 --- NEWS.md | 2 +- fireSense_dataPrepFit.R | 6 +++--- tests/testthat/test-disturbanceAgeSources.R | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/NEWS.md b/NEWS.md index 6e3a00fe..3936e2cb 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) -* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) when Biomass_borealDataPrep's `ageDisturbanceSources` is `"NFDB+NBAC+CanLaD"` (opt in), so they match the simulation's own starting ages; `youngAge` then follows the same fires and cuts (new `disturbancePixelsByYear`). With `"NFDB"` (Biomass_borealDataPrep's default), or without Biomass_borealDataPrep in the simulation, nothing changes. Opting in changes the vegetation the fits are made with. +* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) when Biomass_borealDataPrep's `ageDisturbanceSources` is `"all"` (opt in), so they match the simulation's own starting ages; `youngAge` then follows the same fires and cuts (new `disturbancePixelsByYear`). With `"NFDB"` (Biomass_borealDataPrep's default), or without Biomass_borealDataPrep in the simulation, nothing changes. Opting in changes the vegetation the fits are made with. * New parameter `saveFitTables` (default `character(0)`: nothing is written). `"ignition"` and/or `"escape"` write `fireSense_ignitionCovariates` and `fireSense_escapeCovariates`, the exact tables the fits are trained on, to `outputPath(sim)` as `
_.qs2` (qs2) and list them in `outputs(sim)`, so an analysis outside the fit can use them. They are written by a new event `saveFitTables` after the prep events: it is never cached (`.neverCache`) and reads the tables from the simList, so a cached `prepIgnitionFitData` still writes them. No table changes, and the parameter is not in the cache keys (`cacheKey = FALSE`). diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index c98cf00a..8fddb34b 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -335,7 +335,7 @@ defineModule(sim, list( expectsInput("disturbancePixelsByYear", "list", sourceURL = NA, paste("List named by year of the pixels (of `rasterToMatch`) with a stand-replacing fire or harvest", "that year, from `LandR::prepInputsDisturbanceYear(byYear = TRUE)`. Made when Biomass_borealDataPrep's", - "`ageDisturbanceSources` is `\"NFDB+NBAC+CanLaD\"`; then it replaces `firePolysForAge` and", + "`ageDisturbanceSources` is `\"all\"`; then it replaces `firePolysForAge` and", "`historicalFireRaster` for time since disturbance (`youngAge`), so `youngAge` follows the same", "disturbances as the stand ages.")), expectsInput("historicalFireRaster", "SpatRaster", @@ -2011,7 +2011,7 @@ runBorealDP_forCohortData <- function(sim) { ## the last stand-replacing disturbance that resets age, from the records Biomass_borealDataPrep uses ## (its ageDisturbanceSources); NULL: prepInputsStandAgeMap() reads the NFDB fires itself, as before bbdp <- params(sim)$Biomass_borealDataPrep - distYear <- if (identical(bbdp$ageDisturbanceSources, "NFDB+NBAC+CanLaD")) { + distYear <- if (identical(bbdp$ageDisturbanceSources, "all")) { LandR::prepInputsDisturbanceYear(rasterToMatch = sim$rasterToMatch_biomassParam, latestYear = dy, destinationPath = dPath, earliestYear = if (is.null(bbdp$earliestFireYear)) 1950L else bbdp$earliestFireYear) |> @@ -2044,7 +2044,7 @@ runBorealDP_forCohortData <- function(sim) { ## every stand-replacing disturbance by year, for youngAge, from the records the stand ages use if (!suppliedElsewhere("disturbancePixelsByYear", sim) && - identical(params(sim)$Biomass_borealDataPrep$ageDisturbanceSources, "NFDB+NBAC+CanLaD")) { + identical(params(sim)$Biomass_borealDataPrep$ageDisturbanceSources, "all")) { bbdp <- params(sim)$Biomass_borealDataPrep sim$disturbancePixelsByYear <- LandR::prepInputsDisturbanceYear( rasterToMatch = sim$rasterToMatch, latestYear = max(P(sim)$fireYears), destinationPath = dPath, diff --git a/tests/testthat/test-disturbanceAgeSources.R b/tests/testthat/test-disturbanceAgeSources.R index 1f20429c..2a220787 100644 --- a/tests/testthat/test-disturbanceAgeSources.R +++ b/tests/testthat/test-disturbanceAgeSources.R @@ -3,7 +3,7 @@ test_that(".inputObjects builds the per-year age maps from Biomass_borealDataPrep's ageDisturbanceSources", { io <- paste(deparse(moduleDefs()[[".inputObjects"]], width.cutoff = 500L), collapse = "\n") - expect_match(io, 'identical(bbdp$ageDisturbanceSources, "NFDB+NBAC+CanLaD")', fixed = TRUE) + expect_match(io, 'identical(bbdp$ageDisturbanceSources, "all")', fixed = TRUE) expect_match(io, "LandR::prepInputsDisturbanceYear(rasterToMatch = sim$rasterToMatch_biomassParam, latestYear = dy", fixed = TRUE) expect_match(io, "dataYear = dy, firePerimeters = distYear)", fixed = TRUE) From 972b652131afa148016cde6f05343f05ad3fe3c6 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 30 Nov 2026 16:34:05 -0700 Subject: [PATCH 4/4] ageDisturbanceSources is this module's own parameter, checked against Biomass_borealDataPrep's A hindcast runs without Biomass_borealDataPrep, and simInit drops the parameters of a module that is not loaded, so reading params(sim)$Biomass_borealDataPrep gave a hindcast the default and a youngAge unlike the fit's. paramCheckOtherMods() stops when both modules are loaded and differ; set it in .globals. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXfVqAugcusGHygZGJ3 --- NEWS.md | 2 +- fireSense_dataPrepFit.R | 20 +++++++++++++++----- tests/testthat/test-disturbanceAgeSources.R | 14 ++++++++++---- tests/testthat/test-metadata.R | 2 +- 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3936e2cb..2347a24f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) -* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) when Biomass_borealDataPrep's `ageDisturbanceSources` is `"all"` (opt in), so they match the simulation's own starting ages; `youngAge` then follows the same fires and cuts (new `disturbancePixelsByYear`). With `"NFDB"` (Biomass_borealDataPrep's default), or without Biomass_borealDataPrep in the simulation, nothing changes. Opting in changes the vegetation the fits are made with. +* The per-year stand age maps (`standAgeMaps`, which the fits' vegetation and the hindcasts use) reset age at the last stand-replacing disturbance from `LandR::prepInputsDisturbanceYear()` (NFDB, NBAC and CanLaD fire and harvest) with the new parameter `ageDisturbanceSources = "all"` (opt in; same parameter as Biomass_borealDataPrep's, checked to match, so set it in `.globals`), so they match the simulation's own starting ages; `youngAge` then follows the same fires and cuts (new `disturbancePixelsByYear`). It is this module's own parameter because a hindcast runs without Biomass_borealDataPrep. With `"NFDB"` (the default) nothing changes. Opting in changes the vegetation the fits are made with. * New parameter `saveFitTables` (default `character(0)`: nothing is written). `"ignition"` and/or `"escape"` write `fireSense_ignitionCovariates` and `fireSense_escapeCovariates`, the exact tables the fits are trained on, to `outputPath(sim)` as `
_.qs2` (qs2) and list them in `outputs(sim)`, so an analysis outside the fit can use them. They are written by a new event `saveFitTables` after the prep events: it is never cached (`.neverCache`) and reads the tables from the simList, so a cached `prepIgnitionFitData` still writes them. No table changes, and the parameter is not in the cache keys (`cacheKey = FALSE`). diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 8fddb34b..9c213ba0 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -41,6 +41,15 @@ defineModule(sim, list( defineParameter("bufferForFireRaster", "numeric", 1000, 0, NA, paste("Buffer distance within which separate patches of burned pixels count as one fire.", "Only used when `useRasterizedFireForSpread = TRUE`.")), + defineParameter("ageDisturbanceSources", "character", "NFDB", NA, NA, + paste("Which records reset stand age and `youngAge` at the last stand-replacing disturbance.", + "`\"NFDB\"` (default): as before (NFDB fire polygons for the per-year stand ages; `firePolysForAge`", + "or `historicalFireRaster` for `youngAge`). `\"all\"` (opt in): every record", + "`LandR::prepInputsDisturbanceYear()` uses (currently NFDB, NBAC and CanLaD fire and harvest),", + "for the per-year `standAgeMaps` and a new `disturbancePixelsByYear`. Same parameter as in", + "Biomass_borealDataPrep, which must match when both are in the simulation", + "(`SpaDES.core::paramCheckOtherMods()`); set it in `.globals` to set both. Its own parameter, so a", + "hindcast without Biomass_borealDataPrep builds `youngAge` as the fit did.")), defineParameter("cutoffForYoungAge", "numeric", fireSenseUtils::fireSenseYoungAgeCutoff, NA, NA, "Age at and below which pixels are considered 'young' (`young <- age <= cutoffForYoungAge`)"), defineParameter("dataYears", "integer", c(1985L, 1990L, 2000L, 2010L, 2020L), NA_integer_, NA_integer_, @@ -1904,6 +1913,8 @@ runBorealDP_forCohortData <- function(sim) { #' @param sim a `simList`. #' @return the `simList`, invisibly. .inputObjects <- function(sim) { + ## must match Biomass_borealDataPrep's when it is in the simulation; a hindcast runs without it + ageSources <- SpaDES.core::paramCheckOtherMods(sim, "ageDisturbanceSources", ifSetButDifferent = "error") if (!suppliedElsewhere("studyArea", sim)) { sim$studyArea <- LandR::randomStudyArea(size = 10000 * 6.25 * 20000) } @@ -2008,10 +2019,10 @@ runBorealDP_forCohortData <- function(sim) { } if (doStandAgeMaps) { - ## the last stand-replacing disturbance that resets age, from the records Biomass_borealDataPrep uses - ## (its ageDisturbanceSources); NULL: prepInputsStandAgeMap() reads the NFDB fires itself, as before + ## the last stand-replacing disturbance that resets age (ageDisturbanceSources); + ## NULL: prepInputsStandAgeMap() reads the NFDB fires itself, as before bbdp <- params(sim)$Biomass_borealDataPrep - distYear <- if (identical(bbdp$ageDisturbanceSources, "all")) { + distYear <- if (identical(ageSources, "all")) { LandR::prepInputsDisturbanceYear(rasterToMatch = sim$rasterToMatch_biomassParam, latestYear = dy, destinationPath = dPath, earliestYear = if (is.null(bbdp$earliestFireYear)) 1950L else bbdp$earliestFireYear) |> @@ -2043,8 +2054,7 @@ runBorealDP_forCohortData <- function(sim) { list2env(outsRev, envir = envir(sim)) # nolint: vars standAgeMaps propFlammables rstLCCs ## every stand-replacing disturbance by year, for youngAge, from the records the stand ages use - if (!suppliedElsewhere("disturbancePixelsByYear", sim) && - identical(params(sim)$Biomass_borealDataPrep$ageDisturbanceSources, "all")) { + if (!suppliedElsewhere("disturbancePixelsByYear", sim) && identical(ageSources, "all")) { bbdp <- params(sim)$Biomass_borealDataPrep sim$disturbancePixelsByYear <- LandR::prepInputsDisturbanceYear( rasterToMatch = sim$rasterToMatch, latestYear = max(P(sim)$fireYears), destinationPath = dPath, diff --git a/tests/testthat/test-disturbanceAgeSources.R b/tests/testthat/test-disturbanceAgeSources.R index 2a220787..034db65c 100644 --- a/tests/testthat/test-disturbanceAgeSources.R +++ b/tests/testthat/test-disturbanceAgeSources.R @@ -1,9 +1,15 @@ -## The per-year stand age maps reset age with the same disturbance records as Biomass_borealDataPrep (its -## ageDisturbanceSources), so the fits' vegetation and the simulation's starting vegetation agree. +## The per-year stand age maps reset age with the same disturbance records as Biomass_borealDataPrep +## (ageDisturbanceSources), so the fits' vegetation and the simulation's starting vegetation agree. The parameter is +## this module's own (checked against Biomass_borealDataPrep's): a hindcast runs without Biomass_borealDataPrep, and +## simInit drops the parameters of a module that is not loaded, so reading Biomass_borealDataPrep's would give a +## hindcast the default and a youngAge unlike the fit's. -test_that(".inputObjects builds the per-year age maps from Biomass_borealDataPrep's ageDisturbanceSources", { +test_that(".inputObjects builds the per-year age maps from this module's ageDisturbanceSources", { io <- paste(deparse(moduleDefs()[[".inputObjects"]], width.cutoff = 500L), collapse = "\n") - expect_match(io, 'identical(bbdp$ageDisturbanceSources, "all")', fixed = TRUE) + expect_match(io, 'ageSources <- SpaDES.core::paramCheckOtherMods(sim, "ageDisturbanceSources", ifSetButDifferent = "error")', + fixed = TRUE) + expect_match(io, 'identical(ageSources, "all")', fixed = TRUE) + expect_no_match(io, "bbdp$ageDisturbanceSources", fixed = TRUE) expect_match(io, "LandR::prepInputsDisturbanceYear(rasterToMatch = sim$rasterToMatch_biomassParam, latestYear = dy", fixed = TRUE) expect_match(io, "dataYear = dy, firePerimeters = distYear)", fixed = TRUE) diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index 627aed0a..2ac079f5 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -99,7 +99,7 @@ test_that("parameters are the expected names", { expect_identical( sort(md$parameters$paramName), sort(c(".neverCache", ".plots", ".studyAreaName", - ".useCache", ".useCacheArgs", "areaMultiplier", "bufferForFireRaster", "cutoffForYoungAge", + ".useCache", ".useCacheArgs", "ageDisturbanceSources", "areaMultiplier", "bufferForFireRaster", "cutoffForYoungAge", "dataYears", "doFit", "escapeSizeHa", "estimateFuelClasses", "fireCauses", "fireYears", "flammabilityThreshold", "forestedLCC", "fuelClassCol", "fuelCovariates", "heldOutFold", "igAggFactor", "minBufferSize", "minBurnableFireSizeHa", "minCovariateProp", "nonflammableLCC",