diff --git a/NEWS.md b/NEWS.md index a81d70a..bccaae2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # 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.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. * `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..e8b94e1 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 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) { +spreadRHS <- function(spreadCovariates, spreadVars, vegColsForRHS, spreadInteractions = character(), climateSplit = 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(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 e6ad689..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.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.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)", @@ -217,6 +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("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`, `_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::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 `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, @@ -264,7 +275,8 @@ defineModule(sim, list( fireSenseUtils::rasterFireSpreadPoints, spreadFitPreRun = sim$spreadFitPreRun), fireSenseUtils::harmonizeFireDataDeps(), fireSenseUtils::escapeFireSetDeps()))), prepSpreadFitData = list(.cacheExtra = quote(c(list( - fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, + fireSenseUtils::addClimateCurve, fireSenseUtils::bufferToArea, fireSenseUtils::chooseDomSecFuelClasses, + fireSenseUtils::climateCurvePars, fireSenseUtils::climateTermCols, fireSenseUtils::softplus, fireSenseUtils::climateRasterToDataTable, fireSenseUtils::climateSplitCols, fireSenseUtils::climateSplitRefPixels, fireSenseUtils::dataYearBefore, fireSenseUtils::dataYearElement, @@ -416,6 +428,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("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", events = "prepEscapeFitData"), @@ -682,6 +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 curve terms, and the `k` and `s` it was fitted with + mod$spreadClimateCurve <- if (reuseOwnFit) + 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 sim$climateVariablesForFire <- addFitClimateVariablesForFire(sim$climateVariablesForFire, fitClimVars) @@ -1090,7 +1111,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), + climateCurve = useClimateCurve(mod, Par)) ## this is a funny way to get years but avoids years with 0 fires allYears <- unname(unlist(mod$allYears)) @@ -1119,7 +1141,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), + 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 @@ -1166,6 +1190,15 @@ prepare_SpreadFit <- function(sim) { #' @return logical(1). useClimateSplit <- function(mod, Par) isTRUE(mod$spreadClimateSplit %||% Par$spreadClimateSplit) +#' Does the spread climate have a curve term? +#' +#' 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). +useClimateCurve <- function(mod, Par) isTRUE(mod$spreadClimateCurve %||% Par$spreadClimateCurve) + #' 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 +1212,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 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 two terms) and `youngAge`. +#' 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) { + 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) |> @@ -1193,11 +1230,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)) { + 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))) - fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), climateAt(burnableIndex), by = fireSenseUtils::yearTxt) + burnableClimate <- climateAt(burnableIndex) + } + ## 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 (useCurve) fireSenseUtils::addClimateCurve(fbl, pars) + if (isTRUE(climateSplit)) + fireSenseUtils::splitSpreadClimate(fbl, names(spreadClimate), burnableClimate, by = fireSenseUtils::yearTxt) annuals <- split(fbl, by = fireSenseUtils::yearTxt, keep.by = FALSE) @@ -1217,8 +1262,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 (useCurve) attr(annualCovariates, fireSenseUtils::spreadFitClimateCurveParsTxt) <- pars + 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..10872c8 --- /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-spreadClimateCurve.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-spreadClimateCurve.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-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), diff --git a/tests/testthat/test-metadata.R b/tests/testthat/test-metadata.R index c681ebf..92d5f80 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(climateCurvePars = "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", "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-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)