Skip to content
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
* The "Historical Fire Maps" figure is now listed in `outputs(sim)` on every run. Its outer `Cache()` skipped `Plots()` on a hit, so the figure was missing from the run's saved files; `Plots(useCache = TRUE, .cacheExtra = )` (SpaDES.core, PredictiveEcology/SpaDES.core#535) now skips building the maps on a hit and still records the figure.

* New parameter `spreadInteractions` (default `character(0)`: nothing changes, the formula string is byte-identical). `"climate:fuel"` adds to the spread formula one interaction term for each spread climate variable and each fuel covariate (`fireSenseUtils::spreadFuelCols()`: not `youngAge`, `nfLCC_*` or `treedWetland`), e.g. `CMD:dom_agb_Pice_mar`, after the main effects, so `fireSense_spreadFit` fits fuel x climate interactions with the other terms (`spreadRHS()`, `checkSpreadInteractions()`). Each term is the product of its two covariates after each is rescaled and centred, 0 where `youngAge` cleared the fuel, in the fit and in `fireSense_spreadPredict`; each main effect is then the slope at the mean of the other covariate, so the drought >= 0 and fuel >= 0 bounds apply at typical conditions (`fireSenseUtils::spreadProbFromIntegerCovs()`). It needs `spreadCovariates = "all"`. Needs fireSenseUtils >= 0.2.3.9177 (#242), and `fireSense_spreadFit` and `fireSense_spreadPredict` with their interaction PRs. Adding `spreadFuelCols` to `prepSpreadFitData`'s `.cacheExtra` re-runs that event once.
* New parameter `spreadClimateSplit` (default `FALSE`: nothing changes, the formula string is byte-identical). `TRUE` splits the spread climate variable `C` into two terms with a coefficient each: `C_yr`, the year's median of `C` over the ELF's burnable pixels (one value for every pixel of a year: the year-to-year swings), and `C_dev`, `C` minus it (the departure from the year's median: the gradient within a year). The median is over the burnable pixels, not the fire buffers, so `fireSense_spreadPredict` can make the same value from a year's climate layer; both use `fireSenseUtils::splitSpreadClimate()`. `annualSpreadCovariates()` has a new argument `climateSplit`. The parameter is in the `prepSpreadFitData` cache key, so that event re-runs once. Needs `fireSenseUtils::splitSpreadClimate()` (Depends-on PredictiveEcology/fireSenseUtils); the `reqdPkgs` floor is set after that merges. Run it with `fireSense_spreadFit` and `fireSense_spreadPredict` of the same change; a prediction needs no setting, it reads the terms from the ledger row. A ledger fit that is reused (`doFit` FALSE) keeps its own split: `Init()` takes it from the row's coefficient names (`mod$spreadClimateSplit`, `useClimateSplit()`), so a predict-only job with the parameter `FALSE` still gets `CMD_yr`/`CMD_dev`. The reference pixels are chosen by `fireSenseUtils::climateSplitRefPixels()`.

* `spreadInteractions = "climate:fuel"` now works with `spreadClimateSplit` (the two together stopped in `checkSpreadInteractions()`). With the split on, each interaction is built from the between-year term, `CMD_yr:fuel` (the year's ELF median of CMD times the fuel), and the within-year `CMD_dev` does not interact. `checkSpreadInteractions()` lost its `climateSplit` argument; `spreadRHS()` builds the term names from `fireSenseUtils::climateSplitYrSuffix`. Without the split nothing changes. Run it with `fireSense_spreadFit` and `fireSense_spreadPredict` of the same change.

* New parameter `seedVegInit` (default `1`; `NA` = no seed, the old behaviour). The nested `Biomass_borealDataPrep` runs that rebuild `cohortDatas` and `pixelGroupMaps` draw random numbers (age and biomass models fit to a random subset, replacement land cover), so the same ELF got different vegetation on different machines. `seedVegInit` is passed as the nested module's `.seed` for `init`, so the vegetation is the same everywhere for a given seed and different for another one. The seed is in the cache key of the nested run, which re-runs once under the default. Needs `Biomass_borealDataPrep` with the seed in the keys of its inner `Cache()` calls (`Depends-on` there).

* `allFirePixelsByYear()` is one call of `fireSenseUtils::firePixelsByYear(fireRaster =, firePolys =, template =)`, which now also checks the raster's geometry, and `stopIfNonForestCannotBeYoung()` is `fireSenseUtils::stopIfNonForestCannotBeYoung()`, which `fireSense_dataPrepPredict` calls too. `addAnnualYoungAge()` builds its time-since-disturbance table with `fireSenseUtils::tsdTable()`. No change in results. Needs fireSenseUtils >= 0.2.3.9177 (#239).
Expand Down
14 changes: 10 additions & 4 deletions R/spreadFormula.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ spreadInteractionClimateFuel <- "climate:fuel"
#' The spread climate variable(s), `youngAge`, then the other covariates (fuel, non-forest), joined with
#' `" + "`; then, with `spreadInteractions = "climate:fuel"`, one interaction term (`climate:fuel`) for each climate
#' variable and each fuel covariate (`fireSenseUtils::spreadFuelCols()`: not `youngAge`, `nfLCC_*` or `treedWetland`),
#' climate first, after all the main effects. Without interactions the string is what it always was, so the cache keys
#' climate first, after all the main effects. With `climateSplit` the climate part of each is the between-year term
#' (`C_yr:fuel`); the within-year term (`C_dev`) does not interact. Without interactions the string is what it always was, so the cache keys
#' that hold it do not move.
#'
#' @param spreadCovariates the module's `spreadCovariates`: `"none"` gives `character()`, the null model; `"climate"`
Expand All @@ -37,15 +38,20 @@ spreadInteractionClimateFuel <- "climate:fuel"
#' @param spreadVars character; the spread climate variable(s).
#' @param vegColsForRHS character; the other covariates (not `youngAge` or the climate variables).
#' @param spreadInteractions the module's `spreadInteractions`; `NULL` or `character(0)` for none.
#' @param climateSplit the module's `spreadClimateSplit`: `TRUE` replaces each climate variable `C` by `C_yr` and
#' `C_dev` (`fireSenseUtils::climateSplitCols()`).
#' @return a character string, or `character()` for the null model.
spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character()) {
spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character(), climateSplit = FALSE) {
if (identical(spreadCovariates, "none")) return(character())
fuel <- if (spreadInteractionClimateFuel %in% spreadInteractions) fireSenseUtils::spreadFuelCols(vegColsForRHS)
climateTerms <- if (!identical(spreadCovariates, "fuel")) paste0(spreadVars, collapse = " + ")
climCols <- if (isTRUE(climateSplit)) fireSenseUtils::climateSplitCols(spreadVars) else spreadVars
## a split climate variable interacts through its between-year term only, never `_dev`
interClim <- if (isTRUE(climateSplit)) paste0(spreadVars, fireSenseUtils::climateSplitYrSuffix) else spreadVars
climateTerms <- if (!identical(spreadCovariates, "fuel")) paste0(climCols, collapse = " + ")
fuelTerms <- if (!identical(spreadCovariates, "climate"))
c(fireSenseUtils::youngAgeTxt, paste0(vegColsForRHS, collapse = " + "))
paste(c(climateTerms, fuelTerms,
paste(rep(spreadVars, each = length(fuel)), rep(fuel, times = length(spreadVars)), sep = ":")),
paste(rep(interClim, each = length(fuel)), rep(fuel, times = length(interClim)), sep = ":")),
collapse = " + ")
}

Expand Down
54 changes: 44 additions & 10 deletions fireSense_dataPrepFit.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ defineModule(sim, list(
reqdPkgs = list("data.table", "digest", "fastDummies", "googledrive", "httr2", "qs2", "Require",
"PredictiveEcology/reproducible@development (>= 3.2.1.9042)", # CacheGeo re-reads a changed local file
"PredictiveEcology/climateData@development (>= 2.2.3.9006)",
"PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9184)", # 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
"PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9186)", # 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)",
Expand Down Expand Up @@ -196,6 +196,7 @@ defineModule(sim, list(
"(bounded symmetrically, no sign constraint). Each is the product of the two covariates after each is",
"rescaled to 0-1 and centred (0 where `youngAge` cleared the fuel), so each main effect is the slope at the mean of the other covariate,",
"(`fireSenseUtils::spreadProbFromIntegerCovs()`), in the fit and in `fireSense_spreadPredict`.",
"With `spreadClimateSplit` the climate part is the between-year term: `CMD_yr:fuel`, never `CMD_dev`.",
"Needs climate and fuel covariates (`spreadCovariates = \"all\"`). Ignored if `sim$fireSense_spreadFormula` is supplied.",
"Needs a `fireSense_spreadFit` and a `fireSense_spreadPredict` that know interactions.")),
defineParameter("spreadIntercept", "logical", TRUE, NA, NA,
Expand All @@ -206,6 +207,16 @@ defineModule(sim, list(
"against the fuel and non-forest ones (ELF 13.1). `TRUE` is the default; `FALSE` gives `~ 0 + ...`.",
"Ignored if `sim$fireSense_spreadFormula` is supplied. Needs a `fireSense_spreadFit` and a",
"`fireSense_spreadPredict` that know the intercept.")),
defineParameter("spreadClimateSplit", "logical", FALSE, NA, NA,
paste("`FALSE` (the default): the spread formula has one term for the climate variable, `C`, as always",
"(the formula string is unchanged). `TRUE`: it has two, each with its own coefficient: `<C>_yr`, the year's",
"median of `C` over the ELF's burnable pixels (the same value for every pixel of a year: the year-to-year",
"swings), and `<C>_dev`, `C` minus that median (a pixel's departure from its year's median: the spatial",
"gradient within a year). One coefficient for both let the gradient, which is confounded with fuel, set the",
"year-to-year slope. The median is taken over the ELF's burnable pixels, not the fire buffers, so",
"`fireSense_spreadPredict` computes the same value from a year's climate layer",
"(`fireSenseUtils::splitSpreadClimate()`). `CMD*` and `MDC*` terms are bounded below by 0, as before; others",
"are not. Ignored if `sim$fireSense_spreadFormula` is supplied. A prediction needs no setting: `fireSense_spreadPredict` reads the terms from the ledger row. A ledger fit that is reused (`doFit` FALSE) keeps its own split, whatever this says.")),
defineParameter("targetFuelClasses", "numeric", 5, 1, 7,
"the target number of unique fuel classes when using semi-automated approach"),
defineParameter("useRasterizedFireForSpread", "logical", FALSE, NA, NA,
Expand Down Expand Up @@ -253,13 +264,14 @@ defineModule(sim, list(
fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps()))),
prepSpreadFitData = list(.cacheExtra = quote(c(list(
fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses,
fireSenseUtils::climateRasterToDataTable, fireSenseUtils::dataYearBefore,
fireSenseUtils::climateRasterToDataTable, fireSenseUtils::climateSplitCols, fireSenseUtils::climateSplitRefPixels,
fireSenseUtils::dataYearBefore,
fireSenseUtils::dataYearElement,
fireSenseUtils::dataYearFor, fireSenseUtils::emptySpreadCovariates,
fireSenseUtils::escapedFires, fireSenseUtils::escapeDefinitionOf, fireSenseUtils::fireCauseCodes, fireSenseUtils::fireSenseCovariatesCreate, fireSenseUtils::firePixelsByYear,
fireSenseUtils::harmonizeFireData, fireSenseUtils::lccFlammableShare,
fireSenseUtils::makeMutuallyExclusive, fireSenseUtils::rasterFireBufferDT,
fireSenseUtils::rasterFireSpreadPoints, fireSenseUtils::spreadFuelCols, fireSenseUtils::stopIfNonForestCannotBeYoung, fireSenseUtils::tsdTable,
fireSenseUtils::rasterFireSpreadPoints, fireSenseUtils::splitSpreadClimate, fireSenseUtils::spreadFuelCols, fireSenseUtils::stopIfNonForestCannotBeYoung, fireSenseUtils::tsdTable,
fireSenseUtils::youngAgeAtYear,
spreadFitPreRun = sim$spreadFitPreRun),
fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps())))),
Expand Down Expand Up @@ -666,6 +678,9 @@ Init <- function(sim) {
reuseOwnFit <- !is.na(ownRow) && !isTRUE(Par$doFit)
mod$spreadFormulaClimate <- if (reuseOwnFit) outs2[[ownRow]][["theseClimVarsNoUnderscore"]] else
sim$climateVariablesForFire[["spread"]]
## a reused fit keeps its split (or not): the formula follows the ledger row's coefficient names, not `spreadClimateSplit`
mod$spreadClimateSplit <- if (reuseOwnFit)
any(fireSenseUtils::isClimateSplitCol(colnames(sim$spreadFitPreRun$params[[ownRow]])))
## spread: the union, for prediction; ignition (xgboost) can use every one of them
sim$climateVariablesForFire <- addFitClimateVariablesForFire(sim$climateVariablesForFire, fitClimVars)

Expand Down Expand Up @@ -1072,7 +1087,9 @@ prepare_SpreadFit <- function(sim) {
## the formula lists them twice and terms() silently drops the duplicate, leaving one fewer term
## than parameters.
vegColsForRHS <- setdiff(vegCols, c(youngAgeTxt, spreadVars))
RHS <- spreadRHS(Par$spreadCovariates, spreadVars, vegColsForRHS, Par$spreadInteractions)
## a reused fit's split (mod$spreadClimateSplit) can differ from the parameter
checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates)
RHS <- spreadRHS(Par$spreadCovariates, spreadVars, vegColsForRHS, Par$spreadInteractions, useClimateSplit(mod, Par))

## this is a funny way to get years but avoids years with 0 fires
allYears <- unname(unlist(mod$allYears))
Expand Down Expand Up @@ -1101,7 +1118,7 @@ prepare_SpreadFit <- function(sim) {
annualCovariates <- annualSpreadCovariates(
pixelsByYear, spreadClimate, mod$allYears, burnablePixels,
tsds = sim$nonForest_timeSinceDisturbances, firePixelsByYear = firePixels,
cutoffForYoungAge = P(sim)$cutoffForYoungAge)
cutoffForYoungAge = P(sim)$cutoffForYoungAge, climateSplit = useClimateSplit(mod, Par))

# Confirm that YoungAge is the right amount. If there are "normal" amount of fires,
# then it should be < 0.2
Expand Down Expand Up @@ -1139,6 +1156,15 @@ prepare_SpreadFit <- function(sim) {
return(invisible(sim))
}

#' Is the spread climate split into a between-year and a within-year term?
#'
#' A fit reused from the ledger (`mod$spreadClimateSplit`, set by `Init()` from the row's coefficient names) keeps
#' its own split; otherwise the `spreadClimateSplit` parameter decides.
#'
#' @param mod,Par the module's `mod` and `Par`.
#' @return logical(1).
useClimateSplit <- function(mod, Par) isTRUE(mod$spreadClimateSplit %||% Par$spreadClimateSplit)

#' The annual spread covariates of the given pixels
#'
#' Climate of each fire year's pixels, then `youngAge`, grouped by data year. `prepare_SpreadFit()` calls it
Expand All @@ -1150,19 +1176,27 @@ prepare_SpreadFit <- function(sim) {
#' @param allYears list named by data year of the `year<year>` fire years that use it, as `mod$allYears`.
#' @param burnablePixels from [burnablePixelsByFireYear()]: only these pixels are kept.
#' @param tsds,firePixelsByYear,cutoffForYoungAge see [addAnnualYoungAge()].
#' @param climateSplit logical; `TRUE` replaces each climate variable `C` by `C_yr`, the year's median of `C` over
#' the burnable pixels, and `C_dev`, `C` minus it ([fireSenseUtils::splitSpreadClimate()]).
#' @return list named by data year of lists named `year<year>` (every year of `allYears`, empty if no pixels)
#' of data.tables of `pixelID`, the climate variables and `youngAge`.
#' of data.tables of `pixelID`, the climate variables (or their two terms) and `youngAge`.
annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnablePixels, tsds,
firePixelsByYear, cutoffForYoungAge) {
firePixelsByYear, cutoffForYoungAge, climateSplit = FALSE) {
## only these pixels of each year are read from the rasters; the join below keeps no others
climateDT <- climateRasterToDataTable(historicalClimateRasters = spreadClimate,
Index = pixelsByYear) |>
Cache(userTags = c("climateRasterToDataTable", names(spreadClimate)))
climateAt <- function(Index)
climateRasterToDataTable(historicalClimateRasters = spreadClimate, Index = Index) |>
Cache(userTags = c("climateRasterToDataTable", names(spreadClimate)))
climateDT <- climateAt(pixelsByYear)

fbl <- rbindlist(pixelsByYear, idcol = fireSenseUtils::yearTxt)
rmCols <- setdiff(colnames(fbl), c("pixelID", fireSenseUtils::yearTxt))
set(fbl, NULL, rmCols, NULL)
fbl <- climateDT[fbl, on = c(fireSenseUtils::yearTxt, "pixelID"), nomatch = NULL]
if (isTRUE(climateSplit)) {
## the median is over each year's burnable pixels of the ELF (what a prediction has), not over the fitted pixels
burnableIndex <- lapply(burnablePixels[names(pixelsByYear)], function(p) data.table(pixelID = fireSenseUtils::climateSplitRefPixels(p)))
fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), climateAt(burnableIndex), by = fireSenseUtils::yearTxt)
}

annuals <- split(fbl, by = fireSenseUtils::yearTxt, keep.by = FALSE)

Expand Down
2 changes: 1 addition & 1 deletion tests/testthat/test-metadata.R
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ test_that("parameters are the expected names", {
"forestedLCC", "fuelClassCol", "fuelCovariates", "heldOutFold", "igAggFactor",
"minBufferSize", "minBurnableFireSizeHa", "minCovariateProp", "nonflammableLCC",
"nonForestCanBeYoungAge", "scanfiVersion", "sppEquivCol", "spreadClimateCandidates", "spreadFitFilename",
"spreadFitGoogleDriveFolder", "skipUnusedFitPrep", "spreadCovariates", "spreadInteractions", "spreadIntercept", "targetFuelClasses",
"spreadFitGoogleDriveFolder", "skipUnusedFitPrep", "spreadClimateSplit", "spreadCovariates", "spreadInteractions", "spreadIntercept", "targetFuelClasses",
"useRasterizedFireForSpread", "seedVegInit", "wholeLandscapeSpreadCovariates", "whichModulesToPrepare"))
)
## a new user sees the plots; the tests set .plots = NA (helper-dataPrepBuild.R)
Expand Down
Loading