From c1b2b570c25c5fdc51a714f506c88a245eb7cb88 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Thu, 19 Nov 2026 22:12:24 -0700 Subject: [PATCH 1/5] Year climate term: one definition of z in fit and predict, level-free beta, norm, NA handling, more tests Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- fireSense_ignitionPredict.R | 24 +++++++++++++++++------- tests/testthat/test-multiELF.R | 9 +++++++++ tests/testthat/test-run-values.R | 32 ++++++++++++++++++++++++++++++-- 4 files changed, 57 insertions(+), 10 deletions(-) diff --git a/NEWS.md b/NEWS.md index de21c51..74f05fe 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 core and no `NA`, `fireSenseUtils::yearClimateMeans()`, and the multiplier averages 1 over the fit years). 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`, was `IgnitionProbability_yr`), 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. diff --git a/fireSense_ignitionPredict.R b/fireSense_ignitionPredict.R index 6f99ee1..a9cc6d8 100644 --- a/fireSense_ignitionPredict.R +++ b/fireSense_ignitionPredict.R @@ -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.9183)" # 9183: yearClimateMeans(covariates, variable) unweighted, yearClimateMultiplier() norm; 9182: yearClimateColumn(), yearClimateMultiplier(); 9177: storedFitProblem(); 9168: foldModels(), foldMeanPrediction() ), loadOrder = list(after = "fireSense_dataPrepPredict"), parameters = bindrows( @@ -325,18 +325,28 @@ 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 no `NA` and with core). 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. #' #' @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. #' @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))]])) + 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 diff --git a/tests/testthat/test-multiELF.R b/tests/testthat/test-multiELF.R index 094b13d..09cef32 100644 --- a/tests/testthat/test-multiELF.R +++ b/tests/testthat/test-multiELF.R @@ -95,3 +95,12 @@ 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)) +}) diff --git a/tests/testthat/test-run-values.R b/tests/testthat/test-run-values.R index 05470f2..27e5bfc 100644 --- a/tests/testthat/test-run-values.R +++ b/tests/testthat/test-run-values.R @@ -135,14 +135,14 @@ 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 @@ -150,7 +150,35 @@ test_that("a drier year raises the expected ignitions by exp(beta * z), escapes 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("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) }) From b18fcc3ed46f9675853a6b5bcd277de41b7052e2 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Thu, 19 Nov 2026 22:50:54 -0700 Subject: [PATCH 2/5] Year climate term: coreFraction-based yearly mean; predict stops without coreFraction Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- fireSense_ignitionPredict.R | 8 ++++++-- tests/testthat/setup-toyIgnition.R | 3 ++- tests/testthat/test-covariate-scaling.R | 2 +- tests/testthat/test-run-values.R | 7 +++++++ tests/testthat/test-xgboost-objective.R | 12 ++++++++++++ 6 files changed, 29 insertions(+), 5 deletions(-) diff --git a/NEWS.md b/NEWS.md index 74f05fe..3fe4dec 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 and the prediction take the same unweighted mean over the rows with core and no `NA`, `fireSenseUtils::yearClimateMeans()`, and the multiplier averages 1 over the fit years). Escapes are untouched; fits without the term are unchanged. Needs fireSenseUtils (>= 0.2.3.9183). +* 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 core and no `NA`, `fireSenseUtils::yearClimateMeans()`, 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`, was `IgnitionProbability_yr`), 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. diff --git a/fireSense_ignitionPredict.R b/fireSense_ignitionPredict.R index a9cc6d8..78f3eb2 100644 --- a/fireSense_ignitionPredict.R +++ b/fireSense_ignitionPredict.R @@ -328,8 +328,8 @@ yearSDOf <- function(fit) { #' `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 no `NA` and with core). 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. +#' 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, one year. @@ -337,6 +337,10 @@ yearSDOf <- function(fit) { yearClimateMultiplierOf <- function(fit, covariates) { yc <- fit$modelList$yearClimate if (is.null(yc)) return(1) + 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.9183).", 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 = ", "), diff --git a/tests/testthat/setup-toyIgnition.R b/tests/testthat/setup-toyIgnition.R index 81521da..6e58eab 100644 --- a/tests/testthat/setup-toyIgnition.R +++ b/tests/testthat/setup-toyIgnition.R @@ -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 diff --git a/tests/testthat/test-covariate-scaling.R b/tests/testthat/test-covariate-scaling.R index f55f9e4..8854b4d 100644 --- a/tests/testthat/test-covariate-scaling.R +++ b/tests/testthat/test-covariate-scaling.R @@ -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)) diff --git a/tests/testthat/test-run-values.R b/tests/testthat/test-run-values.R index 27e5bfc..9eef008 100644 --- a/tests/testthat/test-run-values.R +++ b/tests/testthat/test-run-values.R @@ -177,6 +177,13 @@ test_that("a stored variable missing from the covariates, or several years in th expect_no_error(toyIgRun(withYearClimate(twoFolds(covs = noYear), toyClimate))) }) +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") diff --git a/tests/testthat/test-xgboost-objective.R b/tests/testthat/test-xgboost-objective.R index 30debe8..78e167f 100644 --- a/tests/testthat/test-xgboost-objective.R +++ b/tests/testthat/test-xgboost-objective.R @@ -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) +}) From c64ea8cd2b01faad0f46777d4cea450b95bcd90a Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Thu, 19 Nov 2026 23:26:20 -0700 Subject: [PATCH 3/5] Review fixes: raw-table year mean in predict, onMissing and cached coreFraction, level helper, warnings Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- fireSense_ignitionPredict.R | 23 +++++++++++++++++++++-- tests/testthat/test-multiELF.R | 12 ++++++++++++ tests/testthat/test-run-values.R | 7 +++++++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/NEWS.md b/NEWS.md index 3fe4dec..9d49cf2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 and the prediction take the same unweighted mean over the rows with core and no `NA`, `fireSenseUtils::yearClimateMeans()`, 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). +* 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`, was `IgnitionProbability_yr`), 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. diff --git a/fireSense_ignitionPredict.R b/fireSense_ignitionPredict.R index 78f3eb2..c6e73eb 100644 --- a/fireSense_ignitionPredict.R +++ b/fireSense_ignitionPredict.R @@ -168,6 +168,9 @@ IgnitionPredictRun <- function(sim) { sim$fireSense_IgAndEscapeDistribution <- list(ignition = fitObjective(fits, "ign"), escape = fitObjective(fits, "esc")) stopIfStoredFitsProblem(fits, igCov) + ## the year climate term averages the covariate as the fit did, before `na.omit()` (a row with an NA in some other column + ## counts, as it does in the fit's table); the rows of each fit's ELF, by the same ELF assignment + rawByFit <- rawCovariatesByFit(sim, fits) # From here, it makes predictions from each KFold, then averages them to get the expected counts for # each cell; same for Escape (expected escapes given an ignition), for every cell. @@ -179,7 +182,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, rawByFit[[f$elf]]) predsEscs[f$rows] <- fireSenseUtils::foldMeanPrediction(f$esc, covsEsc) sdIgns[f$rows] <- yearSDOf(f$ign) sdEscs[f$rows] <- yearSDOf(f$esc) @@ -323,6 +326,22 @@ yearSDOf <- function(fit) { if (is.null(sd)) 0 else sd } +#' The covariates of each fit's pixels before `na.omit()`, for the year climate term +#' +#' `IgnitionPredictRun()` predicts only pixels with no `NA` in any covariate, but the fit's year climate mean +#' (`fireSenseUtils::yearClimateMeans()`) is over the fit table as it is: only `NA` in the variable or `coreFraction` +#' leave a row out. So the term's mean is taken from the covariates as they are, for the pixels of the fit's ELF. +#' +#' @param sim A `simList`. +#' @param fits The result of `ignitionFitsByELF()` (on the pixels left after `na.omit()`). +#' @return `NULL` if no fit has a year climate term, else a list of the covariate rows of each fit's ELF, named by `elf`. +rawCovariatesByFit <- function(sim, fits) { + if (!any(vapply(fits, function(f) !is.null(f$ign$modelList$yearClimate), logical(1)))) return(NULL) + all <- sim$fireSense_igAndEscapePred_Covariates + byELF <- suppressWarnings(ignitionFitsByELF(sim, all$pixelID)) # its warning of pixels in no ELF was given for the same pixels + stats::setNames(lapply(byELF, function(f) all[f$rows]), vapply(byELF, function(f) f$elf, "")) +} + #' The year climate multiplier of a fit's expected ignitions #' #' `fireSense_ignitionFit` stores `modelList$yearClimate` (`list(variable, center, scale, beta, norm)`) with a year @@ -332,7 +351,7 @@ yearSDOf <- function(fit) { #' 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, one year. +#' @param covariates The raw (not standardised) covariates of the fit's pixels, one year, before `na.omit()` (`rawCovariatesByFit()`). #' @return One number. yearClimateMultiplierOf <- function(fit, covariates) { yc <- fit$modelList$yearClimate diff --git a/tests/testthat/test-multiELF.R b/tests/testthat/test-multiELF.R index 09cef32..c85ca69 100644 --- a/tests/testthat/test-multiELF.R +++ b/tests/testthat/test-multiELF.R @@ -104,3 +104,15 @@ test_that("each ELF's fit applies its own year climate term, or 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)) +}) + diff --git a/tests/testthat/test-run-values.R b/tests/testthat/test-run-values.R index 9eef008..e048a2b 100644 --- a/tests/testthat/test-run-values.R +++ b/tests/testthat/test-run-values.R @@ -177,6 +177,13 @@ test_that("a stored variable missing from the covariates, or several years in th 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") From 316aae7b389eac05124782e7093b41d18ebf119a Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Thu, 19 Nov 2026 23:34:32 -0700 Subject: [PATCH 4/5] One ELF assignment on the raw table; each fit keeps its rows before and after na.omit Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- fireSense_ignitionPredict.R | 40 +++++++++++++--------------------- tests/testthat/test-multiELF.R | 14 ++++++++++++ 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/fireSense_ignitionPredict.R b/fireSense_ignitionPredict.R index c6e73eb..cfdc2a6 100644 --- a/fireSense_ignitionPredict.R +++ b/fireSense_ignitionPredict.R @@ -154,23 +154,29 @@ 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) - ## the year climate term averages the covariate as the fit did, before `na.omit()` (a row with an NA in some other column - ## counts, as it does in the fit's table); the rows of each fit's ELF, by the same ELF assignment - rawByFit <- rawCovariatesByFit(sim, fits) # From here, it makes predictions from each KFold, then averages them to get the expected counts for # each cell; same for Escape (expected escapes given an ignition), for every cell. @@ -182,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, rawByFit[[f$elf]]) + 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) @@ -326,22 +332,6 @@ yearSDOf <- function(fit) { if (is.null(sd)) 0 else sd } -#' The covariates of each fit's pixels before `na.omit()`, for the year climate term -#' -#' `IgnitionPredictRun()` predicts only pixels with no `NA` in any covariate, but the fit's year climate mean -#' (`fireSenseUtils::yearClimateMeans()`) is over the fit table as it is: only `NA` in the variable or `coreFraction` -#' leave a row out. So the term's mean is taken from the covariates as they are, for the pixels of the fit's ELF. -#' -#' @param sim A `simList`. -#' @param fits The result of `ignitionFitsByELF()` (on the pixels left after `na.omit()`). -#' @return `NULL` if no fit has a year climate term, else a list of the covariate rows of each fit's ELF, named by `elf`. -rawCovariatesByFit <- function(sim, fits) { - if (!any(vapply(fits, function(f) !is.null(f$ign$modelList$yearClimate), logical(1)))) return(NULL) - all <- sim$fireSense_igAndEscapePred_Covariates - byELF <- suppressWarnings(ignitionFitsByELF(sim, all$pixelID)) # its warning of pixels in no ELF was given for the same pixels - stats::setNames(lapply(byELF, function(f) all[f$rows]), vapply(byELF, function(f) f$elf, "")) -} - #' The year climate multiplier of a fit's expected ignitions #' #' `fireSense_ignitionFit` stores `modelList$yearClimate` (`list(variable, center, scale, beta, norm)`) with a year @@ -351,7 +341,7 @@ rawCovariatesByFit <- function(sim, fits) { #' 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, one year, before `na.omit()` (`rawCovariatesByFit()`). +#' @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 diff --git a/tests/testthat/test-multiELF.R b/tests/testthat/test-multiELF.R index c85ca69..2d378b6 100644 --- a/tests/testthat/test-multiELF.R +++ b/tests/testthat/test-multiELF.R @@ -116,3 +116,17 @@ test_that("with several ELFs the year mean is of each ELF's pixels, NA rows incl 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) +}) From c2c6765daf64f12d9eb0c622da866d8b0057075b Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 06:29:30 -0700 Subject: [PATCH 5/5] fireSenseUtils floor 0.2.3.9184 (#254 merged as 9184, after #255) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- fireSense_ignitionPredict.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fireSense_ignitionPredict.R b/fireSense_ignitionPredict.R index cfdc2a6..4a8e29b 100644 --- a/fireSense_ignitionPredict.R +++ b/fireSense_ignitionPredict.R @@ -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.9183)" # 9183: yearClimateMeans(covariates, variable) unweighted, yearClimateMultiplier() norm; 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( @@ -349,7 +349,7 @@ yearClimateMultiplierOf <- function(fit, 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.9183).", call. = FALSE) + "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 = ", "),