Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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 `<table>_<ELF>.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 `<C>_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.
Expand Down
38 changes: 38 additions & 0 deletions R/saveFitTables.R
Original file line number Diff line number Diff line change
@@ -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 `<object>_<ELF>.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)
}
17 changes: 16 additions & 1 deletion fireSense_dataPrepFit.R
Original file line number Diff line number Diff line change
Expand Up @@ -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,",
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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).
Expand All @@ -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)
},
Expand Down
2 changes: 1 addition & 1 deletion tests/testthat/test-metadata.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion tests/testthat/test-neverCache.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
85 changes: 85 additions & 0 deletions tests/testthat/test-saveFitTables.R
Original file line number Diff line number Diff line change
@@ -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\\)")
})