diff --git a/NEWS.md b/NEWS.md
index e7be3e4..2347a24 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) 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`).
* 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 e03a9db..63b7849 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 b4e5f41..9c213ba 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)",
@@ -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_,
@@ -271,7 +280,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 +341,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 `\"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",
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 +933,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]],
@@ -1898,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)
}
@@ -2002,9 +2019,21 @@ runBorealDP_forCohortData <- function(sim) {
}
if (doStandAgeMaps) {
+ ## 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(ageSources, "all")) {
+ 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 +2052,17 @@ 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(ageSources, "all")) {
+ 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 0000000..034db65
--- /dev/null
+++ b/tests/testthat/test-disturbanceAgeSources.R
@@ -0,0 +1,30 @@
+## 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 this module's ageDisturbanceSources", {
+ io <- paste(deparse(moduleDefs()[[".inputObjects"]], width.cutoff = 500L), collapse = "\n")
+ 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)
+})
+
+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 80c003c..2ac079f 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",
@@ -98,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",