From 370cea516794e0293ec115c607a4ebf02a13f1ae Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 16 Nov 2026 17:26:46 -0700 Subject: [PATCH 1/6] New parameter spreadClimateSplit: the spread climate covariate as a between-year and a within-year term Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- NEWS.md | 2 + R/spreadFormula.R | 7 ++- fireSense_dataPrepFit.R | 39 +++++++++++---- tests/testthat/test-metadata.R | 2 +- .../test-wholeLandscapeSpreadCovariates.R | 47 +++++++++++++++++++ 5 files changed, 85 insertions(+), 12 deletions(-) diff --git a/NEWS.md b/NEWS.md index 92e9ef59..819a69cd 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,6 +8,8 @@ * 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. + * 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). diff --git a/R/spreadFormula.R b/R/spreadFormula.R index 16a38bb5..1b68dd1e 100644 --- a/R/spreadFormula.R +++ b/R/spreadFormula.R @@ -31,11 +31,14 @@ 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) - paste(c(paste0(spreadVars, collapse = " + "), fireSenseUtils::youngAgeTxt, + climCols <- if (isTRUE(climateSplit)) fireSenseUtils::climateSplitCols(spreadVars) else spreadVars + paste(c(paste0(climCols, collapse = " + "), fireSenseUtils::youngAgeTxt, paste0(vegColsForRHS, collapse = " + "), paste(rep(spreadVars, each = length(fuel)), rep(fuel, times = length(spreadVars)), sep = ":")), collapse = " + ") diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 8c83c747..7874300c 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -202,6 +202,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: `_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 `_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.")), defineParameter("targetFuelClasses", "numeric", 5, 1, 7, "the target number of unique fuel classes when using semi-automated approach"), defineParameter("useRasterizedFireForSpread", "logical", FALSE, NA, NA, @@ -249,13 +259,13 @@ 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::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())))), @@ -567,6 +577,9 @@ Init <- function(sim) { checkSpreadCovariates(Par$spreadCovariates, Par$spreadIntercept) checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates) + if (length(Par$spreadInteractions) && isTRUE(Par$spreadClimateSplit)) + stop("fireSense_dataPrepFit: spreadInteractions and spreadClimateSplit = TRUE cannot be combined yet: ", + "the interactions are built from the unsplit climate variable") sim$nonEscapedFireSizesHa <- nonEscapedFireSizes(sim$ignitionFirePoints, Par$escapeSizeHa) @@ -1068,7 +1081,7 @@ 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) + RHS <- spreadRHS(Par$spreadCovariates, spreadVars, vegColsForRHS, Par$spreadInteractions, Par$spreadClimateSplit) ## this is a funny way to get years but avoids years with 0 fires allYears <- unname(unlist(mod$allYears)) @@ -1097,7 +1110,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 = isTRUE(Par$spreadClimateSplit)) # Confirm that YoungAge is the right amount. If there are "normal" amount of fires, # then it should be < 0.2 @@ -1146,19 +1159,27 @@ prepare_SpreadFit <- function(sim) { #' @param allYears list named by data year of the `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` (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 = p)) + fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), climateAt(burnableIndex), by = fireSenseUtils::yearTxt) + } annuals <- split(fbl, by = fireSenseUtils::yearTxt, keep.by = FALSE) diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index 0c06d7ed..c681ebfa 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -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) diff --git a/tests/testthat/test-wholeLandscapeSpreadCovariates.R b/tests/testthat/test-wholeLandscapeSpreadCovariates.R index e0a74f27..58950b71 100644 --- a/tests/testthat/test-wholeLandscapeSpreadCovariates.R +++ b/tests/testthat/test-wholeLandscapeSpreadCovariates.R @@ -71,3 +71,50 @@ test_that("prepare_SpreadFit picks the buffer or the burnable pixels by the para expect_match(body, "pixelsByYear <- if (wholeSpreadCovariates)", fixed = TRUE) expect_equal(lengths(regmatches(body, gregexpr("annualSpreadCovariates(", body, fixed = TRUE))), 1L) # one call, whichever pixels }) + +test_that("spreadClimateSplit: the annual tables have CMD_yr (the year's burnable-pixel median) and CMD_dev (CMD minus it)", { + skip_if_not_installed("fireSenseUtils") + withr::local_options(reproducible.cachePath = withr::local_tempdir(), reproducible.useMemoise = FALSE) + f <- wholeFixture() + run <- function(split) do.call(c, unname(annualSpreadCovariates(f$buffers, f$clim, f$allYears, f$burnablePixels, + tsds = f$tsds, firePixelsByYear = f$fires, cutoffForYoungAge = 15, + climateSplit = split))) + plain <- run(FALSE) + split <- run(TRUE) + expect_identical(names(split), names(plain)) + for (fy in names(plain)) { + expect_identical(names(plain[[fy]]), c("pixelID", "CMD", "youngAge")) + expect_true(all(c("pixelID", "CMD_yr", "CMD_dev", "youngAge") %in% names(split[[fy]]))) + expect_false("CMD" %in% names(split[[fy]])) + expect_identical(split[[fy]]$pixelID, plain[[fy]]$pixelID) + } + ## pixels 1:16 burn: their values are y + 1:16, median y + 8.5 (not that of the fitted buffer pixels, which differ) + for (fy in c("year2001", "year2003", "year2004")) { + y <- as.integer(sub("year", "", fy)) + expect_equal(split[[fy]]$CMD_yr, rep(y + 8.5, nrow(split[[fy]]))) + expect_equal(split[[fy]]$CMD_dev, plain[[fy]]$CMD - (y + 8.5)) + } + expect_false(isTRUE(all.equal(split$year2001$CMD_yr[1], median(plain$year2001$CMD)))) + expect_identical(nrow(split$year2002), 0L) +}) + +test_that("spreadClimateSplit is FALSE by default and the formula is then the same string; TRUE has the two terms", { + md <- SpaDES.core::moduleMetadata(module = moduleName, path = modulePath) + expect_false(md$parameters$default[md$parameters$paramName == "spreadClimateSplit"][[1]]) + + stmts <- as.list(body(prepare_SpreadFit))[-1] + txt <- vapply(stmts, function(s) paste(deparse(s), collapse = " "), character(1)) + idx <- sort(unique(unlist(lapply(c("^spreadVars <-", "^vegColsForRHS <-", "^RHS <-"), grep, x = txt)))) + formulaFor <- function(Par) { + env <- new.env(parent = environment(prepare_SpreadFit)) + env$sim <- new.env(); env$sim$climateVariablesForFire <- list(spread = "CMD") + env$mod <- new.env(); env$Par <- Par + env$vegCols <- c("class1", "class2") + for (i in idx) eval(stmts[[i]], env) + spreadFormula(env$RHS, Par$spreadIntercept) + } + expect_identical(formulaFor(list(spreadIntercept = TRUE)), "~ 1 + CMD + youngAge + class1 + class2") + expect_identical(formulaFor(list(spreadIntercept = TRUE, spreadClimateSplit = FALSE)), "~ 1 + CMD + youngAge + class1 + class2") + expect_identical(formulaFor(list(spreadIntercept = TRUE, spreadClimateSplit = TRUE)), + "~ 1 + CMD_yr + CMD_dev + youngAge + class1 + class2") +}) From cea86d1e1ca40c3d727925480ee0263ad02b935d Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 16 Nov 2026 17:36:09 -0700 Subject: [PATCH 2/6] Reused ledger fits keep their split; the median's reference pixels come from fireSenseUtils::climateSplitRefPixels(); cell labels from elfCellLabels() Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- NEWS.md | 2 +- fireSense_dataPrepFit.R | 23 ++++++++--- tests/testthat/test-spreadClimateOwnELF.R | 39 +++++++++++++++++++ .../test-wholeLandscapeSpreadCovariates.R | 9 ++++- 4 files changed, 65 insertions(+), 8 deletions(-) diff --git a/NEWS.md b/NEWS.md index 819a69cd..5596c5b6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -8,7 +8,7 @@ * 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. +* 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()`. * 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). diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 7874300c..fcb85c5d 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -211,7 +211,7 @@ defineModule(sim, list( "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.")), + "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, @@ -259,7 +259,8 @@ defineModule(sim, list( fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps()))), prepSpreadFitData = list(.cacheExtra = quote(c(list( fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, - fireSenseUtils::climateRasterToDataTable, fireSenseUtils::climateSplitCols, 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, @@ -675,6 +676,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) @@ -1081,7 +1085,7 @@ 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, Par$spreadClimateSplit) + 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)) @@ -1110,7 +1114,7 @@ prepare_SpreadFit <- function(sim) { annualCovariates <- annualSpreadCovariates( pixelsByYear, spreadClimate, mod$allYears, burnablePixels, tsds = sim$nonForest_timeSinceDisturbances, firePixelsByYear = firePixels, - cutoffForYoungAge = P(sim)$cutoffForYoungAge, climateSplit = isTRUE(Par$spreadClimateSplit)) + 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 @@ -1148,6 +1152,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 @@ -1177,7 +1190,7 @@ annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnab 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 = p)) + burnableIndex <- lapply(burnablePixels[names(pixelsByYear)], function(p) data.table(pixelID = fireSenseUtils::climateSplitRefPixels(p))) fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), climateAt(burnableIndex), by = fireSenseUtils::yearTxt) } diff --git a/tests/testthat/test-spreadClimateOwnELF.R b/tests/testthat/test-spreadClimateOwnELF.R index be743fcb..dbcb5aa0 100644 --- a/tests/testthat/test-spreadClimateOwnELF.R +++ b/tests/testthat/test-spreadClimateOwnELF.R @@ -58,3 +58,42 @@ test_that("the spread formula has this ELF's climate variable only, not the ledg expect_identical(env$sim$fireSense_spreadFormula, "~ 0 + CMD + youngAge + fuelA") expect_setequal(env$sim$climateVariablesForFire$spread, c("CMD", "CMDsm")) }) + +## spreadClimateSplit: a reused ledger fit keeps its own split, whatever the parameter says +splitLedger <- function() { + ledger <- ownAndNeighbourLedger() + own <- ledger$params[[2]] + names(own)[names(own) == "CMD"] <- "CMD_yr" + own$CMD_dev <- 0 + ledger$params[[2]] <- own + ledger +} +initSplit <- function(ledger, doFit, parSplit) { + e <- ledgerInitEnv(ledger) + e$sim$.ELFind <- "4.2.2" + e$sim$climateVariablesForFire <- list(ignition = c("CMD", "cumMDC", "CMDsm", "CMDsp"), spread = "auto") + e$Par$doFit <- doFit + e$Par$spreadClimateSplit <- parSplit + for (s in initBody()) suppressMessages(eval(s, e)) + e +} + +test_that("a reused fit with split terms rebuilds the split formula even when spreadClimateSplit is FALSE", { + e <- initSplit(splitLedger(), doFit = NA, parSplit = FALSE) + expect_identical(e$mod$spreadFormulaClimate, "CMD") # the variable, found from CMD_yr and CMD_dev + expect_true(e$mod$spreadClimateSplit) + expect_true(useClimateSplit(e$mod, e$Par)) +}) + +test_that("a reused fit without split terms stays unsplit, also when spreadClimateSplit is TRUE", { + e <- initSplit(ownAndNeighbourLedger(), doFit = NA, parSplit = TRUE) + expect_false(e$mod$spreadClimateSplit) + expect_false(useClimateSplit(e$mod, e$Par)) +}) + +test_that("a refit follows the parameter", { + e <- initSplit(splitLedger(), doFit = TRUE, parSplit = FALSE) + expect_null(e$mod$spreadClimateSplit) + expect_false(useClimateSplit(e$mod, e$Par)) + expect_true(useClimateSplit(e$mod, list(spreadClimateSplit = TRUE))) +}) diff --git a/tests/testthat/test-wholeLandscapeSpreadCovariates.R b/tests/testthat/test-wholeLandscapeSpreadCovariates.R index 58950b71..6b69eff7 100644 --- a/tests/testthat/test-wholeLandscapeSpreadCovariates.R +++ b/tests/testthat/test-wholeLandscapeSpreadCovariates.R @@ -105,10 +105,10 @@ test_that("spreadClimateSplit is FALSE by default and the formula is then the sa stmts <- as.list(body(prepare_SpreadFit))[-1] txt <- vapply(stmts, function(s) paste(deparse(s), collapse = " "), character(1)) idx <- sort(unique(unlist(lapply(c("^spreadVars <-", "^vegColsForRHS <-", "^RHS <-"), grep, x = txt)))) - formulaFor <- function(Par) { + formulaFor <- function(Par, modSplit = NULL) { env <- new.env(parent = environment(prepare_SpreadFit)) env$sim <- new.env(); env$sim$climateVariablesForFire <- list(spread = "CMD") - env$mod <- new.env(); env$Par <- Par + env$mod <- new.env(); env$mod$spreadClimateSplit <- modSplit; env$Par <- Par env$vegCols <- c("class1", "class2") for (i in idx) eval(stmts[[i]], env) spreadFormula(env$RHS, Par$spreadIntercept) @@ -117,4 +117,9 @@ test_that("spreadClimateSplit is FALSE by default and the formula is then the sa expect_identical(formulaFor(list(spreadIntercept = TRUE, spreadClimateSplit = FALSE)), "~ 1 + CMD + youngAge + class1 + class2") expect_identical(formulaFor(list(spreadIntercept = TRUE, spreadClimateSplit = TRUE)), "~ 1 + CMD_yr + CMD_dev + youngAge + class1 + class2") + ## a reused ledger fit's split (mod$spreadClimateSplit, from Init()) wins over the parameter + expect_identical(formulaFor(list(spreadIntercept = TRUE, spreadClimateSplit = FALSE), modSplit = TRUE), + "~ 1 + CMD_yr + CMD_dev + youngAge + class1 + class2") + expect_identical(formulaFor(list(spreadIntercept = TRUE, spreadClimateSplit = TRUE), modSplit = FALSE), + "~ 1 + CMD + youngAge + class1 + class2") }) From bfe1cb5ca25b27152db6fd16e530c3d8ad3d000e Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 16:43:41 -0700 Subject: [PATCH 3/6] fireSenseUtils floor 0.2.3.9185 (fireSenseUtils#244) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- fireSense_dataPrepFit.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index fcb85c5d..259dbf91 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -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.9185)", # 9185: splitSpreadClimate(), climateSplitCols(), climateSplitRefPixels(), isClimateSplitCol() (fireSenseUtils#244, version not yet released; CHECK after it merges); 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)", From 9d70fbecd512e6f729022f6f11910b3859a068d5 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 17:11:01 -0700 Subject: [PATCH 4/6] spreadInteractions x split climate: one check in checkSpreadInteractions(), also for a reused split fit Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- R/spreadFormula.R | 7 +++++- fireSense_dataPrepFit.R | 7 +++--- tests/testthat/test-spreadInteractions.R | 30 ++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/R/spreadFormula.R b/R/spreadFormula.R index 1b68dd1e..bf1961f2 100644 --- a/R/spreadFormula.R +++ b/R/spreadFormula.R @@ -70,13 +70,18 @@ checkSpreadCovariates <- function(spreadCovariates, spreadIntercept) { #' #' @param spreadInteractions the module's `spreadInteractions`. #' @param spreadCovariates the module's `spreadCovariates`. +#' @param climateSplit whether the fit splits the climate variable (`spreadClimateSplit`, or a reused fit's split, see +#' `useClimateSplit()`); the interactions are built from the unsplit variable, so the two cannot be combined yet. #' @return `NULL`, invisibly; stops on a value that is not allowed. -checkSpreadInteractions <- function(spreadInteractions, spreadCovariates) { +checkSpreadInteractions <- function(spreadInteractions, spreadCovariates, climateSplit = FALSE) { if (length(spreadInteractions) && (!is.character(spreadInteractions) || !all(spreadInteractions %in% spreadInteractionClimateFuel))) stop("fireSense_dataPrepFit: parameter 'spreadInteractions' must be character(0) or \"", spreadInteractionClimateFuel, "\"; got: ", paste(format(spreadInteractions), collapse = ", ")) if (length(spreadInteractions) && identical(spreadCovariates, "none")) stop("fireSense_dataPrepFit: spreadInteractions = \"", spreadInteractionClimateFuel, "\" needs covariates: ", "the null model (spreadCovariates = \"none\") has none") + if (length(spreadInteractions) && isTRUE(climateSplit)) + stop("fireSense_dataPrepFit: spreadInteractions and spreadClimateSplit = TRUE cannot be combined yet: ", + "the interactions are built from the unsplit climate variable") invisible(NULL) } diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 259dbf91..f021360b 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -577,10 +577,7 @@ Init <- function(sim) { fireSenseUtils::escapeDefinitionOf(sim) checkSpreadCovariates(Par$spreadCovariates, Par$spreadIntercept) - checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates) - if (length(Par$spreadInteractions) && isTRUE(Par$spreadClimateSplit)) - stop("fireSense_dataPrepFit: spreadInteractions and spreadClimateSplit = TRUE cannot be combined yet: ", - "the interactions are built from the unsplit climate variable") + checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates, Par$spreadClimateSplit) sim$nonEscapedFireSizesHa <- nonEscapedFireSizes(sim$ignitionFirePoints, Par$escapeSizeHa) @@ -1085,6 +1082,8 @@ 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)) + ## a reused fit's split (mod$spreadClimateSplit) can differ from the parameter + checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates, useClimateSplit(mod, Par)) 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 diff --git a/tests/testthat/test-spreadInteractions.R b/tests/testthat/test-spreadInteractions.R index 7e4a0bf7..f96bd6e6 100644 --- a/tests/testthat/test-spreadInteractions.R +++ b/tests/testthat/test-spreadInteractions.R @@ -41,6 +41,32 @@ test_that("checkSpreadInteractions() allows character(0) and 'climate:fuel', and expect_error(checkSpreadInteractions("climate:fuel", "none"), "needs covariates") }) +test_that("checkSpreadInteractions() refuses interactions with a split climate variable, and allows a split without them", { + expect_error(checkSpreadInteractions("climate:fuel", "all", climateSplit = TRUE), "cannot be combined") + expect_null(checkSpreadInteractions("climate:fuel", "all", climateSplit = FALSE)) + expect_null(checkSpreadInteractions(character(0), "all", climateSplit = TRUE)) + expect_null(checkSpreadInteractions(NULL, "all", climateSplit = TRUE)) +}) + +test_that("prepare_SpreadFit() refuses interactions for a reused fit that is split, whatever spreadClimateSplit says", { + stmts <- as.list(body(prepare_SpreadFit))[-1] + txt <- vapply(stmts, function(s) paste(deparse(s), collapse = " "), character(1)) + idx <- sort(unique(unlist(lapply(c("^spreadVars <-", "^vegColsForRHS <-", "^checkSpreadInteractions", "^RHS <-"), grep, x = txt)))) + build <- function(modSplit, parSplit) { + env <- new.env(parent = environment(prepare_SpreadFit)) + env$sim <- new.env(); env$sim$climateVariablesForFire <- list(spread = "CMD") + env$mod <- new.env(); env$mod$spreadClimateSplit <- modSplit + env$Par <- list(spreadIntercept = TRUE, spreadCovariates = "all", spreadInteractions = "climate:fuel", + spreadClimateSplit = parSplit) + env$vegCols <- c("class1", "class2") + for (i in idx) eval(stmts[[i]], env) + env$RHS + } + expect_error(build(modSplit = TRUE, parSplit = FALSE), "cannot be combined") + expect_error(build(modSplit = NULL, parSplit = TRUE), "cannot be combined") + expect_match(build(modSplit = FALSE, parSplit = TRUE), "CMD:class1", fixed = TRUE) +}) + test_that("the module defines spreadInteractions, character(0) by default, and Init() checks it", { def <- Filter(function(x) is.call(x) && identical(x[[1]], as.name("defineModule")), parse(testthat::test_path("..", "..", "fireSense_dataPrepFit.R"), keep.source = FALSE)) @@ -49,8 +75,8 @@ test_that("the module defines spreadInteractions, character(0) by default, and I expect_false(is.na(i)) expect_identical(params$paramClass[[i]], "character") expect_identical(params$default[[i]], character(0)) - expect_match(paste(deparse(body(Init)), collapse = "\n"), - "checkSpreadInteractions\\(Par\\$spreadInteractions, Par\\$spreadCovariates\\)") + expect_match(paste(deparse(body(Init)), collapse = " "), + "checkSpreadInteractions\\(Par\\$spreadInteractions, Par\\$spreadCovariates,\\s+Par\\$spreadClimateSplit\\)") }) test_that("prepare_SpreadFit() gives the formula it always gave, and with 'climate:fuel' the interactions of the fuels it keeps", { From b85fd0da023b0930eff276e2e14ac1a56ae7e11c Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 21:11:32 -0700 Subject: [PATCH 5/6] fireSenseUtils floor 0.2.3.9186 (#244 merged as 9186; 9185 is #256) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- fireSense_dataPrepFit.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index f021360b..36748ed6 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -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.9185)", # 9185: splitSpreadClimate(), climateSplitCols(), climateSplitRefPixels(), isClimateSplitCol() (fireSenseUtils#244, version not yet released; CHECK after it merges); 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)", From 9b82a86343e786073e14f4c652d0b98baee15ae0 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 22:49:34 -0700 Subject: [PATCH 6/6] spreadInteractions x spreadClimateSplit: the interaction is built from the between-year term (CMD_yr:fuel), never _dev; checkSpreadInteractions() no longer stops Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 ++ R/spreadFormula.R | 14 +++++------ fireSense_dataPrepFit.R | 5 ++-- tests/testthat/test-spreadInteractions.R | 30 +++++++++++++++++------- 4 files changed, 32 insertions(+), 19 deletions(-) diff --git a/NEWS.md b/NEWS.md index 5596c5b6..fa577cc8 100644 --- a/NEWS.md +++ b/NEWS.md @@ -10,6 +10,8 @@ * 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). diff --git a/R/spreadFormula.R b/R/spreadFormula.R index bf1961f2..b8d638e7 100644 --- a/R/spreadFormula.R +++ b/R/spreadFormula.R @@ -24,7 +24,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. @@ -38,9 +39,11 @@ spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInterac if (identical(spreadCovariates, "none")) return(character()) fuel <- if (spreadInteractionClimateFuel %in% spreadInteractions) fireSenseUtils::spreadFuelCols(vegColsForRHS) 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 paste(c(paste0(climCols, collapse = " + "), fireSenseUtils::youngAgeTxt, paste0(vegColsForRHS, collapse = " + "), - 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 = " + ") } @@ -70,18 +73,13 @@ checkSpreadCovariates <- function(spreadCovariates, spreadIntercept) { #' #' @param spreadInteractions the module's `spreadInteractions`. #' @param spreadCovariates the module's `spreadCovariates`. -#' @param climateSplit whether the fit splits the climate variable (`spreadClimateSplit`, or a reused fit's split, see -#' `useClimateSplit()`); the interactions are built from the unsplit variable, so the two cannot be combined yet. #' @return `NULL`, invisibly; stops on a value that is not allowed. -checkSpreadInteractions <- function(spreadInteractions, spreadCovariates, climateSplit = FALSE) { +checkSpreadInteractions <- function(spreadInteractions, spreadCovariates) { if (length(spreadInteractions) && (!is.character(spreadInteractions) || !all(spreadInteractions %in% spreadInteractionClimateFuel))) stop("fireSense_dataPrepFit: parameter 'spreadInteractions' must be character(0) or \"", spreadInteractionClimateFuel, "\"; got: ", paste(format(spreadInteractions), collapse = ", ")) if (length(spreadInteractions) && identical(spreadCovariates, "none")) stop("fireSense_dataPrepFit: spreadInteractions = \"", spreadInteractionClimateFuel, "\" needs covariates: ", "the null model (spreadCovariates = \"none\") has none") - if (length(spreadInteractions) && isTRUE(climateSplit)) - stop("fireSense_dataPrepFit: spreadInteractions and spreadClimateSplit = TRUE cannot be combined yet: ", - "the interactions are built from the unsplit climate variable") invisible(NULL) } diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 36748ed6..cd1ad2fa 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -192,6 +192,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 covariates (not `spreadCovariates = \"none\"`). Ignored if `sim$fireSense_spreadFormula` is supplied.", "Needs a `fireSense_spreadFit` and a `fireSense_spreadPredict` that know interactions.")), defineParameter("spreadIntercept", "logical", TRUE, NA, NA, @@ -577,7 +578,7 @@ Init <- function(sim) { fireSenseUtils::escapeDefinitionOf(sim) checkSpreadCovariates(Par$spreadCovariates, Par$spreadIntercept) - checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates, Par$spreadClimateSplit) + checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates) sim$nonEscapedFireSizesHa <- nonEscapedFireSizes(sim$ignitionFirePoints, Par$escapeSizeHa) @@ -1083,7 +1084,7 @@ prepare_SpreadFit <- function(sim) { ## than parameters. vegColsForRHS <- setdiff(vegCols, c(youngAgeTxt, spreadVars)) ## a reused fit's split (mod$spreadClimateSplit) can differ from the parameter - checkSpreadInteractions(Par$spreadInteractions, Par$spreadCovariates, useClimateSplit(mod, Par)) + 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 diff --git a/tests/testthat/test-spreadInteractions.R b/tests/testthat/test-spreadInteractions.R index f96bd6e6..3def6771 100644 --- a/tests/testthat/test-spreadInteractions.R +++ b/tests/testthat/test-spreadInteractions.R @@ -41,14 +41,25 @@ test_that("checkSpreadInteractions() allows character(0) and 'climate:fuel', and expect_error(checkSpreadInteractions("climate:fuel", "none"), "needs covariates") }) -test_that("checkSpreadInteractions() refuses interactions with a split climate variable, and allows a split without them", { - expect_error(checkSpreadInteractions("climate:fuel", "all", climateSplit = TRUE), "cannot be combined") - expect_null(checkSpreadInteractions("climate:fuel", "all", climateSplit = FALSE)) - expect_null(checkSpreadInteractions(character(0), "all", climateSplit = TRUE)) - expect_null(checkSpreadInteractions(NULL, "all", climateSplit = TRUE)) +test_that("spreadRHS() with a split climate variable interacts the between-year term (_yr) only, never _dev", { + expect_identical( + spreadRHS("all", "CMD", c("fuelA", "fuelB"), "climate:fuel", climateSplit = TRUE), + "CMD_yr + CMD_dev + youngAge + fuelA + fuelB + CMD_yr:fuelA + CMD_yr:fuelB") + expect_identical( + spreadRHS("all", c("CMD", "Tmax"), "fuelA", "climate:fuel", climateSplit = TRUE), + "CMD_yr + CMD_dev + Tmax_yr + Tmax_dev + youngAge + fuelA + CMD_yr:fuelA + Tmax_yr:fuelA") + rhs <- spreadRHS("all", "CMD", c("fuelA", "fuelB"), "climate:fuel", climateSplit = TRUE) + expect_false(grepl("_dev:|:[A-Za-z]*_dev", rhs)) + ## the design columns: the interaction's source columns include CMD_yr and the fuels, not CMD + cols <- fireSenseUtils::spreadDesignCols(spreadFormula(rhs, TRUE)) + expect_identical(fireSenseUtils::spreadInteractionCols(cols), c("CMD_yr:fuelA", "CMD_yr:fuelB")) + expect_false("CMD" %in% fireSenseUtils::spreadSourceCols(cols)) + ## a split without interactions, and interactions without a split, are as before + expect_identical(spreadRHS("all", "CMD", "fuelA", character(0), climateSplit = TRUE), "CMD_yr + CMD_dev + youngAge + fuelA") + expect_identical(spreadRHS("all", "CMD", "fuelA", "climate:fuel", climateSplit = FALSE), "CMD + youngAge + fuelA + CMD:fuelA") }) -test_that("prepare_SpreadFit() refuses interactions for a reused fit that is split, whatever spreadClimateSplit says", { +test_that("prepare_SpreadFit() builds _yr:fuel interactions for a split fit, whatever spreadClimateSplit says for a reused fit", { stmts <- as.list(body(prepare_SpreadFit))[-1] txt <- vapply(stmts, function(s) paste(deparse(s), collapse = " "), character(1)) idx <- sort(unique(unlist(lapply(c("^spreadVars <-", "^vegColsForRHS <-", "^checkSpreadInteractions", "^RHS <-"), grep, x = txt)))) @@ -62,8 +73,9 @@ test_that("prepare_SpreadFit() refuses interactions for a reused fit that is spl for (i in idx) eval(stmts[[i]], env) env$RHS } - expect_error(build(modSplit = TRUE, parSplit = FALSE), "cannot be combined") - expect_error(build(modSplit = NULL, parSplit = TRUE), "cannot be combined") + want <- "CMD_yr + CMD_dev + youngAge + class1 + class2 + CMD_yr:class1 + CMD_yr:class2" + expect_identical(build(modSplit = TRUE, parSplit = FALSE), want) + expect_identical(build(modSplit = NULL, parSplit = TRUE), want) expect_match(build(modSplit = FALSE, parSplit = TRUE), "CMD:class1", fixed = TRUE) }) @@ -76,7 +88,7 @@ test_that("the module defines spreadInteractions, character(0) by default, and I expect_identical(params$paramClass[[i]], "character") expect_identical(params$default[[i]], character(0)) expect_match(paste(deparse(body(Init)), collapse = " "), - "checkSpreadInteractions\\(Par\\$spreadInteractions, Par\\$spreadCovariates,\\s+Par\\$spreadClimateSplit\\)") + "checkSpreadInteractions\\(Par\\$spreadInteractions, Par\\$spreadCovariates\\)") }) test_that("prepare_SpreadFit() gives the formula it always gave, and with 'climate:fuel' the interactions of the fuels it keeps", {