From 164a5d127b2eaac96c0884593f92e7e256d48faf Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 27 Nov 2026 19:30:52 -0700 Subject: [PATCH] saveFitTables: write the ignition and escape fit tables to outputPath(sim) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 + R/saveFitTables.R | 38 +++++++++++++ fireSense_dataPrepFit.R | 17 +++++- tests/testthat/test-metadata.R | 2 +- tests/testthat/test-neverCache.R | 2 +- tests/testthat/test-saveFitTables.R | 85 +++++++++++++++++++++++++++++ 6 files changed, 143 insertions(+), 3 deletions(-) create mode 100644 R/saveFitTables.R create mode 100644 tests/testthat/test-saveFitTables.R diff --git a/NEWS.md b/NEWS.md index bccaae23..e7be3e47 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fireSense_dataPrepFit 1.3.0.9011 (development version) +* New parameter `saveFitTables` (default `character(0)`: nothing is written). `"ignition"` and/or `"escape"` write `fireSense_ignitionCovariates` and `fireSense_escapeCovariates`, the exact tables the fits are trained on, to `outputPath(sim)` as `_.qs2` (qs2) and list them in `outputs(sim)`, so an analysis outside the fit can use them. They are written by a new event `saveFitTables` after the prep events: it is never cached (`.neverCache`) and reads the tables from the simList, so a cached `prepIgnitionFitData` still writes them. No table changes, and the parameter is not in the cache keys (`cacheKey = FALSE`). + * New parameter `spreadClimateCurve` (`FALSE` by default: nothing changes). `TRUE` adds a covariate `_curve = softplus(C - k, s)` (smooth, no corner) for each spread climate variable `C`, with its own coefficient, so the climate response can steepen in dry years; `k` and `s` are the ELF's median and sd of `C` over the burnable pixels of all the fit years. They are in `sim$climateCurvePars`, which `fireSense_spreadFit` writes to the ledger row, and `fireSense_spreadPredict` builds the term from them. A negative coefficient flattens the dry side. A reused ledger fit keeps its own curve terms and their `k` and `s`. The code is `fireSenseUtils::climateCurvePars()`, `addClimateCurve()`, `softplus()` and `climateTermCols()`, in the `prepSpreadFitData` cache key. Needs `fireSense_spreadFit`, `fireSense_spreadPredict` and fireSenseUtils with the curve (fireSenseUtils >= 0.2.3.9196). * 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/saveFitTables.R b/R/saveFitTables.R new file mode 100644 index 00000000..7c094a7c --- /dev/null +++ b/R/saveFitTables.R @@ -0,0 +1,38 @@ +## The fit tables `saveFitTables` can write: parameter value -> the simList object +fitTableObjects <- c(ignition = "fireSense_ignitionCovariates", escape = "fireSense_escapeCovariates") + +#' The events to schedule for `saveFitTables` +#' +#' @param which character, `P(sim)$saveFitTables`. +#' @return `"saveFitTables"` if any table is asked for, otherwise `character(0)`. +saveFitTablesEvents <- function(which) { + if (length(which)) "saveFitTables" else character(0) +} + +#' Write the ignition and/or escape fit tables to `outputPath(sim)` +#' +#' Runs after the prep events, as its own uncached event, so it sees the tables whether `prepIgnitionFitData` +#' just built them or its cache restored them. It only reads them: no table and no cache key changes. Each +#' file is `_.qs2` (`sim$.ELFind`; no ELF suffix without one) and is listed in `outputs(sim)`. +#' A requested table the run did not build (`skipUnusedFitPrep`) is reported, not an error. +#' +#' @param sim a `simList`. +#' @return the `simList`, invisibly, with the files registered as outputs. +saveFitTables <- function(sim) { + which <- P(sim)$saveFitTables + if (!all(which %in% names(fitTableObjects))) + stop("saveFitTables must be among ", paste(shQuote(names(fitTableObjects)), collapse = ", "), + "; got: ", paste(shQuote(setdiff(which, names(fitTableObjects))), collapse = ", ")) + elf <- if (length(sim$.ELFind)) paste0("_", paste(sim$.ELFind, collapse = "_")) + for (obj in fitTableObjects[unique(which)]) { + if (is.null(sim[[obj]])) { + message("saveFitTables: ", obj, " was not built in this run; nothing written") + next + } + f <- file.path(SpaDES.core::outputPath(sim), paste0(obj, elf, ".qs2")) + dir.create(dirname(f), recursive = TRUE, showWarnings = FALSE) + qs2::qs_save(sim[[obj]], f) + sim <- SpaDES.core::registerOutputs(f, sim) + } + invisible(sim) +} diff --git a/fireSense_dataPrepFit.R b/fireSense_dataPrepFit.R index 6e3adfdd..3e22077a 100644 --- a/fireSense_dataPrepFit.R +++ b/fireSense_dataPrepFit.R @@ -160,6 +160,14 @@ defineModule(sim, list( "`.globals = list(skipUnusedFitPrep = FALSE)`; init stops if they differ on it or on `doFit`.", "Not part of the cache keys."), cacheKey = FALSE), + defineParameter("saveFitTables", "character", character(0), NA, NA, + paste("Which fit tables to write to `outputPath(sim)` as qs2 files, `\"ignition\"`", + "(`fireSense_ignitionCovariates`) and/or `\"escape\"` (`fireSense_escapeCovariates`); default none.", + "Each file is the exact table the fit is trained on (every covariate, `pixelID`, `year`, the response),", + "named for the table and the run's ELF (`sim$.ELFind`), and listed in `outputs(sim)`.", + "They are written by their own, never cached event after the prep events, so a cached", + "`prepIgnitionFitData` still writes them. Changes no table. Not part of the cache keys."), + cacheKey = FALSE), defineParameter("spreadClimateCandidates", "character", c(fireSenseUtils::defaultClimateVariablesForFire$ignition, "Tmax_sm", "PPT_sm"), NA, NA, paste("The climate variables `climateVariablesForFire$spread = \"auto\"` chooses among (ClimateNA names,", @@ -253,8 +261,9 @@ defineModule(sim, list( defineParameter(".useCache", "logical", FALSE, NA, NA, paste("Should this entire module be run with caching activated? This is intended", "for data-type modules, where stochasticity and time are not relevant")), - defineParameter(".neverCache", "character", "init", NA, NA, + defineParameter(".neverCache", "character", c("init", "saveFitTables"), NA, NA, paste("Events that are never cached, whatever `.useCache` says (read by SpaDES.core, 3.2.1.9037 or later):", + "`saveFitTables` writes files, which a cache hit would skip.", "`init` asks Google Drive whether the spread-fit ledger already has parameters for this study area, and a cached `init` replays an older answer.")), defineParameter(".useCacheArgs", "list", list(dataPrepBuild = list(.cacheExtra = quote(list( @@ -551,6 +560,9 @@ doEvent.fireSense_dataPrepFit = function(sim, eventTime, eventType) { for (ev in prepEventsToSchedule(P(sim)$whichModulesToPrepare, fitPrepNeeded(sim), fitPrepNeeded(sim, "fireSense_ignitionFit"))) sim <- scheduleEvent(sim, start(sim), "fireSense_dataPrepFit", ev, eventPriority = 1) + for (ev in saveFitTablesEvents(P(sim)$saveFitTables)) + sim <- scheduleEvent(sim, start(sim), "fireSense_dataPrepFit", ev, eventPriority = 2) # after the prep events (1) + sim <- Init(sim) ## Priority 0 runs dataPrepBuild straight after this event and ahead of every other module's ## init (those are at .first(), i.e. 1). @@ -571,6 +583,9 @@ doEvent.fireSense_dataPrepFit = function(sim, eventTime, eventType) { prepSpreadFitData = { sim <- prepare_SpreadFit(sim) }, + saveFitTables = { + sim <- saveFitTables(sim) + }, prepSpreadFitFireData = { sim <- prepare_SpreadFitFires(sim) }, diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index 92d5f80a..80c003cb 100644 --- a/tests/testthat/test-metadata.R +++ b/tests/testthat/test-metadata.R @@ -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", "spreadClimateCurve", "spreadClimateSplit", "spreadCovariates", "spreadInteractions", "spreadIntercept", "targetFuelClasses", + "spreadFitGoogleDriveFolder", "saveFitTables", "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-neverCache.R b/tests/testthat/test-neverCache.R index 68ffdc66..3c7b04c7 100644 --- a/tests/testthat/test-neverCache.R +++ b/tests/testthat/test-neverCache.R @@ -3,7 +3,7 @@ test_that(".neverCache is declared and SpaDES.core refuses to cache those events whatever .useCache says", { md <- SpaDES.core::moduleMetadata(module = moduleName, path = modulePath) declared <- md$parameters$default[[which(md$parameters$paramName == ".neverCache")]] - expect_setequal(declared, c("init")) + expect_setequal(declared, c("init", "saveFitTables")) eventIsCached <- utils::getFromNamespace(".eventIsCached", "SpaDES.core") for (useCache in list(c(".inputObjects", declared), TRUE)) { for (ev in declared) diff --git a/tests/testthat/test-saveFitTables.R b/tests/testthat/test-saveFitTables.R new file mode 100644 index 00000000..a5b232e1 --- /dev/null +++ b/tests/testthat/test-saveFitTables.R @@ -0,0 +1,85 @@ +## `saveFitTables` writes the ignition / escape fit tables to outputPath(sim) after they are built, so analyses +## outside the fit can use the exact table a fit was trained on. It is its own uncached event: the tables come +## from the simList, whether `prepIgnitionFitData` just ran or its cache restored them. + +tableSim <- function(saveFitTables, outDir, ELF = "6.6.2") { + sim <- suppressMessages(SpaDES.core::simInit(paths = list(outputPath = outDir))) + sim@params <- list(fireSense_dataPrepFit = list(saveFitTables = saveFitTables)) + sim@current <- data.table::data.table(moduleName = "fireSense_dataPrepFit") + sim$.ELFind <- ELF + sim$fireSense_ignitionCovariates <- data.table::data.table( + pixelID = c(3L, 5L, 3L), year = c(2001, 2001, 2002), ignitions = c(0L, 1L, 2L), + CMDsm = c(1.5, 2.5, 3.5), coreFraction = c(1, 0.5, 1)) + sim$fireSense_escapeCovariates <- data.frame(sim$fireSense_ignitionCovariates, escapes = c(0L, 1L, 1L)) |> data.table::as.data.table() + sim +} + +## the module's functions get `P()` from the running simList; a test supplies it +runSave <- function(sim) { + env <- new.env(parent = environment(saveFitTables)) + env$P <- function(sim) sim@params$fireSense_dataPrepFit + f <- saveFitTables + environment(f) <- env + f(sim) +} + +test_that("saveFitTables writes each requested table, identical to the one in the simList, and registers it", { + out <- withr::local_tempdir() + sim <- tableSim(c("ignition", "escape"), out) + sim <- runSave(sim) + files <- list.files(out, "\\.qs2$") + expect_length(files, 2L) + expect_true(all(grepl("6.6.2", files, fixed = TRUE))) + ign <- qs2::qs_read(file.path(out, grep("ignition", files, value = TRUE))) + esc <- qs2::qs_read(file.path(out, grep("escape", files, value = TRUE))) + expect_equal(ign, sim$fireSense_ignitionCovariates) + expect_equal(esc, sim$fireSense_escapeCovariates) + expect_setequal(basename(SpaDES.core::outputs(sim)$file), files) +}) + +test_that("saveFitTables writes only the tables asked for, and nothing by default", { + out <- withr::local_tempdir() + runSave(tableSim("ignition", out)) + expect_length(list.files(out), 1L) + out2 <- withr::local_tempdir() + runSave(tableSim(character(0), out2)) + expect_length(list.files(out2), 0L) + tbl <- moduleParamTable() + expect_identical(tbl$default[[which(tbl$paramName == "saveFitTables")]], character(0)) + expect_false(tbl$cacheKey[[which(tbl$paramName == "saveFitTables")]]) # changing it does not re-run cached events +}) + +test_that("saveFitTables does not change the tables", { + sim <- tableSim(c("ignition", "escape"), withr::local_tempdir()) + before <- data.table::copy(sim$fireSense_ignitionCovariates) + sim <- runSave(sim) + expect_identical(sim$fireSense_ignitionCovariates, before) +}) + +test_that("a table the run did not build is skipped with a message, not an error", { + out <- withr::local_tempdir() + sim <- tableSim("escape", out) + sim$fireSense_escapeCovariates <- NULL + expect_message(runSave(sim), "fireSense_escapeCovariates") + expect_length(list.files(out), 0L) +}) + +test_that("an unknown table name is refused", { + expect_error(runSave(tableSim("spread", withr::local_tempdir())), "saveFitTables") +}) + +test_that("the event is scheduled only when tables are requested, runs after the prep events, and is never cached", { + md <- SpaDES.core::moduleMetadata(module = moduleName, path = modulePath) + declared <- md$parameters$default[[which(md$parameters$paramName == ".neverCache")]] + expect_true("saveFitTables" %in% declared) # a cache hit would skip the write + expect_identical(saveFitTablesEvents(character(0)), character(0)) + expect_identical(saveFitTablesEvents("ignition"), "saveFitTables") +}) + +test_that("init schedules the event after the prep events (priority 2, they are 1) and the dispatcher runs it", { + defs <- moduleDefs() + init <- paste(deparse(defs[["doEvent.fireSense_dataPrepFit"]]), collapse = "\n") + expect_match(init, "saveFitTablesEvents\\(P\\(sim\\)\\$saveFitTables\\)") + expect_match(init, "\"saveFitTables\", eventPriority = 2|ev, eventPriority = 2") + expect_match(init, "saveFitTables = \\{\\s*sim <- saveFitTables\\(sim\\)") +})