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
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# fireSense_ignitionPredict (development version)

* A fit with a spatial field (`modelList$spatialField` of fireSense_ignitionFit's new `spatialField = "twoStage"`) has each pixel's expected ignitions multiplied by `exp(f)`, constant in time. The field is rasterised and projected to `ignitionFitRTM` once per fit (`spatialFieldFactorOf()`, kept in `mod$spatialFactor`), not every year; a pixel the field does not reach, or that is `NA` in it, has a factor of 1, and each ELF's fit applies its own field to its own pixels. Escapes are untouched; fits without a field are unchanged. Needs fireSenseUtils (>= 0.2.3.9199).
* An escape fit with a year climate term (`modelList$yearClimate` of fireSense_ignitionFit's new `escapeYearClimate`) has its expected escapes multiplied by it, from the same year mean of the covariates as the ignitions' term (`yearClimateMultiplierOf()` now takes either fit). A logistic term (fireSense_ignitionFit's `yearClimateShape = "logistic"`) is applied the same way, from the stored fit, through `fireSenseUtils::yearClimateMultiplier()`. A fit without the term is unchanged. Needs fireSenseUtils (>= 0.2.3.9195).
* A fit with a year climate term (`modelList$yearClimate` of fireSense_ignitionFit's new `ignitionYearClimate`) has its expected ignitions multiplied by `exp(beta * z)`, `z` this year's standardised mean of the climate covariate over the ELF's pixels (`fireSenseUtils::yearClimateMultiplier()`; the fit and the prediction take the same unweighted mean over the rows with the covariate and core, `fireSenseUtils::yearClimateMeans()`, in the predict taken before `na.omit()` so a pixel with an NA in another column still counts, and the multiplier averages 1 over the fit years). The covariates must carry `coreFraction` (added by fireSense_dataPrepPredict, in the same way as for the fit): without it a fit that has the term stops with a message. Escapes are untouched; fits without the term are unchanged. Needs fireSenseUtils (>= 0.2.3.9183).
* The yearly ignition and escape probability map (`.plots = "png"`) is bigger. Its png is now 10 x 8 inches at 144 dpi (1440 x 1152 pixels), as fireSense_burn's; it was R's `png()` default of 480 x 480, which looked small in `SpaDES.shiny::shine()`.
Expand Down
30 changes: 27 additions & 3 deletions fireSense_ignitionPredict.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ defineModule(sim, list(
"data.table", "magrittr", "terra", "xgboost (>= 3.0.0)",
"PredictiveEcology/SpaDES.core@development (>= 3.0.4)",
"PredictiveEcology/reproducible@development",
"PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9195)" # 9195: fireSenseUtils#264 (yearClimateMultiplier() reads the logistic term, logisticYearCurve()); TODO change if another fireSenseUtils PR merges before #264; 9194: annualYearWeights(), standardiseYearClimate() (#263); 9184: yearClimateMeans(covariates, variable) unweighted, yearClimateMultiplier() norm; 9182: yearClimateColumn(), yearClimateMultiplier(); 9177: storedFitProblem(); 9168: foldModels(), foldMeanPrediction()
"PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9199)" # 9199: the fireSenseUtils PR that adds spatialFieldFactor() (TODO set to the version its merge is bumped to); 9195: fireSenseUtils#264 (yearClimateMultiplier() reads the logistic term, logisticYearCurve()); TODO change if another fireSenseUtils PR merges before #264; 9194: annualYearWeights(), standardiseYearClimate() (#263); 9184: yearClimateMeans(covariates, variable) unweighted, yearClimateMultiplier() norm; 9182: yearClimateColumn(), yearClimateMultiplier(); 9177: storedFitProblem(); 9168: foldModels(), foldMeanPrediction()
),
loadOrder = list(after = "fireSense_dataPrepPredict"),
parameters = bindrows(
Expand Down Expand Up @@ -146,7 +146,9 @@ doEvent.fireSense_ignitionPredict <- function(sim, eventTime, eventType, debug =
#' pixel with covariates (`fireSenseUtils::foldMeanPrediction()`), and gives each pixel its fits' year-effect sd
#' (`yearSDOf()`) and, when they have one, their fitted effect of this year (`yearEffectOf()`). A fit with a year
#' climate term (`modelList$yearClimate`, `fireSense_ignitionFit`'s `ignitionYearClimate` and `escapeYearClimate`) has its
#' expected ignitions, or escapes, multiplied by `yearClimateMultiplierOf()`, the same year's mean for both. Nothing is
#' expected ignitions, or escapes, multiplied by `yearClimateMultiplierOf()`, the same year's mean for both, and a fit
#' with a spatial field (`modelList$spatialField`, `fireSense_ignitionFit`'s `spatialField = "twoStage"`) has its expected
#' ignitions multiplied by `exp(f)` of the pixel (`spatialFieldFactorOf()`). Nothing is
#' drawn: `fireSense_burn` draws ignitions and escapes from these means,
#' with the distribution named in `fireSense_IgAndEscapeDistribution`.
#'
Expand Down Expand Up @@ -189,7 +191,8 @@ IgnitionPredictRun <- function(sim) {
covsIgn <- if (rescaleVars) scaleAsFit(covsHere, f$ign$scaleData, "fireSense_IgnitionFitted") else covsHere
covsEsc <- if (rescaleVars) scaleAsFit(covsHere, f$esc$scaleData, "fireSense_EscapeFitted") else covsHere
## `covariates` of `yearClimateMultiplierOf()` is read only by a fit with a term (lazy), the same year mean for both
predsIgns[f$rows] <- fireSenseUtils::foldMeanPrediction(f$ign, covsIgn) * yearClimateMultiplierOf(f$ign, igCovAll[f$allRows])
predsIgns[f$rows] <- fireSenseUtils::foldMeanPrediction(f$ign, covsIgn) * yearClimateMultiplierOf(f$ign, igCovAll[f$allRows]) *
spatialFieldFactorOf(f$ign, f$elf, sim$ignitionFitRTM)[igCov$pixelID[f$rows]]
predsEscs[f$rows] <- fireSenseUtils::foldMeanPrediction(f$esc, covsEsc) * yearClimateMultiplierOf(f$esc, igCovAll[f$allRows])
sdIgns[f$rows] <- yearSDOf(f$ign)
sdEscs[f$rows] <- yearSDOf(f$esc)
Expand Down Expand Up @@ -333,6 +336,27 @@ yearSDOf <- function(fit) {
if (is.null(sd)) 0 else sd
}

#' The spatial field factor of a fit's expected ignitions, on the grid to predict
#'
#' `fireSense_ignitionFit` stores, with `spatialField = "twoStage"`, `modelList$spatialField`: the field `f`
#' (`fireSenseUtils::fitSpatialField()`), constant in time. The expected ignitions of each pixel are multiplied by
#' `exp(f)` (`fireSenseUtils::spatialFieldFactor()`: 1 for a pixel the field does not reach, or `NA` in it, and for a fit
#' without a field). The factor of every cell of `template` is made once per fit, rasterised and projected to the grid
#' to predict, and kept in `mod$spatialFactor` for the following years; it is made again if the fit's field is not
#' the kept one.
#'
#' @param fit A `fireSense_IgnitionFitted`.
#' @param elf The fit's name in `ignitionFitsByELF()`, which keeps the factors of the ELFs apart.
#' @param template `sim$ignitionFitRTM`, the grid to predict on.
#' @return Numeric, one per cell of `template`; all 1 for a fit without a field.
spatialFieldFactorOf <- function(fit, elf, template) {
field <- fit$modelList$spatialField
kept <- mod$spatialFactor[[elf]]
if (is.null(kept) || !identical(kept$field, field))
mod$spatialFactor[[elf]] <- list(field = field, factor = fireSenseUtils::spatialFieldFactor(field, template))
mod$spatialFactor[[elf]]$factor
}

#' The year climate multiplier of a fit's expected ignitions or escapes
#'
#' `fireSense_ignitionFit` stores `modelList$yearClimate` (`list(variable, center, scale, beta, norm)`) with a year
Expand Down
6 changes: 6 additions & 0 deletions tests/testthat/setup-toyIgnition.R
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,9 @@ evOf <- function(dt, type) {
df <- as.data.frame(dt)
df[df$moduleName == "fireSense_ignitionPredict" & df$eventType == type, , drop = FALSE]
}

## The spatial field of a fit (fireSenseUtils::fitSpatialField()'s plain list): `f` at the cells `pixelID` of `grid`
toyField <- function(pixelID = 1:3, f = log(c(2, 0.5, 3)), grid = toyCoarse())
list(k = 30, kRequested = 30, edf = 5, grid = list(ncol = terra::ncol(grid), nrow = terra::nrow(grid),
extent = as.vector(terra::ext(grid)), crs = terra::crs(grid)),
pixelID = pixelID, f = f)
10 changes: 10 additions & 0 deletions tests/testthat/test-multiELF.R
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,13 @@ test_that("the ELF assignment (raster post-process) runs once per prediction, wi
o$fireSense_IgnitionFittedList$A$modelList$yearClimate <- list(variable = "MDC", center = 100, scale = 10, beta = 0.5, norm = 1)
expect_identical(calls(o), 1L)
})

test_that("each ELF's field multiplies its own pixels' ignitions", {
o <- multiInputs()
o$fireSense_IgnitionFittedList$A$modelList$spatialField <- toyField(1:4, rep(log(3), 4))
o$fireSense_IgnitionFittedList$B$modelList$spatialField <- toyField(1:4, rep(log(0.5), 4))
expect_equal(probVals(toyIgRun(o))[, "ignitionProb"], c(2 * 3, 5 * 0.5, 2 * 3, 5 * 0.5))
## an ELF without a field is as before
o$fireSense_IgnitionFittedList$B$modelList$spatialField <- NULL
expect_equal(probVals(toyIgRun(o))[, "ignitionProb"], c(6, 5, 6, 5))
})
50 changes: 50 additions & 0 deletions tests/testthat/test-spatialField.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
## The two-stage spatial field of the ignitions (fireSense_ignitionFit's `spatialField = "twoStage"`): a fit that has
## `modelList$spatialField` has each pixel's expected ignitions multiplied by exp(f); a pixel the field does not reach,
## or that is NA in it, has a factor of 1. The field is plain numbers (`fireSenseUtils::fitSpatialField()`).

## stage 1 predicts 1, 2, 3, 4 at the four coarse pixels
fieldFits <- function(...) toyIgInputs(list(byPixel(c(1, 2, 3, 4))), list(constant(1)), ...)

withField <- function(ins, ...) {
ins$fireSense_IgnitionFitted$modelList$spatialField <- toyField(...)
ins
}

test_that("a fit with a field has its expected ignitions multiplied by exp(f); the escapes are untouched", {
sim <- toyIgRun(withField(fieldFits()))
expect_equal(probVals(sim)[, "ignitionProb"], c(1, 2, 3, 4) * c(2, 0.5, 3, 1)) # pixel 4: no field, factor 1
expect_equal(probVals(sim)[, "escapeProb"], rep(1, 4))
})

test_that("without a field the prediction is as before", {
expect_equal(probVals(toyIgRun(fieldFits()))[, "ignitionProb"], c(1, 2, 3, 4))
expect_identical(probVals(toyIgRun(fieldFits())), probVals(toyIgRun(withField(fieldFits(), pixelID = integer(0), f = numeric(0)))))
})

test_that("an NA in the field is a factor of 1", {
expect_equal(probVals(toyIgRun(withField(fieldFits(), f = c(log(2), NA, log(3)))))[, "ignitionProb"], c(2, 2, 9, 4))
})

test_that("the field of a larger grid is projected to the prediction grid; cells it does not reach are 1", {
big <- terra::rast(nrows = 4, ncols = 4, xmin = 0, xmax = 8, ymin = 0, ymax = 8, crs = "EPSG:3005", vals = 1)
## the toy pixels 1-4 are cells 9, 10, 13, 14 of the 4 x 4 grid (its lower left 2 x 2 block); the others hold 5, which no toy pixel reads
sim <- toyIgRun(withField(fieldFits(), pixelID = c(9, 10, 13, 1, 2, 3), f = c(log(2), log(0.5), log(3), 5, 5, 5), grid = big))
expect_equal(probVals(sim)[, "ignitionProb"], c(1, 2, 3, 4) * c(2, 0.5, 3, 1), tolerance = 1e-6) # terra projects in single precision
})

test_that("the factor is made once, not every year", {
made <- 0
real <- fireSenseUtils::spatialFieldFactor
testthat::local_mocked_bindings(spatialFieldFactor = function(...) { made <<- made + 1; real(...) }, .package = "fireSenseUtils")
sim <- toyIgRun(withField(fieldFits()), times = list(start = 2001, end = 2003))
expect_identical(made, 1)
expect_equal(probVals(sim)[, "ignitionProb"], c(1, 2, 3, 4) * c(2, 0.5, 3, 1))
})

test_that("a fit with a field, saved and reloaded, predicts the same", {
ins <- withField(fieldFits())
f <- tempfile(fileext = ".rds"); on.exit(unlink(f))
saveRDS(ins$fireSense_IgnitionFitted$modelList$spatialField, f)
back <- ins; back$fireSense_IgnitionFitted$modelList$spatialField <- readRDS(f)
expect_identical(probVals(toyIgRun(back)), probVals(toyIgRun(ins)))
})