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

* 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 used the exposure-weighted mean over the core, here it is the plain mean). Escapes are untouched; fits without the term are unchanged. Needs fireSenseUtils (>= 0.2.3.9182).
* 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()`.
* The yearly map shows the escape probability beside the ignition probability (`IgnitionEscapeProbability_yr<year>`, was `IgnitionProbability_yr<year>`), both layers of `fireSense_IgAndEscapeProbRas`, and their product, the expected number of escaped fires starting in each pixel that year (`expectedEscapes`).
* New parameter `.plots` (default `"screen"`): the ignition probability map is plotted each `run` with `Plots(types = .plots)`; `NA` or `NULL` for none. The plot was gated on `.saveInterval` instead, so `.plots` (e.g. `"png"` from `.globals`) drew and saved nothing. `.saveInterval`, used for nothing else, is removed.
Expand Down
47 changes: 35 additions & 12 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.9182)" # 9182: yearClimateColumn(), yearClimateMultiplier(); 9177: storedFitProblem(); 9168: foldModels(), foldMeanPrediction()
"PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9184)" # 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 @@ -154,17 +154,26 @@ doEvent.fireSense_ignitionPredict <- function(sim, eventTime, eventType, debug =
#'
#' @return The `simList`, invisibly, with `fireSense_IgAndEscapeProbRas` and `fireSense_IgAndEscapeDistribution`.
IgnitionPredictRun <- function(sim) {
igCov <- copy(sim$fireSense_igAndEscapePred_Covariates)
igCovAll <- copy(sim$fireSense_igAndEscapePred_Covariates)
## Only pixels with no NA in any covariate are predicted, but the year climate term averages its covariate over the
## rows the fit's table would have (`fireSenseUtils::yearClimateMeans()`: only an NA in that covariate leaves a row
## out), so the ELF assignment is made once on all rows and each fit keeps both its rows.
keep <- stats::complete.cases(igCovAll)
igCov <- igCovAll[keep]

igCov <- na.omit(igCov)

paramCheckOtherMods(sim, "modelAlgorithm")
rescaleVars <- paramCheckOtherMods(sim, "rescaleVars")
# The models were fitted on covariates standardized once, over all fitting years; a year's
# own mean and sd would make every year look average.
## The fitted models: one ignition and one escape fit, or one of each per fitted ELF (named by ELF), each
## applied to the coarse pixels of its own ELF (sim$rasterToMatchLargeELF).
fits <- ignitionFitsByELF(sim, igCov$pixelID)
fits <- ignitionFitsByELF(sim, igCovAll$pixelID)
newRow <- cumsum(keep)
fits <- lapply(fits, function(f) {
f$allRows <- f$rows # into the covariates before `na.omit()`
f$rows <- newRow[f$rows[keep[f$rows]]] # into those predicted
f
})
sim$fireSense_IgAndEscapeDistribution <- list(ignition = fitObjective(fits, "ign"),
escape = fitObjective(fits, "esc"))
stopIfStoredFitsProblem(fits, igCov)
Expand All @@ -179,7 +188,7 @@ IgnitionPredictRun <- function(sim) {
# own mean and sd would make every year look average.
covsIgn <- if (rescaleVars) scaleAsFit(covsHere, f$ign$scaleData, "fireSense_IgnitionFitted") else covsHere
covsEsc <- if (rescaleVars) scaleAsFit(covsHere, f$esc$scaleData, "fireSense_EscapeFitted") else covsHere
predsIgns[f$rows] <- fireSenseUtils::foldMeanPrediction(f$ign, covsIgn) * yearClimateMultiplierOf(f$ign, covsHere)
predsIgns[f$rows] <- fireSenseUtils::foldMeanPrediction(f$ign, covsIgn) * yearClimateMultiplierOf(f$ign, if (!is.null(f$ign$modelList$yearClimate)) igCovAll[f$allRows])
predsEscs[f$rows] <- fireSenseUtils::foldMeanPrediction(f$esc, covsEsc)
sdIgns[f$rows] <- yearSDOf(f$ign)
sdEscs[f$rows] <- yearSDOf(f$esc)
Expand Down Expand Up @@ -325,18 +334,32 @@ yearSDOf <- function(fit) {

#' The year climate multiplier of a fit's expected ignitions
#'
#' `fireSense_ignitionFit` stores `modelList$yearClimate` (`list(variable, center, scale, beta)`) with a year climate
#' term; the multiplier is `fireSenseUtils::yearClimateMultiplier()` of this year's mean of the raw covariate over
#' the fit's pixels. The fit standardised with the exposure-weighted mean over the core of its ELF; here it is the
#' plain mean over the ELF's pixels. A fit without the term (older fits) gives 1.
#' `fireSense_ignitionFit` stores `modelList$yearClimate` (`list(variable, center, scale, beta, norm)`) with a year
#' climate term; the multiplier is `fireSenseUtils::yearClimateMultiplier()` of this year's mean of the raw covariate
#' over the fit's pixels, `fireSenseUtils::yearClimateMeans()`, the same definition the fit used (unweighted mean over
#' the rows with the variable and with core: it needs the `coreFraction` column `fireSense_dataPrepPredict` adds). A fit without the term (older fits) gives 1, and so does a year with no
#' usable row, with a warning. Stops if the covariates hold more than one year, or lack the variable or `coreFraction`.
#'
#' @param fit A `fireSense_IgnitionFitted`.
#' @param covariates The raw (not standardised) covariates of the fit's pixels.
#' @param covariates The raw (not standardised) covariates of the fit's pixels, one year, before `na.omit()` (`f$allRows` of `IgnitionPredictRun()`); not used by a fit without the term.
#' @return One number.
yearClimateMultiplierOf <- function(fit, covariates) {
yc <- fit$modelList$yearClimate
if (is.null(yc)) return(1)
fireSenseUtils::yearClimateMultiplier(yc, mean(covariates[[fireSenseUtils::yearClimateColumn(yc$variable, names(covariates))]]))
if (is.null(covariates[[fireSenseUtils::coreFractionTxt]]))
stop("fireSense_ignitionPredict: the fit has a year climate term, which averages the core pixels, but the ",
"covariates to predict have no `", fireSenseUtils::coreFractionTxt, "` column; ",
"fireSense_dataPrepPredict adds it (fireSenseUtils >= 0.2.3.9184).", call. = FALSE)
m <- fireSenseUtils::yearClimateMeans(covariates, yc$variable)
if (nrow(m) > 1L)
stop("fireSense_ignitionPredict: the covariates to predict hold ", nrow(m), " years (", paste(m$year, collapse = ", "),
"), but the year climate term is of one year.", call. = FALSE)
if (nrow(m) == 0L || !is.finite(m$mean)) {
warning("fireSense_ignitionPredict: no ", yc$variable, " to give the year climate multiplier of this year's ",
"ignitions; it is 1.", call. = FALSE)
return(1)
}
fireSenseUtils::yearClimateMultiplier(yc, m$mean)
}

#' A fit's fitted year effect of one year
Expand Down
3 changes: 2 additions & 1 deletion tests/testthat/setup-toyIgnition.R
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ toyCoarse <- function() {

## one row per coarse cell, as fireSense_dataPrepPredict makes them
toyIgCovariates <- function(MDC = c(100, 120, 140, 160), year = 2001) {
## `coreFraction` is what fireSense_dataPrepPredict adds (an exposure, not a covariate)
data.table::data.table(pixelID = 1:4, MDC = MDC, youngAge = c(0, 0.25, 0.5, 1),
year = year)
year = year, coreFraction = 1)
}

## The centre and scale the fit standardised its covariates with, as fireSense_ignitionFit
Expand Down
2 changes: 1 addition & 1 deletion tests/testthat/test-covariate-scaling.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ test_that("with rescaleVars = FALSE the models get the covariates exactly as sup
covs <- toyIgCovariates()
sim <- toyIgRun(oneFold(covs), params = list(rescaleVars = FALSE))
nd <- toyCalls("ign1")[[1]]
expect_setequal(names(nd), c("pixelID", "MDC", "youngAge", "year"))
expect_setequal(names(nd), c("pixelID", "MDC", "youngAge", "year", "coreFraction"))
expect_identical(nd$MDC, c(100, 120, 140, 160))
expect_identical(nd$youngAge, c(0, 0.25, 0.5, 1))
expect_identical(nd$year, rep(2001, 4))
Expand Down
35 changes: 35 additions & 0 deletions tests/testthat/test-multiELF.R
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,38 @@ test_that("with one fit, a stored fit missing features stops, naming the fit", {
o$fireSense_IgnitionFitted$modelList$model$Fold1$features <- c("MDC", "nonexistentCov")
expect_error(toyIgRun(o), "ignition fit of ELF \\(one fit\\).*nonexistentCov")
})

test_that("each ELF's fit applies its own year climate term, or none", {
## A: pixels 1, 3 (MDC 100, 140: mean 120); B: pixels 2, 4 (MDC 120, 160: mean 140)
o <- multiInputs()
o$fireSense_IgnitionFittedList$A$modelList$yearClimate <- list(variable = "MDC", center = 100, scale = 10, beta = 0.5, norm = 1)
expect_equal(probVals(toyIgRun(o))[, "ignitionProb"], c(2 * exp(1), 5, 2 * exp(1), 5)) # B has none
o$fireSense_IgnitionFittedList$B$modelList$yearClimate <- list(variable = "MDC", center = 140, scale = 10, beta = 1, norm = 2)
expect_equal(probVals(toyIgRun(o))[, "ignitionProb"], c(2 * exp(1), 5 / 2, 2 * exp(1), 5 / 2))
})

test_that("with several ELFs the year mean is of each ELF's pixels, NA rows included", {
o <- multiInputs()
## pixels 1, 3 are ELF A; 2, 4 are B. MDC 100, 140 (A) and 120, 160 (B); an NA in an unrelated column of pixel 3
o$fireSense_igAndEscapePred_Covariates <- toyIgCovariates(MDC = c(100, 120, 140, 160))
data.table::set(o$fireSense_igAndEscapePred_Covariates, NULL, "lightningDays", c(1, 1, NA, 1))
o$fireSense_IgnitionFittedList$A$modelList$yearClimate <- list(variable = "MDC", center = 100, scale = 10, beta = 0.5, norm = 1)
sim <- toyIgRun(o)
## A's mean is over pixels 1 and 3 (120), not pixel 1 only (100): z = 2; pixel 3 is dropped (NA), pixel 1 predicted 2
expect_equal(unname(probVals(sim)[1, "ignitionProb"]), 2 * exp(0.5 * 2))
})


test_that("the ELF assignment (raster post-process) runs once per prediction, with or without a year climate term", {
calls <- function(o) {
n <- 0L
orig <- reproducible::postProcess
testthat::local_mocked_bindings(postProcess = function(...) { n <<- n + 1L; orig(...) }, .package = "reproducible")
toyIgRun(o)
n
}
o <- multiInputs()
expect_identical(calls(o), 1L)
o$fireSense_IgnitionFittedList$A$modelList$yearClimate <- list(variable = "MDC", center = 100, scale = 10, beta = 0.5, norm = 1)
expect_identical(calls(o), 1L)
})
46 changes: 44 additions & 2 deletions tests/testthat/test-run-values.R
Original file line number Diff line number Diff line change
Expand Up @@ -135,22 +135,64 @@ withYearClimate <- function(ins, yc) {
ins$fireSense_IgnitionFitted$modelList$yearClimate <- yc
ins
}
toyClimate <- list(variable = "MDC", center = 130, scale = 20, beta = 0.5)
toyClimate <- list(variable = "MDC", center = 130, scale = 20, beta = 0.5, norm = 1)

test_that("a fit without a year climate term gives a multiplier of 1", {
expect_identical(yearClimateMultiplierOf(twoFolds()$fireSense_IgnitionFitted, toyIgCovariates()), 1)
expect_equal(probVals(toyIgRun(twoFolds()))[, "ignitionProb"], c(0, 3, 3, 0))
})

test_that("a drier year raises the expected ignitions by exp(beta * z), escapes untouched", {
test_that("a drier year raises the expected ignitions by exp(beta * z) / norm, escapes untouched", {
## the mean MDC of the toy year is 130 = the fit's centre: no change
expect_equal(probVals(toyIgRun(withYearClimate(twoFolds(), toyClimate)))[, "ignitionProb"], c(0, 3, 3, 0))
## 20 drier: z = 1
dry <- twoFolds(covs = toyIgCovariates(MDC = c(100, 120, 140, 160) + 20))
sim <- toyIgRun(withYearClimate(dry, toyClimate))
expect_equal(probVals(sim)[, "ignitionProb"], c(0, 3, 3, 0) * exp(0.5))
expect_equal(probVals(sim)[, "escapeProb"], rep(1, 4))
expect_equal(probVals(toyIgRun(withYearClimate(dry, modifyList(toyClimate, list(norm = 2)))))[, "ignitionProb"],
c(0, 3, 3, 0) * exp(0.5) / 2)
## beta 0 is no term
sim0 <- toyIgRun(withYearClimate(dry, modifyList(toyClimate, list(beta = 0))))
expect_equal(probVals(sim0)[, "ignitionProb"], c(0, 3, 3, 0))
## the raw column is used whether or not the models see standardised covariates
expect_equal(probVals(toyIgRun(withYearClimate(dry, toyClimate), params = list(rescaleVars = FALSE)))[, "ignitionProb"],
c(0, 3, 3, 0) * exp(0.5))
})

test_that("the multiplier is the fit's definition: unweighted mean over the rows with core and no NA", {
covs <- data.frame(year = 2001, MDC = c(100, 140, 1000, 120), coreFraction = c(1, 0.1, 0, 1), other = c(1, 1, 1, NA))
## rows 1 and 2 count (row 3 has no core, row 4 an NA): mean 120, whatever the coreFraction of the others
expect_equal(yearClimateMultiplierOf(withYearClimate(twoFolds(), toyClimate)$fireSense_IgnitionFitted, covs),
exp(0.5 * (120 - 130) / 20))
})

test_that("a stored variable missing from the covariates, or several years in them, stop", {
expect_error(toyIgRun(withYearClimate(twoFolds(), modifyList(toyClimate, list(variable = "CMDsm")))),
"not among the covariates")
two <- twoFolds(covs = toyIgCovariates(year = c(2001, 2001, 2002, 2002)))
expect_error(toyIgRun(withYearClimate(two, toyClimate)), "hold 2 years")
## no year column: all rows are one year
noYear <- toyIgCovariates(); data.table::set(noYear, NULL, "year", NULL)
expect_no_error(toyIgRun(withYearClimate(twoFolds(covs = noYear), toyClimate)))
})

test_that("the year mean is taken before na.omit: an NA in an unrelated column does not leave the pixel out of it", {
covs <- toyIgCovariates(MDC = c(120, 140, 160, 180)) # mean 150 over the four pixels, 153.3 without pixel 2
data.table::set(covs, NULL, "lightningDays", c(1, NA, 1, 1))
sim <- toyIgRun(withYearClimate(twoFolds(covs = covs), toyClimate))
expect_equal(probVals(sim)[c(1, 3, 4), "ignitionProb"], c(0, 3, 0) * exp(0.5 * (150 - 130) / 20))
})

test_that("a fit with a year climate term and covariates without coreFraction stops with a clear message", {
noCore <- toyIgCovariates(); data.table::set(noCore, NULL, "coreFraction", NULL)
expect_error(toyIgRun(withYearClimate(twoFolds(covs = noCore), toyClimate)), "no `coreFraction` column")
## a fit without the term does not need it
expect_no_error(toyIgRun(twoFolds(covs = noCore)))
})

test_that("a year with no usable covariate gives a multiplier of 1 and a warning", {
expect_warning(m <- yearClimateMultiplierOf(withYearClimate(twoFolds(), toyClimate)$fireSense_IgnitionFitted,
toyIgCovariates()[integer(0), , drop = FALSE]), "it is 1")
expect_identical(m, 1)
})
12 changes: 12 additions & 0 deletions tests/testthat/test-xgboost-objective.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,15 @@ test_that("xgboost folds with different objectives stop", {
fits <- list(ledgerFit(realBooster(), realBooster("reg:squarederror")))
expect_error(fitObjective(fits, "ign"), "different objectives: count:poisson, reg:squarederror")
})

test_that("real boosters predict covariates that carry coreFraction, which is not a feature, and the fit still stores it unscaled", {
skip_if_not_installed("xgboost")
fit <- ledgerFit(realBooster(), realBooster(seed = 2))$ign
covs <- data.frame(pixelID = 1:3, MDC = c(-1, 0, 1), youngAge = c(0, 1, 0), year = 2001)
withCore <- cbind(covs, coreFraction = c(1, 0.5, 0))
expect_equal(fireSenseUtils::foldMeanPrediction(fit, withCore), fireSenseUtils::foldMeanPrediction(fit, covs))
expect_null(fireSenseUtils::storedFitProblem(fit, withCore))
## scaling the covariates as the fit did leaves coreFraction alone
sd <- toyScaleData()
expect_identical(scaleAsFit(data.table::as.data.table(withCore), sd, "fireSense_IgnitionFitted")$coreFraction, withCore$coreFraction)
})