From 7b51e28df55586ef1d0c520ed5cb56a6c60eee68 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 25 Nov 2026 16:15:26 -0700 Subject: [PATCH 1/4] Climate hinge term for the spread climate covariate Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 + R/spreadFormula.R | 6 +- fireSense_dataPrepFit.R | 66 +++++++++-- tests/testthat/helper-spreadFixtures.R | 32 +++++ tests/testthat/test-metadata.R | 5 +- tests/testthat/test-spreadClimateHinge.R | 111 ++++++++++++++++++ tests/testthat/test-spreadClimateOwnELF.R | 11 -- .../test-wholeLandscapeSpreadCovariates.R | 18 --- 8 files changed, 209 insertions(+), 42 deletions(-) create mode 100644 tests/testthat/helper-spreadFixtures.R create mode 100644 tests/testthat/test-spreadClimateHinge.R diff --git a/NEWS.md b/NEWS.md index a81d70a..5e3ece0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) +* New parameter `spreadClimateHinge` (`FALSE` by default: nothing changes). `TRUE` adds a covariate `_hinge = pmax(0, C - k)` for each spread climate variable `C`, with its own coefficient, so the climate response can steepen in dry years; `k` is the ELF's median of `C` over the burnable pixels of all the fit years. The knots are in `sim$climateHingeKnots`, which `fireSense_spreadFit` writes to the ledger row, and `fireSense_spreadPredict` builds the term from them. A reused ledger fit keeps its own hinge terms and knots. The code is `fireSenseUtils::climateHingeKnots()`, `addClimateHinge()` and `climateHingeCols()`, in the `prepSpreadFitData` cache key. Needs `fireSense_spreadFit`, `fireSense_spreadPredict` and fireSenseUtils with the hinge (fireSenseUtils >= 0.2.3.9193, version to be set after it merges). + * No prescribed burn is fitted: the spread fit's fire polygons and the ignition fit's NFDB points are selected by `fireSenseUtils::modelledFires()` (the causes of `fireCauses`, and no NBAC `PRESCRIBED`, NFDB `PRESCRIBED`, `FIRE_TYPE` or `H-PB` fire). It replaces the module's `polysOfCauses()`. Needs fireSenseUtils with `modelledFires()`; spread and ignition fits made before this included the prescribed fires of the wanted causes. * `spreadCovariates` takes two more values, `"climate"` (the intercept and the spread climate variable(s) only) and `"fuel"` (the intercept, `youngAge`, fuel and non-forest classes), beside `"all"` (default) and `"none"`, for an ANOVA of what drives spread-fit quality. The covariate tables are still made. `spreadInteractions = "climate:fuel"` stops with `"fuel"` and `"climate"` (it needs both). The default is unchanged. diff --git a/R/spreadFormula.R b/R/spreadFormula.R index 2530eb8..d83417b 100644 --- a/R/spreadFormula.R +++ b/R/spreadFormula.R @@ -40,11 +40,15 @@ spreadInteractionClimateFuel <- "climate:fuel" #' @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()`). +#' @param climateHinge `TRUE` adds each variable's hinge term (`C_hinge`, `fireSenseUtils::climateHingeCols()`) after its +#' other climate terms; it does not interact. #' @return a character string, or `character()` for the null model. -spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character(), climateSplit = FALSE) { +spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character(), climateSplit = FALSE, + climateHinge = FALSE) { if (identical(spreadCovariates, "none")) return(character()) fuel <- if (spreadInteractionClimateFuel %in% spreadInteractions) fireSenseUtils::spreadFuelCols(vegColsForRHS) climCols <- if (isTRUE(climateSplit)) fireSenseUtils::climateSplitCols(spreadVars) else spreadVars + if (isTRUE(climateHinge)) climCols <- c(climCols, fireSenseUtils::climateHingeCols(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 = " + ") diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index e6ad689..a5ca75e 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.9190)", # 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 + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9193)", # 9193 (placeholder until the climate hinge PR (fireSenseUtils) merges and is bumped): climateHingeKnots(), addClimateHinge(), climateHingeCols(), ledgerClimateHingeKnots(), isClimateHingeCol(); 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)", @@ -217,6 +217,16 @@ defineModule(sim, list( "`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("spreadClimateHinge", "logical", FALSE, NA, NA, + paste("`FALSE` (the default): the spread formula is unchanged. `TRUE`: it has an extra term for each spread", + "climate variable `C`, `_hinge = pmax(0, C - k)`, with its own coefficient, so the climate response", + "can steepen (or flatten) above `k` (dry years); `C` keeps its own term. `k` is the ELF's median of `C`", + "over the burnable pixels in all the fit's years, one number for the ELF. It is stored in the ledger row", + "(`fireSenseUtils::spreadFitClimateHingeKnotsTxt`), and `fireSense_spreadPredict` builds the term from it", + "(`fireSenseUtils::addClimateHinge()`). With `spreadClimateSplit` the hinge is of `C`, the pixel's value,", + "beside the `_yr` and `_dev` terms. Ignored if `sim$fireSense_spreadFormula` is supplied. A prediction needs no", + "setting: it reads the knots from the ledger row. A ledger fit that is reused (`doFit` FALSE) keeps its own", + "hinge terms and knots, whatever this says. Needs a `fireSense_spreadFit` that writes the knots.")), defineParameter("targetFuelClasses", "numeric", 5, 1, 7, "the target number of unique fuel classes when using semi-automated approach"), defineParameter("useRasterizedFireForSpread", "logical", FALSE, NA, NA, @@ -264,7 +274,8 @@ defineModule(sim, list( fireSenseUtils::rasterFireSpreadPoints, spreadFitPreRun = sim$spreadFitPreRun), fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps()))), prepSpreadFitData = list(.cacheExtra = quote(c(list( - fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, + fireSenseUtils::addClimateHinge, fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, + fireSenseUtils::climateHingeCols, fireSenseUtils::climateHingeKnots, fireSenseUtils::climateRasterToDataTable, fireSenseUtils::climateSplitCols, fireSenseUtils::climateSplitRefPixels, fireSenseUtils::dataYearBefore, fireSenseUtils::dataYearElement, @@ -416,6 +427,10 @@ defineModule(sim, list( createsOutput("fireSense_annualSpreadFitCovariates", "list", "List of data.tables, one per fire year, of `pixelID` and the spread climate covariates in the fire buffers (every flammable pixel with `wholeLandscapeSpreadCovariates`).", events = "prepSpreadFitData"), + createsOutput("climateHingeKnots", "list", + paste("With `spreadClimateHinge`, the knot of each spread climate variable's hinge term (`fireSenseUtils::climateHingeKnots()`),", + "which `fireSense_spreadFit` stores in the ledger row; `NULL` without hinge terms."), + events = "prepSpreadFitData"), createsOutput("fireSense_escapeCovariates", "data.table", "ignition covariates with added column of escapes", events = "prepEscapeFitData"), @@ -682,6 +697,11 @@ Init <- function(sim) { ## 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]]))) + ## a reused fit keeps its hinge terms, and the knots it was fitted with + mod$spreadClimateHinge <- if (reuseOwnFit) + any(fireSenseUtils::isClimateHingeCol(colnames(sim$spreadFitPreRun$params[[ownRow]]))) + mod$climateHingeKnots <- if (isTRUE(mod$spreadClimateHinge)) + fireSenseUtils::ledgerClimateHingeKnots(sim$spreadFitPreRun, ownRow) ## spread: the union, for prediction; ignition (xgboost) can use every one of them sim$climateVariablesForFire <- addFitClimateVariablesForFire(sim$climateVariablesForFire, fitClimVars) @@ -1090,7 +1110,8 @@ prepare_SpreadFit <- function(sim) { vegColsForRHS <- setdiff(vegCols, c(youngAgeTxt, spreadVars)) ## 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)) + RHS <- spreadRHS(Par$spreadCovariates, spreadVars, vegColsForRHS, Par$spreadInteractions, useClimateSplit(mod, Par), + climateHinge = useClimateHinge(mod, Par)) ## this is a funny way to get years but avoids years with 0 fires allYears <- unname(unlist(mod$allYears)) @@ -1119,7 +1140,9 @@ prepare_SpreadFit <- function(sim) { annualCovariates <- annualSpreadCovariates( pixelsByYear, spreadClimate, mod$allYears, burnablePixels, tsds = sim$nonForest_timeSinceDisturbances, firePixelsByYear = firePixels, - cutoffForYoungAge = P(sim)$cutoffForYoungAge, climateSplit = useClimateSplit(mod, Par)) + cutoffForYoungAge = P(sim)$cutoffForYoungAge, climateSplit = useClimateSplit(mod, Par), + climateHinge = if (useClimateHinge(mod, Par)) mod$climateHingeKnots %||% TRUE else FALSE) + sim$climateHingeKnots <- attr(annualCovariates, fireSenseUtils::spreadFitClimateHingeKnotsTxt) # Confirm that YoungAge is the right amount. If there are "normal" amount of fires, # then it should be < 0.2 @@ -1166,6 +1189,15 @@ prepare_SpreadFit <- function(sim) { #' @return logical(1). useClimateSplit <- function(mod, Par) isTRUE(mod$spreadClimateSplit %||% Par$spreadClimateSplit) +#' Does the spread climate have a hinge term? +#' +#' A fit reused from the ledger (`mod$spreadClimateHinge`, set by `Init()` from the row's coefficient names) keeps +#' its own hinge terms; otherwise the `spreadClimateHinge` parameter decides. +#' +#' @param mod,Par the module's `mod` and `Par`. +#' @return logical(1). +useClimateHinge <- function(mod, Par) isTRUE(mod$spreadClimateHinge %||% Par$spreadClimateHinge) + #' 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 @@ -1179,10 +1211,14 @@ useClimateSplit <- function(mod, Par) isTRUE(mod$spreadClimateSplit %||% Par$spr #' @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()]). +#' @param climateHinge `FALSE` (none); `TRUE`, which adds `C_hinge = pmax(0, C - k)` for each climate variable `C`, with `k` +#' the median of `C` over the burnable pixels of all the years ([fireSenseUtils::climateHingeKnots()]); or the +#' knots (a named list or numeric) of a reused fit, used as they are ([fireSenseUtils::addClimateHinge()]). `C` stays. #' @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 (or their two terms) and `youngAge`. +#' of data.tables of `pixelID`, the climate variables (or their terms) and `youngAge`. With `climateHinge` its attribute +#' `fireSenseUtils::spreadFitClimateHingeKnotsTxt` is the knots. annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnablePixels, tsds, - firePixelsByYear, cutoffForYoungAge, climateSplit = FALSE) { + firePixelsByYear, cutoffForYoungAge, climateSplit = FALSE, climateHinge = FALSE) { ## only these pixels of each year are read from the rasters; the join below keeps no others climateAt <- function(Index) climateRasterToDataTable(historicalClimateRasters = spreadClimate, Index = Index) |> @@ -1193,11 +1229,19 @@ annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnab 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)) { + useHinge <- !isFALSE(climateHinge) + if (isTRUE(climateSplit) || isTRUE(climateHinge)) { ## 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) + burnableClimate <- climateAt(burnableIndex) + } + ## the hinge is of the pixel's own value, so it is made before the split removes the variable + knots <- if (useHinge) { + if (isTRUE(climateHinge)) fireSenseUtils::climateHingeKnots(burnableClimate, names(spreadClimate)) else climateHinge } + if (useHinge) fireSenseUtils::addClimateHinge(fbl, knots) + if (isTRUE(climateSplit)) + fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), burnableClimate, by = fireSenseUtils::yearTxt) annuals <- split(fbl, by = fireSenseUtils::yearTxt, keep.by = FALSE) @@ -1217,8 +1261,10 @@ annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnab ## youngAge of each fire year's pixels: the data year's time since disturbance aged to that year, ## reset by every fire since (all fires, not only those fitted). spreadFit clears fuel, non-forest ## land cover and treed wetland where it is 1, after joining these annual tables to the fuels. - addAnnualYoungAge(annualCovariates, tsds = tsds, firePixelsByYear = firePixelsByYear, - cutoffForYoungAge = cutoffForYoungAge) + annualCovariates <- addAnnualYoungAge(annualCovariates, tsds = tsds, firePixelsByYear = firePixelsByYear, + cutoffForYoungAge = cutoffForYoungAge) + if (useHinge) attr(annualCovariates, fireSenseUtils::spreadFitClimateHingeKnotsTxt) <- as.list(knots) + annualCovariates } #' The non-annual (fuel) spread covariates of one data year diff --git a/tests/testthat/helper-spreadFixtures.R b/tests/testthat/helper-spreadFixtures.R new file mode 100644 index 0000000..683f4f7 --- /dev/null +++ b/tests/testthat/helper-spreadFixtures.R @@ -0,0 +1,32 @@ +## Fixtures shared by several test files: test files do not see each other's functions, helpers are sourced into all. + +## the whole-landscape fixture (test-wholeLandscapeSpreadCovariates.R, test-spreadClimateHinge.R) +wholeFixture <- function() { + r <- terra::rast(nrows = 4, ncols = 5) + years <- 2001:2004 + clim <- list(CMD = terra::rast(lapply(years, function(y) { x <- r; terra::values(x) <- seq_len(20) + y; x }))) + names(clim$CMD) <- paste0("year", years) + tsd <- function(v) { x <- r; terra::values(x) <- v; x } + tsds <- list(year2000 = tsd(c(rep(100, 19), 3)), year2002 = tsd(rep(100, 20))) + allYears <- list(`2000` = c("year2001", "year2002"), `2002` = c("year2003", "year2004")) + burnable <- seq_len(16) # pixels 17:20 cannot burn + burnablePixels <- setNames(rep(list(burnable), 4), unlist(allYears)) + buffers <- list(year2001 = data.table::data.table(pixelID = c(2L, 3L, 5L)), + year2002 = data.table::data.table(pixelID = integer(0)), # a year without fire + year2003 = data.table::data.table(pixelID = c(3L, 16L, 17L)), + year2004 = data.table::data.table(pixelID = c(7L, 8L))) + list(clim = clim, tsds = tsds, allYears = allYears, burnablePixels = burnablePixels, buffers = buffers, + fires = list(`2003` = 9L)) +} + +## a ledger with this ELF (4.2.2, CMD) and a neighbour (4.2.1, CMDsm) (test-spreadClimateOwnELF.R, test-spreadClimateHinge.R) +ownAndNeighbourLedger <- function() { + own <- oneELFLedger() # 4.2.2, fitted with CMD + nb <- oneELFLedger() + nb[[fireSenseUtils::polygonIDTxt]] <- "4.2.1" + nbPars <- own$params[[1]] + names(nbPars)[names(nbPars) == "CMD"] <- "CMDsm" + ledger <- rbind(nb, own) + ledger$params <- list(nbPars, own$params[[1]]) + ledger +} diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index c681ebf..1311854 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -51,7 +51,8 @@ test_that("outputs are the expected names and classes", { outputs <- stats::setNames(md$outputObjects$objectClass, md$outputObjects$objectName) expect_identical( outputs[order(names(outputs))], - c(climateVariables = "list", + c(climateHingeKnots = "list", + climateVariables = "list", climateVariablesForFire = "list", escapeFireSet = "SpatVector", fireBufferedListDT = "list", @@ -102,7 +103,7 @@ test_that("parameters are the expected names", { "forestedLCC", "fuelClassCol", "fuelCovariates", "heldOutFold", "igAggFactor", "minBufferSize", "minBurnableFireSizeHa", "minCovariateProp", "nonflammableLCC", "nonForestCanBeYoungAge", "scanfiVersion", "sppEquivCol", "spreadClimateCandidates", "spreadFitFilename", - "spreadFitGoogleDriveFolder", "skipUnusedFitPrep", "spreadClimateSplit", "spreadCovariates", "spreadInteractions", "spreadIntercept", "targetFuelClasses", + "spreadFitGoogleDriveFolder", "skipUnusedFitPrep", "spreadClimateHinge", "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-spreadClimateHinge.R b/tests/testthat/test-spreadClimateHinge.R new file mode 100644 index 0000000..79765d6 --- /dev/null +++ b/tests/testthat/test-spreadClimateHinge.R @@ -0,0 +1,111 @@ +## spreadClimateHinge: an extra covariate C_hinge = pmax(0, C - k) per spread climate variable, k the ELF's median of C over the +## burnable pixels of all the fit years, stored with the covariates for the ledger. FALSE leaves everything as it was. + +hingeRun <- function(climateSplit = FALSE, climateHinge = FALSE) { + f <- wholeFixture() + withr::local_options(reproducible.cachePath = withr::local_tempdir(), reproducible.useMemoise = FALSE, + .local_envir = parent.frame()) + list(f = f, out = annualSpreadCovariates(f$buffers, f$clim, f$allYears, f$burnablePixels, tsds = f$tsds, + firePixelsByYear = f$fires, cutoffForYoungAge = 15, + climateSplit = climateSplit, climateHinge = climateHinge)) +} + +test_that("with the hinge, each table has C_hinge = pmax(0, C - k), k the median over every burnable pixel of every year", { + skip_if_not_installed("fireSenseUtils") + r <- hingeRun(climateHinge = TRUE) + ## burnable pixels 1:16 in years 2001:2004: CMD is pixel + year + k <- stats::median(unlist(lapply(2001:2004, function(y) 1:16 + y))) + expect_identical(unname(unlist(attr(r$out, fireSenseUtils::spreadFitClimateHingeKnotsTxt))), k) + tabs <- do.call(c, unname(r$out)) + for (x in tabs) { + expect_true(all(c("CMD", "CMD_hinge") %in% names(x))) + expect_equal(x$CMD_hinge, pmax(0, x$CMD - k)) + } + expect_gt(max(unlist(lapply(tabs, function(x) x$CMD_hinge))), 0) # the fixture reaches above k + expect_identical(min(unlist(lapply(tabs, function(x) x$CMD_hinge))), 0) +}) + +test_that("a reused fit's knots are used as they are", { + skip_if_not_installed("fireSenseUtils") + r <- hingeRun(climateHinge = list(CMD = 12)) + for (x in do.call(c, unname(r$out))) expect_equal(x$CMD_hinge, pmax(0, x$CMD - 12)) + expect_identical(attr(r$out, fireSenseUtils::spreadFitClimateHingeKnotsTxt), list(CMD = 12)) +}) + +test_that("the hinge is of the pixel's value with the split too", { + skip_if_not_installed("fireSenseUtils") + r <- hingeRun(climateSplit = TRUE, climateHinge = list(CMD = 12)) + x <- r$out[[1]][[1]] + expect_true(all(c("CMD_yr", "CMD_dev", "CMD_hinge") %in% names(x))) + expect_false("CMD" %in% names(x)) + expect_equal(x$CMD_hinge, pmax(0, x$CMD_yr + x$CMD_dev - 12)) +}) + +test_that("without the hinge the tables and the formula are what they were", { + skip_if_not_installed("fireSenseUtils") + plain <- hingeRun()$out + expect_null(attr(plain, fireSenseUtils::spreadFitClimateHingeKnotsTxt)) + expect_false(any(vapply(do.call(c, unname(plain)), function(x) "CMD_hinge" %in% names(x), logical(1)))) + expect_identical(spreadRHS("all", "CMD", "fuelA"), "CMD + youngAge + fuelA") + expect_identical(spreadRHS("all", "CMD", "fuelA", climateHinge = FALSE), spreadRHS("all", "CMD", "fuelA")) +}) + +test_that("the formula has the hinge term after the variable's other climate terms, and it does not interact", { + expect_identical(spreadRHS("all", "CMD", "fuelA", climateHinge = TRUE), "CMD + CMD_hinge + youngAge + fuelA") + expect_identical(spreadRHS("all", c("CMD", "Tmax"), "fuelA", climateHinge = TRUE), + "CMD + Tmax + CMD_hinge + Tmax_hinge + youngAge + fuelA") + expect_identical(spreadRHS("all", "CMD", "fuelA", "climate:fuel", climateSplit = TRUE, climateHinge = TRUE), + "CMD_yr + CMD_dev + CMD_hinge + youngAge + fuelA + CMD_yr:fuelA") + expect_identical(spreadRHS("fuel", "CMD", "fuelA", climateHinge = TRUE), spreadRHS("fuel", "CMD", "fuelA")) +}) + +test_that("the module defines spreadClimateHinge, FALSE by default", { + def <- Filter(function(x) is.call(x) && identical(x[[1]], as.name("defineModule")), + parse(testthat::test_path("..", "..", "fireSense_dataPrepFit.R"), keep.source = FALSE)) + params <- eval(as.list(def[[1]][[3]])[["parameters"]], envir = asNamespace("SpaDES.core")) + i <- match("spreadClimateHinge", params$paramName) + expect_false(is.na(i)) + expect_identical(params$default[[i]], FALSE) +}) + +## a reused ledger fit keeps its own hinge terms and knots, whatever the parameter says +hingeLedger <- function(withKnots = TRUE) { + ledger <- ownAndNeighbourLedger() + own <- ledger$params[[2]] + own$CMD_hinge <- 0 + ledger$params[[2]] <- own + if (withKnots) ledger[[fireSenseUtils::spreadFitClimateHingeKnotsTxt]] <- I(list(NULL, list(CMD = 12))) + ledger +} +initHinge <- function(ledger, doFit, parHinge) { + 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$spreadClimateHinge <- parHinge + for (s in initBody()) suppressMessages(eval(s, e)) + e +} + +test_that("a reused fit with a hinge term keeps it and its knots even when spreadClimateHinge is FALSE", { + skip_if_not_installed("fireSenseUtils") + e <- initHinge(hingeLedger(), doFit = NA, parHinge = FALSE) + expect_true(e$mod$spreadClimateHinge) + expect_identical(e$mod$climateHingeKnots, list(CMD = 12)) + expect_true(useClimateHinge(e$mod, e$Par)) +}) + +test_that("a reused fit without a hinge term stays without, also when spreadClimateHinge is TRUE", { + skip_if_not_installed("fireSenseUtils") + e <- initHinge(ownAndNeighbourLedger(), doFit = NA, parHinge = TRUE) + expect_false(e$mod$spreadClimateHinge) + expect_false(useClimateHinge(e$mod, e$Par)) +}) + +test_that("a refit follows the parameter", { + skip_if_not_installed("fireSenseUtils") + e <- initHinge(hingeLedger(), doFit = TRUE, parHinge = FALSE) + expect_null(e$mod$spreadClimateHinge) + expect_false(useClimateHinge(e$mod, e$Par)) + expect_true(useClimateHinge(e$mod, list(spreadClimateHinge = TRUE))) +}) diff --git a/tests/testthat/test-spreadClimateOwnELF.R b/tests/testthat/test-spreadClimateOwnELF.R index dbcb5aa..cc97ae0 100644 --- a/tests/testthat/test-spreadClimateOwnELF.R +++ b/tests/testthat/test-spreadClimateOwnELF.R @@ -3,17 +3,6 @@ ## "auto", no variable was chosen, and the spread formula had both CMD and CMDsm, two near-collinear terms. ## The union is still prepared (prediction blends neighbour ELFs); the formula takes this ELF's own. -ownAndNeighbourLedger <- function() { - own <- oneELFLedger() # 4.2.2, fitted with CMD - nb <- oneELFLedger() - nb[[fireSenseUtils::polygonIDTxt]] <- "4.2.1" - nbPars <- own$params[[1]] - names(nbPars)[names(nbPars) == "CMD"] <- "CMDsm" - ledger <- rbind(nb, own) - ledger$params <- list(nbPars, own$params[[1]]) - ledger -} - initWithLedger <- function(doFit) { e <- ledgerInitEnv(ownAndNeighbourLedger()) e$sim$.ELFind <- "4.2.2" diff --git a/tests/testthat/test-wholeLandscapeSpreadCovariates.R b/tests/testthat/test-wholeLandscapeSpreadCovariates.R index 6b69eff..c320cc5 100644 --- a/tests/testthat/test-wholeLandscapeSpreadCovariates.R +++ b/tests/testthat/test-wholeLandscapeSpreadCovariates.R @@ -3,24 +3,6 @@ ## instead of the buffer pixels. They must have the buffer tables' names and columns, and the same values ## on the buffer pixels. -wholeFixture <- function() { - r <- terra::rast(nrows = 4, ncols = 5) - years <- 2001:2004 - clim <- list(CMD = terra::rast(lapply(years, function(y) { x <- r; terra::values(x) <- seq_len(20) + y; x }))) - names(clim$CMD) <- paste0("year", years) - tsd <- function(v) { x <- r; terra::values(x) <- v; x } - tsds <- list(year2000 = tsd(c(rep(100, 19), 3)), year2002 = tsd(rep(100, 20))) - allYears <- list(`2000` = c("year2001", "year2002"), `2002` = c("year2003", "year2004")) - burnable <- seq_len(16) # pixels 17:20 cannot burn - burnablePixels <- setNames(rep(list(burnable), 4), unlist(allYears)) - buffers <- list(year2001 = data.table::data.table(pixelID = c(2L, 3L, 5L)), - year2002 = data.table::data.table(pixelID = integer(0)), # a year without fire - year2003 = data.table::data.table(pixelID = c(3L, 16L, 17L)), - year2004 = data.table::data.table(pixelID = c(7L, 8L))) - list(clim = clim, tsds = tsds, allYears = allYears, burnablePixels = burnablePixels, buffers = buffers, - fires = list(`2003` = 9L)) -} - test_that("whole annual tables have the buffer tables' names and rows on the buffer pixels, and every burnable pixel", { skip_if_not_installed("fireSenseUtils") withr::local_options(reproducible.cachePath = withr::local_tempdir(), reproducible.useMemoise = FALSE) From fb68d18941cd8efafb759ff129b746385e424b99 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 25 Nov 2026 16:34:51 -0700 Subject: [PATCH 2/4] Smooth climate curve term: softplus(C - k, s), k the ELF median, s its sd (replaces the hard hinge) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- R/spreadFormula.R | 6 +- fireSense_dataPrepFit.R | 75 +++++++-------- tests/testthat/helper-spreadFixtures.R | 4 +- tests/testthat/test-metadata.R | 4 +- tests/testthat/test-spreadClimateCurve.R | 111 +++++++++++++++++++++++ tests/testthat/test-spreadClimateHinge.R | 111 ----------------------- 7 files changed, 157 insertions(+), 156 deletions(-) create mode 100644 tests/testthat/test-spreadClimateCurve.R delete mode 100644 tests/testthat/test-spreadClimateHinge.R diff --git a/NEWS.md b/NEWS.md index 5e3ece0..fbc16dc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) -* New parameter `spreadClimateHinge` (`FALSE` by default: nothing changes). `TRUE` adds a covariate `_hinge = pmax(0, C - k)` for each spread climate variable `C`, with its own coefficient, so the climate response can steepen in dry years; `k` is the ELF's median of `C` over the burnable pixels of all the fit years. The knots are in `sim$climateHingeKnots`, which `fireSense_spreadFit` writes to the ledger row, and `fireSense_spreadPredict` builds the term from them. A reused ledger fit keeps its own hinge terms and knots. The code is `fireSenseUtils::climateHingeKnots()`, `addClimateHinge()` and `climateHingeCols()`, in the `prepSpreadFitData` cache key. Needs `fireSense_spreadFit`, `fireSense_spreadPredict` and fireSenseUtils with the hinge (fireSenseUtils >= 0.2.3.9193, version to be set after it merges). +* 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` is the ELF's median of `C` over the burnable pixels of all the fit years. The knots are in `sim$climateCurvePars`, which `fireSense_spreadFit` writes to the ledger row, and `fireSense_spreadPredict` builds the term from them. A reused ledger fit keeps its own curve terms and knots. The code is `fireSenseUtils::climateCurvePars()`, `addClimateCurve()` and `climateCurveCols()`, in the `prepSpreadFitData` cache key. Needs `fireSense_spreadFit`, `fireSense_spreadPredict` and fireSenseUtils with the curve (fireSenseUtils >= 0.2.3.9193, version to be set after it merges). * No prescribed burn is fitted: the spread fit's fire polygons and the ignition fit's NFDB points are selected by `fireSenseUtils::modelledFires()` (the causes of `fireCauses`, and no NBAC `PRESCRIBED`, NFDB `PRESCRIBED`, `FIRE_TYPE` or `H-PB` fire). It replaces the module's `polysOfCauses()`. Needs fireSenseUtils with `modelledFires()`; spread and ignition fits made before this included the prescribed fires of the wanted causes. diff --git a/R/spreadFormula.R b/R/spreadFormula.R index d83417b..a5ede6d 100644 --- a/R/spreadFormula.R +++ b/R/spreadFormula.R @@ -40,15 +40,15 @@ spreadInteractionClimateFuel <- "climate:fuel" #' @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()`). -#' @param climateHinge `TRUE` adds each variable's hinge term (`C_hinge`, `fireSenseUtils::climateHingeCols()`) after its +#' @param climateCurve `TRUE` adds each variable's curve term (`C_curve`, `fireSenseUtils::climateCurveCols()`) after its #' other climate terms; it does not interact. #' @return a character string, or `character()` for the null model. spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character(), climateSplit = FALSE, - climateHinge = FALSE) { + climateCurve = FALSE) { if (identical(spreadCovariates, "none")) return(character()) fuel <- if (spreadInteractionClimateFuel %in% spreadInteractions) fireSenseUtils::spreadFuelCols(vegColsForRHS) climCols <- if (isTRUE(climateSplit)) fireSenseUtils::climateSplitCols(spreadVars) else spreadVars - if (isTRUE(climateHinge)) climCols <- c(climCols, fireSenseUtils::climateHingeCols(spreadVars)) + if (isTRUE(climateCurve)) climCols <- c(climCols, fireSenseUtils::climateCurveCols(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 = " + ") diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index a5ca75e..5574f20 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.9193)", # 9193 (placeholder until the climate hinge PR (fireSenseUtils) merges and is bumped): climateHingeKnots(), addClimateHinge(), climateHingeCols(), ledgerClimateHingeKnots(), isClimateHingeCol(); 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 + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9193)", # 9193 (placeholder until the climate curve PR (fireSenseUtils) merges and is bumped): climateCurvePars(), addClimateCurve(), climateCurveCols(), ledgerClimateCurvePars(), isClimateCurveCol(); 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)", @@ -217,16 +217,17 @@ defineModule(sim, list( "`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("spreadClimateHinge", "logical", FALSE, NA, NA, + defineParameter("spreadClimateCurve", "logical", FALSE, NA, NA, paste("`FALSE` (the default): the spread formula is unchanged. `TRUE`: it has an extra term for each spread", - "climate variable `C`, `_hinge = pmax(0, C - k)`, with its own coefficient, so the climate response", + "climate variable `C`, `_curve = softplus(C - k, s)` (`fireSenseUtils::softplus()`: smooth, no corner), with its own coefficient, so the climate response", + "can steepen above `k` when the coefficient is positive; a negative one flattens the dry side (the sign is free). `k` and `s` are the median and sd of `C`", "can steepen (or flatten) above `k` (dry years); `C` keeps its own term. `k` is the ELF's median of `C`", "over the burnable pixels in all the fit's years, one number for the ELF. It is stored in the ledger row", - "(`fireSenseUtils::spreadFitClimateHingeKnotsTxt`), and `fireSense_spreadPredict` builds the term from it", - "(`fireSenseUtils::addClimateHinge()`). With `spreadClimateSplit` the hinge is of `C`, the pixel's value,", + "(`fireSenseUtils::spreadFitClimateCurveParsTxt`), and `fireSense_spreadPredict` builds the term from it", + "(`fireSenseUtils::addClimateCurve()`). With `spreadClimateSplit` the curve is of `C`, the pixel's value,", "beside the `_yr` and `_dev` terms. Ignored if `sim$fireSense_spreadFormula` is supplied. A prediction needs no", - "setting: it reads the knots from the ledger row. A ledger fit that is reused (`doFit` FALSE) keeps its own", - "hinge terms and knots, whatever this says. Needs a `fireSense_spreadFit` that writes the knots.")), + "setting: it reads `k` and `s` from the ledger row. A ledger fit that is reused (`doFit` FALSE) keeps its own", + "curve terms and their `k` and `s`, whatever this says. Needs a `fireSense_spreadFit` that writes them.")), defineParameter("targetFuelClasses", "numeric", 5, 1, 7, "the target number of unique fuel classes when using semi-automated approach"), defineParameter("useRasterizedFireForSpread", "logical", FALSE, NA, NA, @@ -274,8 +275,8 @@ defineModule(sim, list( fireSenseUtils::rasterFireSpreadPoints, spreadFitPreRun = sim$spreadFitPreRun), fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps()))), prepSpreadFitData = list(.cacheExtra = quote(c(list( - fireSenseUtils::addClimateHinge, fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, - fireSenseUtils::climateHingeCols, fireSenseUtils::climateHingeKnots, + fireSenseUtils::addClimateCurve, fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, + fireSenseUtils::climateCurveCols, fireSenseUtils::climateCurvePars, fireSenseUtils::softplus, fireSenseUtils::climateRasterToDataTable, fireSenseUtils::climateSplitCols, fireSenseUtils::climateSplitRefPixels, fireSenseUtils::dataYearBefore, fireSenseUtils::dataYearElement, @@ -427,9 +428,9 @@ defineModule(sim, list( createsOutput("fireSense_annualSpreadFitCovariates", "list", "List of data.tables, one per fire year, of `pixelID` and the spread climate covariates in the fire buffers (every flammable pixel with `wholeLandscapeSpreadCovariates`).", events = "prepSpreadFitData"), - createsOutput("climateHingeKnots", "list", - paste("With `spreadClimateHinge`, the knot of each spread climate variable's hinge term (`fireSenseUtils::climateHingeKnots()`),", - "which `fireSense_spreadFit` stores in the ledger row; `NULL` without hinge terms."), + createsOutput("climateCurvePars", "list", + paste("With `spreadClimateCurve`, `k` and `s` of each spread climate variable's curve term (`fireSenseUtils::climateCurvePars()`),", + "which `fireSense_spreadFit` stores in the ledger row; `NULL` without curve terms."), events = "prepSpreadFitData"), createsOutput("fireSense_escapeCovariates", "data.table", "ignition covariates with added column of escapes", @@ -697,11 +698,11 @@ Init <- function(sim) { ## 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]]))) - ## a reused fit keeps its hinge terms, and the knots it was fitted with - mod$spreadClimateHinge <- if (reuseOwnFit) - any(fireSenseUtils::isClimateHingeCol(colnames(sim$spreadFitPreRun$params[[ownRow]]))) - mod$climateHingeKnots <- if (isTRUE(mod$spreadClimateHinge)) - fireSenseUtils::ledgerClimateHingeKnots(sim$spreadFitPreRun, ownRow) + ## a reused fit keeps its curve terms, and the `k` and `s` it was fitted with + mod$spreadClimateCurve <- if (reuseOwnFit) + any(fireSenseUtils::isClimateCurveCol(colnames(sim$spreadFitPreRun$params[[ownRow]]))) + mod$climateCurvePars <- if (isTRUE(mod$spreadClimateCurve)) + fireSenseUtils::ledgerClimateCurvePars(sim$spreadFitPreRun, ownRow) ## spread: the union, for prediction; ignition (xgboost) can use every one of them sim$climateVariablesForFire <- addFitClimateVariablesForFire(sim$climateVariablesForFire, fitClimVars) @@ -1111,7 +1112,7 @@ prepare_SpreadFit <- function(sim) { ## 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), - climateHinge = useClimateHinge(mod, Par)) + climateCurve = useClimateCurve(mod, Par)) ## this is a funny way to get years but avoids years with 0 fires allYears <- unname(unlist(mod$allYears)) @@ -1141,8 +1142,8 @@ prepare_SpreadFit <- function(sim) { pixelsByYear, spreadClimate, mod$allYears, burnablePixels, tsds = sim$nonForest_timeSinceDisturbances, firePixelsByYear = firePixels, cutoffForYoungAge = P(sim)$cutoffForYoungAge, climateSplit = useClimateSplit(mod, Par), - climateHinge = if (useClimateHinge(mod, Par)) mod$climateHingeKnots %||% TRUE else FALSE) - sim$climateHingeKnots <- attr(annualCovariates, fireSenseUtils::spreadFitClimateHingeKnotsTxt) + climateCurve = if (useClimateCurve(mod, Par)) mod$climateCurvePars %||% TRUE else FALSE) + sim$climateCurvePars <- attr(annualCovariates, fireSenseUtils::spreadFitClimateCurveParsTxt) # Confirm that YoungAge is the right amount. If there are "normal" amount of fires, # then it should be < 0.2 @@ -1189,14 +1190,14 @@ prepare_SpreadFit <- function(sim) { #' @return logical(1). useClimateSplit <- function(mod, Par) isTRUE(mod$spreadClimateSplit %||% Par$spreadClimateSplit) -#' Does the spread climate have a hinge term? +#' Does the spread climate have a curve term? #' -#' A fit reused from the ledger (`mod$spreadClimateHinge`, set by `Init()` from the row's coefficient names) keeps -#' its own hinge terms; otherwise the `spreadClimateHinge` parameter decides. +#' A fit reused from the ledger (`mod$spreadClimateCurve`, set by `Init()` from the row's coefficient names) keeps +#' its own curve terms; otherwise the `spreadClimateCurve` parameter decides. #' #' @param mod,Par the module's `mod` and `Par`. #' @return logical(1). -useClimateHinge <- function(mod, Par) isTRUE(mod$spreadClimateHinge %||% Par$spreadClimateHinge) +useClimateCurve <- function(mod, Par) isTRUE(mod$spreadClimateCurve %||% Par$spreadClimateCurve) #' The annual spread covariates of the given pixels #' @@ -1211,14 +1212,14 @@ useClimateHinge <- function(mod, Par) isTRUE(mod$spreadClimateHinge %||% Par$spr #' @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()]). -#' @param climateHinge `FALSE` (none); `TRUE`, which adds `C_hinge = pmax(0, C - k)` for each climate variable `C`, with `k` -#' the median of `C` over the burnable pixels of all the years ([fireSenseUtils::climateHingeKnots()]); or the -#' knots (a named list or numeric) of a reused fit, used as they are ([fireSenseUtils::addClimateHinge()]). `C` stays. +#' @param climateCurve `FALSE` (none); `TRUE`, which adds `C_curve = softplus(C - k, s)` for each climate variable `C`, with `k` and `s` +#' the median and sd of `C` over the burnable pixels of all the years ([fireSenseUtils::climateCurvePars()]); or the +#' `c(k = , s = )` of each variable (a named list) of a reused fit, used as they are ([fireSenseUtils::addClimateCurve()]). `C` stays. #' @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 (or their terms) and `youngAge`. With `climateHinge` its attribute -#' `fireSenseUtils::spreadFitClimateHingeKnotsTxt` is the knots. +#' of data.tables of `pixelID`, the climate variables (or their terms) and `youngAge`. With `climateCurve` its attribute +#' `fireSenseUtils::spreadFitClimateCurveParsTxt` is `k` and `s` of each variable. annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnablePixels, tsds, - firePixelsByYear, cutoffForYoungAge, climateSplit = FALSE, climateHinge = FALSE) { + firePixelsByYear, cutoffForYoungAge, climateSplit = FALSE, climateCurve = FALSE) { ## only these pixels of each year are read from the rasters; the join below keeps no others climateAt <- function(Index) climateRasterToDataTable(historicalClimateRasters = spreadClimate, Index = Index) |> @@ -1229,17 +1230,17 @@ annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnab rmCols <- setdiff(colnames(fbl), c("pixelID", fireSenseUtils::yearTxt)) set(fbl, NULL, rmCols, NULL) fbl <- climateDT[fbl, on = c(fireSenseUtils::yearTxt, "pixelID"), nomatch = NULL] - useHinge <- !isFALSE(climateHinge) - if (isTRUE(climateSplit) || isTRUE(climateHinge)) { + useCurve <- !isFALSE(climateCurve) + if (isTRUE(climateSplit) || isTRUE(climateCurve)) { ## 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))) burnableClimate <- climateAt(burnableIndex) } - ## the hinge is of the pixel's own value, so it is made before the split removes the variable - knots <- if (useHinge) { - if (isTRUE(climateHinge)) fireSenseUtils::climateHingeKnots(burnableClimate, names(spreadClimate)) else climateHinge + ## the curve is of the pixel's own value, so it is made before the split removes the variable + pars <- if (useCurve) { + if (isTRUE(climateCurve)) fireSenseUtils::climateCurvePars(burnableClimate, names(spreadClimate)) else climateCurve } - if (useHinge) fireSenseUtils::addClimateHinge(fbl, knots) + if (useCurve) fireSenseUtils::addClimateCurve(fbl, pars) if (isTRUE(climateSplit)) fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), burnableClimate, by = fireSenseUtils::yearTxt) @@ -1263,7 +1264,7 @@ annualSpreadCovariates <- function(pixelsByYear, spreadClimate, allYears, burnab ## land cover and treed wetland where it is 1, after joining these annual tables to the fuels. annualCovariates <- addAnnualYoungAge(annualCovariates, tsds = tsds, firePixelsByYear = firePixelsByYear, cutoffForYoungAge = cutoffForYoungAge) - if (useHinge) attr(annualCovariates, fireSenseUtils::spreadFitClimateHingeKnotsTxt) <- as.list(knots) + if (useCurve) attr(annualCovariates, fireSenseUtils::spreadFitClimateCurveParsTxt) <- pars annualCovariates } diff --git a/tests/testthat/helper-spreadFixtures.R b/tests/testthat/helper-spreadFixtures.R index 683f4f7..10872c8 100644 --- a/tests/testthat/helper-spreadFixtures.R +++ b/tests/testthat/helper-spreadFixtures.R @@ -1,6 +1,6 @@ ## Fixtures shared by several test files: test files do not see each other's functions, helpers are sourced into all. -## the whole-landscape fixture (test-wholeLandscapeSpreadCovariates.R, test-spreadClimateHinge.R) +## the whole-landscape fixture (test-wholeLandscapeSpreadCovariates.R, test-spreadClimateCurve.R) wholeFixture <- function() { r <- terra::rast(nrows = 4, ncols = 5) years <- 2001:2004 @@ -19,7 +19,7 @@ wholeFixture <- function() { fires = list(`2003` = 9L)) } -## a ledger with this ELF (4.2.2, CMD) and a neighbour (4.2.1, CMDsm) (test-spreadClimateOwnELF.R, test-spreadClimateHinge.R) +## a ledger with this ELF (4.2.2, CMD) and a neighbour (4.2.1, CMDsm) (test-spreadClimateOwnELF.R, test-spreadClimateCurve.R) ownAndNeighbourLedger <- function() { own <- oneELFLedger() # 4.2.2, fitted with CMD nb <- oneELFLedger() diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index 1311854..92d5f80 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -51,7 +51,7 @@ test_that("outputs are the expected names and classes", { outputs <- stats::setNames(md$outputObjects$objectClass, md$outputObjects$objectName) expect_identical( outputs[order(names(outputs))], - c(climateHingeKnots = "list", + c(climateCurvePars = "list", climateVariables = "list", climateVariablesForFire = "list", escapeFireSet = "SpatVector", @@ -103,7 +103,7 @@ test_that("parameters are the expected names", { "forestedLCC", "fuelClassCol", "fuelCovariates", "heldOutFold", "igAggFactor", "minBufferSize", "minBurnableFireSizeHa", "minCovariateProp", "nonflammableLCC", "nonForestCanBeYoungAge", "scanfiVersion", "sppEquivCol", "spreadClimateCandidates", "spreadFitFilename", - "spreadFitGoogleDriveFolder", "skipUnusedFitPrep", "spreadClimateHinge", "spreadClimateSplit", "spreadCovariates", "spreadInteractions", "spreadIntercept", "targetFuelClasses", + "spreadFitGoogleDriveFolder", "skipUnusedFitPrep", "spreadClimateCurve", "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-spreadClimateCurve.R b/tests/testthat/test-spreadClimateCurve.R new file mode 100644 index 0000000..31a627b --- /dev/null +++ b/tests/testthat/test-spreadClimateCurve.R @@ -0,0 +1,111 @@ +## spreadClimateCurve: an extra covariate C_curve = softplus(C - k, s) per spread climate variable, k the ELF's median and s its sd of C over the +## burnable pixels of all the fit years, stored with the covariates for the ledger. FALSE leaves everything as it was. + +curveRun <- function(climateSplit = FALSE, climateCurve = FALSE) { + f <- wholeFixture() + withr::local_options(reproducible.cachePath = withr::local_tempdir(), reproducible.useMemoise = FALSE, + .local_envir = parent.frame()) + list(f = f, out = annualSpreadCovariates(f$buffers, f$clim, f$allYears, f$burnablePixels, tsds = f$tsds, + firePixelsByYear = f$fires, cutoffForYoungAge = 15, + climateSplit = climateSplit, climateCurve = climateCurve)) +} + +test_that("with the curve, each table has C_curve = softplus(C - k, s), k the median and s the sd over every burnable pixel of every year", { + skip_if_not_installed("fireSenseUtils") + r <- curveRun(climateCurve = TRUE) + ## burnable pixels 1:16 in years 2001:2004: CMD is pixel + year + all <- unlist(lapply(2001:2004, function(y) 1:16 + y)) + k <- stats::median(all); s <- stats::sd(all) + expect_identical(attr(r$out, fireSenseUtils::spreadFitClimateCurveParsTxt), list(CMD = c(k = k, s = s))) + tabs <- do.call(c, unname(r$out)) + for (x in tabs) { + expect_true(all(c("CMD", "CMD_curve") %in% names(x))) + expect_equal(x$CMD_curve, fireSenseUtils::softplus(x$CMD - k, s)) + } + expect_true(all(unlist(lapply(tabs, function(x) x$CMD_curve)) > 0)) # smooth: never exactly 0 +}) + +test_that("a reused fit's k and s are used as they are", { + skip_if_not_installed("fireSenseUtils") + r <- curveRun(climateCurve = list(CMD = c(k = 12, s = 3))) + for (x in do.call(c, unname(r$out))) expect_equal(x$CMD_curve, fireSenseUtils::softplus(x$CMD - 12, 3)) + expect_identical(attr(r$out, fireSenseUtils::spreadFitClimateCurveParsTxt), list(CMD = c(k = 12, s = 3))) +}) + +test_that("the curve is of the pixel's value with the split too", { + skip_if_not_installed("fireSenseUtils") + r <- curveRun(climateSplit = TRUE, climateCurve = list(CMD = c(k = 12, s = 3))) + x <- r$out[[1]][[1]] + expect_true(all(c("CMD_yr", "CMD_dev", "CMD_curve") %in% names(x))) + expect_false("CMD" %in% names(x)) + expect_equal(x$CMD_curve, fireSenseUtils::softplus(x$CMD_yr + x$CMD_dev - 12, 3)) +}) + +test_that("without the curve the tables and the formula are what they were", { + skip_if_not_installed("fireSenseUtils") + plain <- curveRun()$out + expect_null(attr(plain, fireSenseUtils::spreadFitClimateCurveParsTxt)) + expect_false(any(vapply(do.call(c, unname(plain)), function(x) "CMD_curve" %in% names(x), logical(1)))) + expect_identical(spreadRHS("all", "CMD", "fuelA"), "CMD + youngAge + fuelA") + expect_identical(spreadRHS("all", "CMD", "fuelA", climateCurve = FALSE), spreadRHS("all", "CMD", "fuelA")) +}) + +test_that("the formula has the curve term after the variable's other climate terms, and it does not interact", { + expect_identical(spreadRHS("all", "CMD", "fuelA", climateCurve = TRUE), "CMD + CMD_curve + youngAge + fuelA") + expect_identical(spreadRHS("all", c("CMD", "Tmax"), "fuelA", climateCurve = TRUE), + "CMD + Tmax + CMD_curve + Tmax_curve + youngAge + fuelA") + expect_identical(spreadRHS("all", "CMD", "fuelA", "climate:fuel", climateSplit = TRUE, climateCurve = TRUE), + "CMD_yr + CMD_dev + CMD_curve + youngAge + fuelA + CMD_yr:fuelA") + expect_identical(spreadRHS("fuel", "CMD", "fuelA", climateCurve = TRUE), spreadRHS("fuel", "CMD", "fuelA")) +}) + +test_that("the module defines spreadClimateCurve, FALSE by default", { + def <- Filter(function(x) is.call(x) && identical(x[[1]], as.name("defineModule")), + parse(testthat::test_path("..", "..", "fireSense_dataPrepFit.R"), keep.source = FALSE)) + params <- eval(as.list(def[[1]][[3]])[["parameters"]], envir = asNamespace("SpaDES.core")) + i <- match("spreadClimateCurve", params$paramName) + expect_false(is.na(i)) + expect_identical(params$default[[i]], FALSE) +}) + +## a reused ledger fit keeps its own curve terms and knots, whatever the parameter says +curveLedger <- function(withPars = TRUE) { + ledger <- ownAndNeighbourLedger() + own <- ledger$params[[2]] + own$CMD_curve <- 0 + ledger$params[[2]] <- own + if (withPars) ledger[[fireSenseUtils::spreadFitClimateCurveParsTxt]] <- I(list(NULL, list(CMD = c(k = 12, s = 3)))) + ledger +} +initCurve <- function(ledger, doFit, parCurve) { + 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$spreadClimateCurve <- parCurve + for (s in initBody()) suppressMessages(eval(s, e)) + e +} + +test_that("a reused fit with a curve term keeps it and its k and s even when spreadClimateCurve is FALSE", { + skip_if_not_installed("fireSenseUtils") + e <- initCurve(curveLedger(), doFit = NA, parCurve = FALSE) + expect_true(e$mod$spreadClimateCurve) + expect_identical(e$mod$climateCurvePars, list(CMD = c(k = 12, s = 3))) + expect_true(useClimateCurve(e$mod, e$Par)) +}) + +test_that("a reused fit without a curve term stays without, also when spreadClimateCurve is TRUE", { + skip_if_not_installed("fireSenseUtils") + e <- initCurve(ownAndNeighbourLedger(), doFit = NA, parCurve = TRUE) + expect_false(e$mod$spreadClimateCurve) + expect_false(useClimateCurve(e$mod, e$Par)) +}) + +test_that("a refit follows the parameter", { + skip_if_not_installed("fireSenseUtils") + e <- initCurve(curveLedger(), doFit = TRUE, parCurve = FALSE) + expect_null(e$mod$spreadClimateCurve) + expect_false(useClimateCurve(e$mod, e$Par)) + expect_true(useClimateCurve(e$mod, list(spreadClimateCurve = TRUE))) +}) diff --git a/tests/testthat/test-spreadClimateHinge.R b/tests/testthat/test-spreadClimateHinge.R deleted file mode 100644 index 79765d6..0000000 --- a/tests/testthat/test-spreadClimateHinge.R +++ /dev/null @@ -1,111 +0,0 @@ -## spreadClimateHinge: an extra covariate C_hinge = pmax(0, C - k) per spread climate variable, k the ELF's median of C over the -## burnable pixels of all the fit years, stored with the covariates for the ledger. FALSE leaves everything as it was. - -hingeRun <- function(climateSplit = FALSE, climateHinge = FALSE) { - f <- wholeFixture() - withr::local_options(reproducible.cachePath = withr::local_tempdir(), reproducible.useMemoise = FALSE, - .local_envir = parent.frame()) - list(f = f, out = annualSpreadCovariates(f$buffers, f$clim, f$allYears, f$burnablePixels, tsds = f$tsds, - firePixelsByYear = f$fires, cutoffForYoungAge = 15, - climateSplit = climateSplit, climateHinge = climateHinge)) -} - -test_that("with the hinge, each table has C_hinge = pmax(0, C - k), k the median over every burnable pixel of every year", { - skip_if_not_installed("fireSenseUtils") - r <- hingeRun(climateHinge = TRUE) - ## burnable pixels 1:16 in years 2001:2004: CMD is pixel + year - k <- stats::median(unlist(lapply(2001:2004, function(y) 1:16 + y))) - expect_identical(unname(unlist(attr(r$out, fireSenseUtils::spreadFitClimateHingeKnotsTxt))), k) - tabs <- do.call(c, unname(r$out)) - for (x in tabs) { - expect_true(all(c("CMD", "CMD_hinge") %in% names(x))) - expect_equal(x$CMD_hinge, pmax(0, x$CMD - k)) - } - expect_gt(max(unlist(lapply(tabs, function(x) x$CMD_hinge))), 0) # the fixture reaches above k - expect_identical(min(unlist(lapply(tabs, function(x) x$CMD_hinge))), 0) -}) - -test_that("a reused fit's knots are used as they are", { - skip_if_not_installed("fireSenseUtils") - r <- hingeRun(climateHinge = list(CMD = 12)) - for (x in do.call(c, unname(r$out))) expect_equal(x$CMD_hinge, pmax(0, x$CMD - 12)) - expect_identical(attr(r$out, fireSenseUtils::spreadFitClimateHingeKnotsTxt), list(CMD = 12)) -}) - -test_that("the hinge is of the pixel's value with the split too", { - skip_if_not_installed("fireSenseUtils") - r <- hingeRun(climateSplit = TRUE, climateHinge = list(CMD = 12)) - x <- r$out[[1]][[1]] - expect_true(all(c("CMD_yr", "CMD_dev", "CMD_hinge") %in% names(x))) - expect_false("CMD" %in% names(x)) - expect_equal(x$CMD_hinge, pmax(0, x$CMD_yr + x$CMD_dev - 12)) -}) - -test_that("without the hinge the tables and the formula are what they were", { - skip_if_not_installed("fireSenseUtils") - plain <- hingeRun()$out - expect_null(attr(plain, fireSenseUtils::spreadFitClimateHingeKnotsTxt)) - expect_false(any(vapply(do.call(c, unname(plain)), function(x) "CMD_hinge" %in% names(x), logical(1)))) - expect_identical(spreadRHS("all", "CMD", "fuelA"), "CMD + youngAge + fuelA") - expect_identical(spreadRHS("all", "CMD", "fuelA", climateHinge = FALSE), spreadRHS("all", "CMD", "fuelA")) -}) - -test_that("the formula has the hinge term after the variable's other climate terms, and it does not interact", { - expect_identical(spreadRHS("all", "CMD", "fuelA", climateHinge = TRUE), "CMD + CMD_hinge + youngAge + fuelA") - expect_identical(spreadRHS("all", c("CMD", "Tmax"), "fuelA", climateHinge = TRUE), - "CMD + Tmax + CMD_hinge + Tmax_hinge + youngAge + fuelA") - expect_identical(spreadRHS("all", "CMD", "fuelA", "climate:fuel", climateSplit = TRUE, climateHinge = TRUE), - "CMD_yr + CMD_dev + CMD_hinge + youngAge + fuelA + CMD_yr:fuelA") - expect_identical(spreadRHS("fuel", "CMD", "fuelA", climateHinge = TRUE), spreadRHS("fuel", "CMD", "fuelA")) -}) - -test_that("the module defines spreadClimateHinge, FALSE by default", { - def <- Filter(function(x) is.call(x) && identical(x[[1]], as.name("defineModule")), - parse(testthat::test_path("..", "..", "fireSense_dataPrepFit.R"), keep.source = FALSE)) - params <- eval(as.list(def[[1]][[3]])[["parameters"]], envir = asNamespace("SpaDES.core")) - i <- match("spreadClimateHinge", params$paramName) - expect_false(is.na(i)) - expect_identical(params$default[[i]], FALSE) -}) - -## a reused ledger fit keeps its own hinge terms and knots, whatever the parameter says -hingeLedger <- function(withKnots = TRUE) { - ledger <- ownAndNeighbourLedger() - own <- ledger$params[[2]] - own$CMD_hinge <- 0 - ledger$params[[2]] <- own - if (withKnots) ledger[[fireSenseUtils::spreadFitClimateHingeKnotsTxt]] <- I(list(NULL, list(CMD = 12))) - ledger -} -initHinge <- function(ledger, doFit, parHinge) { - 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$spreadClimateHinge <- parHinge - for (s in initBody()) suppressMessages(eval(s, e)) - e -} - -test_that("a reused fit with a hinge term keeps it and its knots even when spreadClimateHinge is FALSE", { - skip_if_not_installed("fireSenseUtils") - e <- initHinge(hingeLedger(), doFit = NA, parHinge = FALSE) - expect_true(e$mod$spreadClimateHinge) - expect_identical(e$mod$climateHingeKnots, list(CMD = 12)) - expect_true(useClimateHinge(e$mod, e$Par)) -}) - -test_that("a reused fit without a hinge term stays without, also when spreadClimateHinge is TRUE", { - skip_if_not_installed("fireSenseUtils") - e <- initHinge(ownAndNeighbourLedger(), doFit = NA, parHinge = TRUE) - expect_false(e$mod$spreadClimateHinge) - expect_false(useClimateHinge(e$mod, e$Par)) -}) - -test_that("a refit follows the parameter", { - skip_if_not_installed("fireSenseUtils") - e <- initHinge(hingeLedger(), doFit = TRUE, parHinge = FALSE) - expect_null(e$mod$spreadClimateHinge) - expect_false(useClimateHinge(e$mod, e$Par)) - expect_true(useClimateHinge(e$mod, list(spreadClimateHinge = TRUE))) -}) From aa31144698bf454c215bb41dfd3c13961548888e Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 25 Nov 2026 17:09:57 -0700 Subject: [PATCH 3/4] Use the shared climate-term helpers (climateTermCols, isClimateTermCol, climateTermBase); test that addAnnualYoungAge returns its input Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- R/spreadFormula.R | 4 ++-- fireSense_dataPrepFit.R | 6 +++--- tests/testthat/test-annualYoungAge.R | 12 ++++++++++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/NEWS.md b/NEWS.md index fbc16dc..3e8bdd1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) -* 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` is the ELF's median of `C` over the burnable pixels of all the fit years. The knots are in `sim$climateCurvePars`, which `fireSense_spreadFit` writes to the ledger row, and `fireSense_spreadPredict` builds the term from them. A reused ledger fit keeps its own curve terms and knots. The code is `fireSenseUtils::climateCurvePars()`, `addClimateCurve()` and `climateCurveCols()`, in the `prepSpreadFitData` cache key. Needs `fireSense_spreadFit`, `fireSense_spreadPredict` and fireSenseUtils with the curve (fireSenseUtils >= 0.2.3.9193, version to be set after it merges). +* 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.9193, version to be set after it merges). * No prescribed burn is fitted: the spread fit's fire polygons and the ignition fit's NFDB points are selected by `fireSenseUtils::modelledFires()` (the causes of `fireCauses`, and no NBAC `PRESCRIBED`, NFDB `PRESCRIBED`, `FIRE_TYPE` or `H-PB` fire). It replaces the module's `polysOfCauses()`. Needs fireSenseUtils with `modelledFires()`; spread and ignition fits made before this included the prescribed fires of the wanted causes. diff --git a/R/spreadFormula.R b/R/spreadFormula.R index a5ede6d..e8b94e1 100644 --- a/R/spreadFormula.R +++ b/R/spreadFormula.R @@ -40,7 +40,7 @@ spreadInteractionClimateFuel <- "climate:fuel" #' @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()`). -#' @param climateCurve `TRUE` adds each variable's curve term (`C_curve`, `fireSenseUtils::climateCurveCols()`) after its +#' @param climateCurve `TRUE` adds each variable's curve term (`C_curve`, `fireSenseUtils::climateTermCols()`) after its #' other climate terms; it does not interact. #' @return a character string, or `character()` for the null model. spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character(), climateSplit = FALSE, @@ -48,7 +48,7 @@ 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 - if (isTRUE(climateCurve)) climCols <- c(climCols, fireSenseUtils::climateCurveCols(spreadVars)) + if (isTRUE(climateCurve)) climCols <- c(climCols, fireSenseUtils::climateTermCols(spreadVars, fireSenseUtils::climateCurveSuffix)) ## 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 = " + ") diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 5574f20..fa8b908 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.9193)", # 9193 (placeholder until the climate curve PR (fireSenseUtils) merges and is bumped): climateCurvePars(), addClimateCurve(), climateCurveCols(), ledgerClimateCurvePars(), isClimateCurveCol(); 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 + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9193)", # 9193 (placeholder until the climate curve PR (fireSenseUtils) merges and is bumped): 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)", @@ -276,7 +276,7 @@ defineModule(sim, list( fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps()))), prepSpreadFitData = list(.cacheExtra = quote(c(list( fireSenseUtils::addClimateCurve, fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, - fireSenseUtils::climateCurveCols, fireSenseUtils::climateCurvePars, fireSenseUtils::softplus, + fireSenseUtils::climateCurvePars, fireSenseUtils::climateTermCols, fireSenseUtils::softplus, fireSenseUtils::climateRasterToDataTable, fireSenseUtils::climateSplitCols, fireSenseUtils::climateSplitRefPixels, fireSenseUtils::dataYearBefore, fireSenseUtils::dataYearElement, @@ -700,7 +700,7 @@ Init <- function(sim) { any(fireSenseUtils::isClimateSplitCol(colnames(sim$spreadFitPreRun$params[[ownRow]]))) ## a reused fit keeps its curve terms, and the `k` and `s` it was fitted with mod$spreadClimateCurve <- if (reuseOwnFit) - any(fireSenseUtils::isClimateCurveCol(colnames(sim$spreadFitPreRun$params[[ownRow]]))) + any(fireSenseUtils::isClimateTermCol(colnames(sim$spreadFitPreRun$params[[ownRow]]), fireSenseUtils::climateCurveSuffix)) mod$climateCurvePars <- if (isTRUE(mod$spreadClimateCurve)) fireSenseUtils::ledgerClimateCurvePars(sim$spreadFitPreRun, ownRow) ## spread: the union, for prediction; ignition (xgboost) can use every one of them diff --git a/tests/testthat/test-annualYoungAge.R b/tests/testthat/test-annualYoungAge.R index b0b3e24..041f7a4 100644 --- a/tests/testthat/test-annualYoungAge.R +++ b/tests/testthat/test-annualYoungAge.R @@ -21,6 +21,18 @@ test_that("addAnnualYoungAge puts youngAge in each fire year's table, from the d expect_true(all(c("pixelID", "CMD") %in% names(out$year2004))) }) +test_that("addAnnualYoungAge returns the list it was given, its tables changed in place (annualSpreadCovariates() relies on it)", { + tsds <- list(year2000 = tsdRaster(c(100, 3, 100, 100))) + tab <- data.table::data.table(pixelID = 1:3, CMD = 1) + ac <- list(`2000` = list(year2001 = tab)) + out <- addAnnualYoungAge(ac, tsds, list(), 15) + expect_identical(names(out), names(ac)) + expect_identical(names(out[["2000"]]), names(ac[["2000"]])) + expect_true("youngAge" %in% names(tab)) # the given table was changed by reference + expect_identical(data.table::address(out[["2000"]]$year2001), data.table::address(tab)) + expect_identical(out, ac) +}) + test_that("addAnnualYoungAge keeps the empty table of a year without fires", { tsds <- list(year2000 = tsdRaster(c(100, 3, 100, 100))) ac <- list(`2000` = list(year2001 = data.table::data.table(pixelID = 1:3, CMD = 1), From ca8f8b1e0be67b2a870a831413fe9e9c83683a1c Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 25 Nov 2026 20:25:10 -0700 Subject: [PATCH 4/4] Floor on fireSenseUtils 0.2.3.9196 (the version after fireSenseUtils#265) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- fireSense_dataPrepFit.R | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3e8bdd1..bccaae2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) -* 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.9193, version to be set after it merges). +* 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). * No prescribed burn is fitted: the spread fit's fire polygons and the ignition fit's NFDB points are selected by `fireSenseUtils::modelledFires()` (the causes of `fireCauses`, and no NBAC `PRESCRIBED`, NFDB `PRESCRIBED`, `FIRE_TYPE` or `H-PB` fire). It replaces the module's `polysOfCauses()`. Needs fireSenseUtils with `modelledFires()`; spread and ignition fits made before this included the prescribed fires of the wanted causes. diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index fa8b908..151810a 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.9193)", # 9193 (placeholder until the climate curve PR (fireSenseUtils) merges and is bumped): 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 + "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)",