From 491a449d001d5a25c9da4d7ec59ae054e324ac1a Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 16 Nov 2026 17:24:56 -0700 Subject: [PATCH 1/6] Predict a split climate fit (_yr, _dev terms) from the year's climate over the ELF's own burnable pixels Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- NEWS.md | 1 + fireSense_spreadPredict.R | 28 +++++++++++-- tests/testthat/test-climateSplit.R | 64 ++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 4 deletions(-) create mode 100644 tests/testthat/test-climateSplit.R diff --git a/NEWS.md b/NEWS.md index f62d92b..870d563 100644 --- a/NEWS.md +++ b/NEWS.md @@ -9,6 +9,7 @@ - New parameter `.plots` (default `"screen"`): the spread probability map (`fireSense_SpreadPredicted`) is plotted each `run` (`SpreadProbability_yr`). `NA` or `NULL` for none. - A ledger row with an interaction coefficient (`a:b`, e.g. `CMD:dom_agb_Pice_mar`, from a `fireSense_spreadFit` fitted with `fireSense_dataPrepFit`'s `spreadInteractions = "climate:fuel"`) predicts with it: `spreadProbOneELF()` needs the covariates `a` and `b` (and their ranges in `covMinMax_spread`), and `fireSenseUtils::spreadProbFromIntegerCovs()` forms their product after each is rescaled and centred with the row's `covCentre_spread` entry for it (0 where `youngAge` cleared the fuel), and multiplies it by the coefficient, as the fit does. A row without interactions predicts exactly as before. Needs fireSenseUtils >= 0.2.3.9177 (#242). +* A ledger row fitted with the split climate covariate (`fireSense_dataPrepFit`'s `spreadClimateSplit`: parameters `_yr` and `_dev`) is predicted with the same two terms: `spreadProbOneELF()` makes them from the year's climate with `fireSenseUtils::splitSpreadClimate()`, the median being over the ELF's own burnable pixels (`elfPixels`: every row with one fitted ELF, the ELF's own pixels of `rasterToMatchLargeELF` with several, not the blend zone). A row without split terms predicts as before. Needs fireSenseUtils with `splitSpreadClimate()` (Depends-on PredictiveEcology/fireSenseUtils); the `reqdPkgs` floor is set after that merges. - With `paramSets`: the cache of a parameter set's surface no longer reads all the values of `flammableRTM` and `rasterToMatchLargeELF` every replicate (a new raster object or a change at 1000 sampled cells is a change) and returns the stored surface without copying it (a changed stored surface is recomputed). On a 20-million-cell raster a replicate that reuses a surface takes 0.35 s instead of 0.9 s, most of it SpaDES. `paramSets` stops if the ledger rows have the simulated ELF twice, or if a file of ledger rows has none for it. diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index a1ba3ed..3348ab7 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -302,6 +302,8 @@ spreadPredictRun <- function(sim) { p <- do.call(spreadProbOneELF, c(list(covs[these], params = parsI, covMinMax = sa$covMinMax_spread[[i]], yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, lowerSpreadProb = P(sim)$lowerSpreadProb, + elfPixels = if (any(fireSenseUtils::isClimateSplitCol(names(parsI)))) + which(ELFcellLabels(sim$rasterToMatchLargeELF[[1]]) %in% ids[i]), covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i), powerLawPc50 = ledgerPowerLawPc50(sa, i)), lks[[i]])) rows <- these[match(p$pixelID, covs$pixelID[these])] @@ -443,6 +445,16 @@ rasterVersion <- function(name, r) { cur$version } +#' The ELF of each cell +#' +#' @param r one layer of `sim$rasterToMatchLargeELF`: categorical (the labels are the second column of its levels) or the id. +#' @return character, the ELF label of each cell, in cell order. +ELFcellLabels <- function(r) { + v <- terra::values(r, mat = FALSE) + lv <- terra::levels(r)[[1]] + if (is.data.frame(lv) && NCOL(lv) >= 2) as.character(lv[[2]][match(v, lv[[1]])]) else as.character(v) +} + #' Each ELF's weight at each pixel #' #' An ELF's raw weight is 1 on its own pixels and falls linearly to 0 at `width` metres from them (distance @@ -465,9 +477,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { stop("fireSense_spreadPredict: sim$rasterToMatchLargeELF is not on the grid of sim$flammableRTM", call. = FALSE) r <- elfRas[[1]] - v <- terra::values(r, mat = FALSE) - lv <- terra::levels(r)[[1]] - lab <- if (is.data.frame(lv) && NCOL(lv) >= 2) as.character(lv[[2]][match(v, lv[[1]])]) else as.character(v) + lab <- ELFcellLabels(r) w <- vapply(ids, function(id) { core <- r; terra::values(core) <- ifelse(lab %in% id, 1, NA) if (all(is.na(terra::values(core, mat = FALSE)))) return(numeric(length(pixelID))) @@ -489,6 +499,9 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' @param params one-row `data.frame`: the ELF's parameter set for this replicate (`paramSetForRep()`). #' @param covMinMax the ELF's `covMinMax_spread` (`ledgerCovMinMax()`): the ranges the fit rescaled its #' covariates with. Every fitted covariate must be a column of it, or it is left unscaled. +#' @param elfPixels integer; the `pixelID`s of the ELF's own burnable pixels, the pixels the year's median of a split +#' climate covariate (`_yr`, `_dev`; `fireSenseUtils::splitSpreadClimate()`) is taken over, as in the fit. +#' `NULL` (one fitted ELF) is every row of `covs`. Not used by a fit without split terms. #' @param yr,maxFireSpread,lowerSpreadProb as for `fireSenseUtils::spreadProbFromIntegerCovs()` and #' `fireSenseUtils::logisticAll()`. #' @param covCentre the ELF's `covCentre_spread` (`ledgerCovCentre()`): the covariate means the fit subtracted @@ -525,7 +538,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' also `linearPredictor`, the `x` that `spreadProb` is the link of (the fuels' only with climate in the ceiling), and #' the attribute `linkPars`, the link's parameters (`fireSenseUtils::linearLinkPars()`): a vector, or with climate in #' the ceiling a matrix with one row per pixel. -spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, +spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, elfPixels = NULL, covCentre = NULL, climateRef = NULL, powerLawPc50 = NULL, powerLawGamma = NULL, powerLawShape = fireSenseUtils::spreadPowerLawShape, link = if (!is.null(powerLawGamma)) "powerLaw", @@ -571,6 +584,13 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp ## the intercept, if the fit has one, is a coefficient with no covariate: it multiplies a column of 1s hasIntercept <- fireSenseUtils::spreadInterceptTxt %in% names(params) fitted <- setdiff(names(params), c(unlist(fireSenseUtils::logisticParamNames), fireSenseUtils::spreadInterceptTxt)) + ## a fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as `_yr` and `_dev`: the + ## year's median of the variable over this ELF's burnable pixels, and the departure from it, made as the fit made them + splitVars <- unique(fireSenseUtils::climateSplitBase(fitted[fireSenseUtils::isClimateSplitCol(fitted)])) + if (length(splitVars) && all(splitVars %in% names(covs))) { + ref <- covs[if (is.null(elfPixels)) TRUE else covs$pixelID %in% elfPixels, splitVars, with = FALSE] + fireSenseUtils::splitSpreadClimate(covs, splitVars, ref) + } ## an interaction (`CMD:fuel`) is made from its two covariates by spreadProbFromIntegerCovs(), as in the fit needed <- fireSenseUtils::spreadSourceCols(fitted) noCov <- setdiff(needed, names(covs)) diff --git a/tests/testthat/test-climateSplit.R b/tests/testthat/test-climateSplit.R new file mode 100644 index 0000000..37e47a7 --- /dev/null +++ b/tests/testthat/test-climateSplit.R @@ -0,0 +1,64 @@ +## A fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as two terms, `MDC_yr` (the year's +## median over the ELF's burnable pixels) and `MDC_dev` (MDC minus it). Prediction builds them from the year's +## climate with fireSenseUtils::splitSpreadClimate(), as the fit did, over the ELF's own pixels. +## +## Rescaling: MDC_yr with c(0, 200), MDC_dev with c(-100, 100) (fireSenseUtils::climateSplitRanges()). + +splitParams <- function(yr = 1.5, dev = 0.8, fuel = 1, name = "fuelA") { + d <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = yr, MDC_dev = dev, x = fuel) + names(d)[6] <- name + d +} +cmmSplit <- function(fuel = "fuelA") { + d <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), f = c(0, 8)) + data.table::setnames(d, "f", fuel) + d +} + +test_that("a split fit predicts from the year's median over the burnable pixels and each pixel's departure from it", { + covs <- toyCovariates() + ins <- toyInputs(covs = covs, params = splitParams(), formula = "~ MDC_yr + MDC_dev + fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + v <- predVals(toyRun(ins)) + o <- order(covs$pixelID) + mdc <- covs$MDC[o]; fuel <- covs$fuelA[o] + med <- stats::median(covs$MDC) # 100: over the 7 burnable pixels of the covariate table + x <- 1.5 * (med / 200) + 0.8 * ((mdc - med + 100) / 200) + 1 * (fuel / 8) + expect_equal(v[cells <- c(1, 2, 3, 4, 6, 7, 8)], handLogistic3(x), tolerance = 1e-7) +}) + +test_that("the between term is the same for every pixel: only the within term moves with the pixel", { + covs <- toyCovariates() + both <- function(yr, dev) { + ins <- toyInputs(covs = data.table::copy(covs), params = splitParams(yr, dev, fuel = 0), formula = "~ MDC_yr + MDC_dev + fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + predVals(toyRun(ins)) + } + yrOnly <- both(1.5, 0) + expect_equal(yrOnly[c(1, 2, 3, 4, 6, 7, 8)], rep(handLogistic3(1.5 * 0.5), 7), tolerance = 1e-7) # median 100 / 200 everywhere + devOnly <- both(0, 0.8) + expect_gt(length(unique(round(devOnly[c(1, 2, 3, 4, 6, 7, 8)], 8))), 1L) +}) + +test_that("with several ELFs each takes the median over its own pixels", { + ins <- multiInputs() + covs <- data.table::data.table(pixelID = 1:10, MDC = c(10, 20, 30, 40, 50, 100, 110, 120, 130, 140), fuelA = 2, fuelB = 3) + ins$fireSense_SpreadCovariates <- covs + d <- function(fuel) { x <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, f = 1) + names(x)[6] <- fuel; x } + ins$studyAreaWithSpreadParams$params <- list(d("fuelA"), d("fuelB")) + ins$studyAreaWithSpreadParams$covMinMax_spread <- list(cmmSplit("fuelA"), cmmSplit("fuelB")) + ins$fireSense_spreadFormula <- "~ MDC_yr + MDC_dev + fuelA - 1" + v <- predVals(toyRun(ins, params = list(ELFblendWidth = 20000))) + ## pixel 1 is only A's (25 km from B): A's median of pixels 1:5 is 30 + xA <- 1.5 * (30 / 200) + 0.8 * ((10 - 30 + 100) / 200) + 1 * (2 / 8) + expect_equal(v[1], handLogistic3(xA), tolerance = 1e-7) + ## pixel 10 is only B's: B's median of pixels 6:10 is 120 + xB <- 1.5 * (120 / 200) + 0.8 * ((140 - 120 + 100) / 200) + 1 * (3 / 8) + expect_equal(v[10], handLogistic3(xB, upper = 0.25), tolerance = 1e-7) +}) + +test_that("a fit without split terms predicts as before: no median is taken", { + expect_identical(predVals(toyRun()), predVals(toyRun(toyInputs()))) + expect_false(any(fireSenseUtils::isClimateSplitCol(names(toyParams())))) +}) From f8b5a88f561ee879281693999788331700985d80 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 16 Nov 2026 17:36:12 -0700 Subject: [PATCH 2/6] Reused ledger fits keep their split; the median's reference pixels come from fireSenseUtils::climateSplitRefPixels(); cell labels from elfCellLabels() Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- NEWS.md | 2 +- fireSense_spreadPredict.R | 25 ++++++++----------------- tests/testthat/test-climateSplit.R | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/NEWS.md b/NEWS.md index 870d563..02b4b9f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -9,7 +9,7 @@ - New parameter `.plots` (default `"screen"`): the spread probability map (`fireSense_SpreadPredicted`) is plotted each `run` (`SpreadProbability_yr`). `NA` or `NULL` for none. - A ledger row with an interaction coefficient (`a:b`, e.g. `CMD:dom_agb_Pice_mar`, from a `fireSense_spreadFit` fitted with `fireSense_dataPrepFit`'s `spreadInteractions = "climate:fuel"`) predicts with it: `spreadProbOneELF()` needs the covariates `a` and `b` (and their ranges in `covMinMax_spread`), and `fireSenseUtils::spreadProbFromIntegerCovs()` forms their product after each is rescaled and centred with the row's `covCentre_spread` entry for it (0 where `youngAge` cleared the fuel), and multiplies it by the coefficient, as the fit does. A row without interactions predicts exactly as before. Needs fireSenseUtils >= 0.2.3.9177 (#242). -* A ledger row fitted with the split climate covariate (`fireSense_dataPrepFit`'s `spreadClimateSplit`: parameters `_yr` and `_dev`) is predicted with the same two terms: `spreadProbOneELF()` makes them from the year's climate with `fireSenseUtils::splitSpreadClimate()`, the median being over the ELF's own burnable pixels (`elfPixels`: every row with one fitted ELF, the ELF's own pixels of `rasterToMatchLargeELF` with several, not the blend zone). A row without split terms predicts as before. Needs fireSenseUtils with `splitSpreadClimate()` (Depends-on PredictiveEcology/fireSenseUtils); the `reqdPkgs` floor is set after that merges. +* A ledger row fitted with the split climate covariate (`fireSense_dataPrepFit`'s `spreadClimateSplit`: parameters `_yr` and `_dev`) is predicted with the same two terms: `spreadProbOneELF()` makes them from the year's climate with `fireSenseUtils::splitSpreadClimate()`, the median being over the ELF's own burnable pixels (`elfPixels`: every row with one fitted ELF, the ELF's own pixels of `rasterToMatchLargeELF` with several, not the blend zone), and only its flammable pixels (`fireSenseUtils::climateSplitRefPixels()`, the choice the fit makes). `ELFblendWeights()` reads the cells' ELF labels with `fireSenseUtils::elfCellLabels()`. A row without split terms predicts as before. Needs fireSenseUtils with `splitSpreadClimate()` (Depends-on PredictiveEcology/fireSenseUtils); the `reqdPkgs` floor is set after that merges. - With `paramSets`: the cache of a parameter set's surface no longer reads all the values of `flammableRTM` and `rasterToMatchLargeELF` every replicate (a new raster object or a change at 1000 sampled cells is a change) and returns the stored surface without copying it (a changed stored surface is recomputed). On a 20-million-cell raster a replicate that reuses a surface takes 0.35 s instead of 0.9 s, most of it SpaDES. `paramSets` stops if the ledger rows have the simulated ELF twice, or if a file of ledger rows has none for it. diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index 3348ab7..5875e29 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -256,7 +256,7 @@ spreadPredictRun <- function(sim) { if (NROW(sa) == 1L) { params1 <- paramSetForRep(sa$params[[1]], rep) lk1 <- ledgerLinkArgs(sa, 1L, floor = P(sim)$lowerSpreadProb) - pred <- do.call(spreadProbOneELF, c(list(covs, params = params1, covMinMax = ledgerCovMinMax(sa, 1L, sim$covMinMax_spread), + pred <- do.call(spreadProbOneELF, c(list(covs, params = params1, flammableRTM = sim$flammableRTM, covMinMax = ledgerCovMinMax(sa, 1L, sim$covMinMax_spread), yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, lowerSpreadProb = P(sim)$lowerSpreadProb, covCentre = ledgerCovCentre(sa, 1L), climateRef = ledgerClimateRef(sa, 1L), @@ -300,10 +300,10 @@ spreadPredictRun <- function(sim) { if (!length(these)) next parsI <- paramSetForRep(sa$params[[i]], rep) p <- do.call(spreadProbOneELF, c(list(covs[these], params = parsI, covMinMax = sa$covMinMax_spread[[i]], - yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, + yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, flammableRTM = sim$flammableRTM, lowerSpreadProb = P(sim)$lowerSpreadProb, elfPixels = if (any(fireSenseUtils::isClimateSplitCol(names(parsI)))) - which(ELFcellLabels(sim$rasterToMatchLargeELF[[1]]) %in% ids[i]), + which(fireSenseUtils::elfCellLabels(sim$rasterToMatchLargeELF[[1]]) %in% ids[i]), covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i), powerLawPc50 = ledgerPowerLawPc50(sa, i)), lks[[i]])) rows <- these[match(p$pixelID, covs$pixelID[these])] @@ -445,16 +445,6 @@ rasterVersion <- function(name, r) { cur$version } -#' The ELF of each cell -#' -#' @param r one layer of `sim$rasterToMatchLargeELF`: categorical (the labels are the second column of its levels) or the id. -#' @return character, the ELF label of each cell, in cell order. -ELFcellLabels <- function(r) { - v <- terra::values(r, mat = FALSE) - lv <- terra::levels(r)[[1]] - if (is.data.frame(lv) && NCOL(lv) >= 2) as.character(lv[[2]][match(v, lv[[1]])]) else as.character(v) -} - #' Each ELF's weight at each pixel #' #' An ELF's raw weight is 1 on its own pixels and falls linearly to 0 at `width` metres from them (distance @@ -477,7 +467,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { stop("fireSense_spreadPredict: sim$rasterToMatchLargeELF is not on the grid of sim$flammableRTM", call. = FALSE) r <- elfRas[[1]] - lab <- ELFcellLabels(r) + lab <- fireSenseUtils::elfCellLabels(r) w <- vapply(ids, function(id) { core <- r; terra::values(core) <- ifelse(lab %in% id, 1, NA) if (all(is.na(terra::values(core, mat = FALSE)))) return(numeric(length(pixelID))) @@ -501,7 +491,8 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' covariates with. Every fitted covariate must be a column of it, or it is left unscaled. #' @param elfPixels integer; the `pixelID`s of the ELF's own burnable pixels, the pixels the year's median of a split #' climate covariate (`_yr`, `_dev`; `fireSenseUtils::splitSpreadClimate()`) is taken over, as in the fit. -#' `NULL` (one fitted ELF) is every row of `covs`. Not used by a fit without split terms. +#' `NULL` (one fitted ELF) is every row of `covs` that is flammable. Not used by a fit without split terms. +#' @param flammableRTM `sim$flammableRTM`; with `elfPixels` it limits the median to the ELF's flammable pixels (`fireSenseUtils::climateSplitRefPixels()`, the fit's choice). #' @param yr,maxFireSpread,lowerSpreadProb as for `fireSenseUtils::spreadProbFromIntegerCovs()` and #' `fireSenseUtils::logisticAll()`. #' @param covCentre the ELF's `covCentre_spread` (`ledgerCovCentre()`): the covariate means the fit subtracted @@ -538,7 +529,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' also `linearPredictor`, the `x` that `spreadProb` is the link of (the fuels' only with climate in the ceiling), and #' the attribute `linkPars`, the link's parameters (`fireSenseUtils::linearLinkPars()`): a vector, or with climate in #' the ceiling a matrix with one row per pixel. -spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, elfPixels = NULL, +spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, elfPixels = NULL, flammableRTM = NULL, covCentre = NULL, climateRef = NULL, powerLawPc50 = NULL, powerLawGamma = NULL, powerLawShape = fireSenseUtils::spreadPowerLawShape, link = if (!is.null(powerLawGamma)) "powerLaw", @@ -588,7 +579,7 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp ## year's median of the variable over this ELF's burnable pixels, and the departure from it, made as the fit made them splitVars <- unique(fireSenseUtils::climateSplitBase(fitted[fireSenseUtils::isClimateSplitCol(fitted)])) if (length(splitVars) && all(splitVars %in% names(covs))) { - ref <- covs[if (is.null(elfPixels)) TRUE else covs$pixelID %in% elfPixels, splitVars, with = FALSE] + ref <- covs[covs$pixelID %in% fireSenseUtils::climateSplitRefPixels(covs$pixelID, flammableRTM, elfPixels), splitVars, with = FALSE] fireSenseUtils::splitSpreadClimate(covs, splitVars, ref) } ## an interaction (`CMD:fuel`) is made from its two covariates by spreadProbFromIntegerCovs(), as in the fit diff --git a/tests/testthat/test-climateSplit.R b/tests/testthat/test-climateSplit.R index 37e47a7..53f449f 100644 --- a/tests/testthat/test-climateSplit.R +++ b/tests/testthat/test-climateSplit.R @@ -27,6 +27,20 @@ test_that("a split fit predicts from the year's median over the burnable pixels expect_equal(v[cells <- c(1, 2, 3, 4, 6, 7, 8)], handLogistic3(x), tolerance = 1e-7) }) +test_that("a non-flammable row in the covariate table is left out of the median, as the fit's burnable pixels are", { + covs <- toyCovariates() + extra <- data.table::data.table(pixelID = 5L, MDC = 5000, youngAge = 0, fuelA = 0) # cell 5 of the toy flammableRTM is 0 + withExtra <- data.table::rbindlist(list(covs, extra)) + run <- function(cv) { + ins <- toyInputs(covs = cv, params = splitParams(), formula = "~ MDC_yr + MDC_dev + fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + predVals(toyRun(ins)) + } + a <- run(covs); b <- run(withExtra) + cellsB <- c(1, 2, 3, 4, 6, 7, 8) + expect_equal(b[cellsB], a[cellsB], tolerance = 1e-12) # median 100 with and without the extra row +}) + test_that("the between term is the same for every pixel: only the within term moves with the pixel", { covs <- toyCovariates() both <- function(yr, dev) { From a3d2ee610d386322b1b2e5059e97daf2b040d292 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 17:10:35 -0700 Subject: [PATCH 3/6] fireSenseUtils floor 0.2.3.9185 (fireSenseUtils#244); a split term in an interaction is split too; tests: split with climate in the ceiling, split in an interaction Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- fireSense_spreadPredict.R | 15 +++++++------- tests/testthat/test-climateSplit.R | 33 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 7 deletions(-) diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index 5875e29..a85bba9 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -17,7 +17,7 @@ defineModule(sim, list( documentation = list("README.txt", "fireSense_spreadPredict.Rmd"), reqdPkgs = list("data.table", "magrittr", "Matrix", "methods", "terra", "SpaDES.core (>=3.0.4)", "stats", "ggplot2", "viridis", - "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9183)"), # 9183: spreadLinkInputs(activationIntercept =), spreadClimateTxt (fireSenseUtils#255); 9181: spreadLinkInputs(), powerLawPc50 (fireSenseUtils#250); 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9185)"), # 9185: splitSpreadClimate(), climateSplitRefPixels(), elfCellLabels() (fireSenseUtils#244, version not yet released; CHECK after it merges); 9183: spreadLinkInputs(activationIntercept =), spreadClimateTxt (fireSenseUtils#255); 9181: spreadLinkInputs(), powerLawPc50 (fireSenseUtils#250); 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape parameters = bindrows( defineParameter(name = "lowerSpreadProb", class = "numeric", default = fireSenseUtils::spreadProbFloor, desc = paste("Lower asymptote of the 2- and 3-parameter logistic. Default", @@ -302,7 +302,7 @@ spreadPredictRun <- function(sim) { p <- do.call(spreadProbOneELF, c(list(covs[these], params = parsI, covMinMax = sa$covMinMax_spread[[i]], yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, flammableRTM = sim$flammableRTM, lowerSpreadProb = P(sim)$lowerSpreadProb, - elfPixels = if (any(fireSenseUtils::isClimateSplitCol(names(parsI)))) + elfPixels = if (any(fireSenseUtils::isClimateSplitCol(fireSenseUtils::spreadSourceCols(names(parsI))))) which(fireSenseUtils::elfCellLabels(sim$rasterToMatchLargeELF[[1]]) %in% ids[i]), covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i), powerLawPc50 = ledgerPowerLawPc50(sa, i)), lks[[i]])) @@ -575,15 +575,16 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp ## the intercept, if the fit has one, is a coefficient with no covariate: it multiplies a column of 1s hasIntercept <- fireSenseUtils::spreadInterceptTxt %in% names(params) fitted <- setdiff(names(params), c(unlist(fireSenseUtils::logisticParamNames), fireSenseUtils::spreadInterceptTxt)) - ## a fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as `_yr` and `_dev`: the - ## year's median of the variable over this ELF's burnable pixels, and the departure from it, made as the fit made them - splitVars <- unique(fireSenseUtils::climateSplitBase(fitted[fireSenseUtils::isClimateSplitCol(fitted)])) + ## an interaction (`CMD:fuel`) is made from its two covariates by spreadProbFromIntegerCovs(), as in the fit + needed <- fireSenseUtils::spreadSourceCols(fitted) + ## a fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as `_yr` and `_dev` (also in an + ## interaction, `CMD_yr:fuel`): the year's median of the variable over this ELF's burnable pixels, and the departure + ## from it, made as the fit made them + splitVars <- unique(fireSenseUtils::climateSplitBase(needed[fireSenseUtils::isClimateSplitCol(needed)])) if (length(splitVars) && all(splitVars %in% names(covs))) { ref <- covs[covs$pixelID %in% fireSenseUtils::climateSplitRefPixels(covs$pixelID, flammableRTM, elfPixels), splitVars, with = FALSE] fireSenseUtils::splitSpreadClimate(covs, splitVars, ref) } - ## an interaction (`CMD:fuel`) is made from its two covariates by spreadProbFromIntegerCovs(), as in the fit - needed <- fireSenseUtils::spreadSourceCols(fitted) noCov <- setdiff(needed, names(covs)) if (length(noCov)) { stop( diff --git a/tests/testthat/test-climateSplit.R b/tests/testthat/test-climateSplit.R index 53f449f..c52a9be 100644 --- a/tests/testthat/test-climateSplit.R +++ b/tests/testthat/test-climateSplit.R @@ -76,3 +76,36 @@ test_that("a fit without split terms predicts as before: no median is taken", { expect_identical(predVals(toyRun()), predVals(toyRun(toyInputs()))) expect_false(any(fireSenseUtils::isClimateSplitCol(names(toyParams())))) }) + +test_that("a split fit with climate in the ceiling moves pc with both terms, and x holds the fuels only", { + covs <- toyCovariates() + p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, + youngAge = -0.5, fuelA = 1) + ins <- toyInputs(covs = covs, params = p, formula = "~ MDC_yr + MDC_dev + youngAge + fuelA - 1") + ins$covMinMax_spread <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), youngAge = c(0, 1), fuelA = c(0, 8)) + ins$studyAreaWithSpreadParams[[linkColPL]] <- "powerLaw" + ins$studyAreaWithSpreadParams[[gammaColPL]] <- 1.9 + ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitClimateRefTxt]] <- list(list(MDC_yr = 0.4, MDC_dev = 0.5)) + ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitPowerLawPc50Txt]] <- 0.3 + sim <- toyRun(ins) + o <- order(covs$pixelID) + med <- stats::median(covs$MDC) + shift <- 1.5 * (med / 200 - 0.4) + 0.8 * ((covs$MDC[o] - med + 100) / 200 - 0.5) + x <- -0.5 * covs$youngAge[o] + covs$fuelA[o] / 8 + pc <- pmax(0.3 - (0.3 - 0.25) * exp(-shift), 0.13) + expect_equal(predVals(sim)[cellsPL], pmax(pc - (pc - 0.13) * exp(-sign(x) * abs(x / 1.9)), 0), tolerance = 1e-9) + expect_equal(terra::values(sim$fireSense_SpreadLinear, mat = FALSE)[cellsPL], x, tolerance = 1e-9) +}) + +test_that("an interaction of a split term is made from the split term, so the fit's interaction names work", { + covs <- toyCovariates() + p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, + fuelA = 1, `MDC_yr:fuelA` = -2, check.names = FALSE) + ins <- toyInputs(covs = covs, params = p, formula = "~ MDC_yr + MDC_dev + fuelA + MDC_yr:fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + o <- order(covs$pixelID) + med <- stats::median(covs$MDC) + yr <- med / 200; dev <- (covs$MDC[o] - med + 100) / 200; fuel <- covs$fuelA[o] / 8 + x <- 1.5 * yr + 0.8 * dev + fuel - 2 * yr * fuel + expect_equal(predVals(toyRun(ins))[cellsPL], handLogistic3(x), tolerance = 1e-7) +}) From 3759da43411e79238db453f0390b14e90d08553d Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 17:11:01 -0700 Subject: [PATCH 4/6] spreadPredict: read the ELF cell labels once, not per ELF Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- fireSense_spreadPredict.R | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index a85bba9..c30cb20 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -295,6 +295,11 @@ spreadPredictRun <- function(sim) { accPL <- matrix(0, NROW(covs), length(linkParNames), dimnames = list(NULL, linkParNames)) accX <- numeric(NROW(covs)) wsumPL <- numeric(NROW(covs)) ## weight of the ELFs with a linear-predictor link only + ## the ELF label of every cell (a whole-raster read): once, and only if a fit has split climate terms + isSplit <- vapply(seq_along(ids), function(i) + any(fireSenseUtils::isClimateSplitCol(fireSenseUtils::spreadSourceCols(names(paramSetForRep(sa$params[[i]], rep))))), + logical(1)) + elfLab <- if (any(isSplit)) fireSenseUtils::elfCellLabels(sim$rasterToMatchLargeELF[[1]]) for (i in seq_along(ids)) { these <- which(w[, i] > 0) if (!length(these)) next @@ -302,8 +307,7 @@ spreadPredictRun <- function(sim) { p <- do.call(spreadProbOneELF, c(list(covs[these], params = parsI, covMinMax = sa$covMinMax_spread[[i]], yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, flammableRTM = sim$flammableRTM, lowerSpreadProb = P(sim)$lowerSpreadProb, - elfPixels = if (any(fireSenseUtils::isClimateSplitCol(fireSenseUtils::spreadSourceCols(names(parsI))))) - which(fireSenseUtils::elfCellLabels(sim$rasterToMatchLargeELF[[1]]) %in% ids[i]), + elfPixels = if (isSplit[i]) which(elfLab %in% ids[i]), covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i), powerLawPc50 = ledgerPowerLawPc50(sa, i)), lks[[i]])) rows <- these[match(p$pixelID, covs$pixelID[these])] From 1a7bf17e79728be93b333f2b65eebe2b3021dfc6 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 21:10:16 -0700 Subject: [PATCH 5/6] fireSenseUtils floor 0.2.3.9186 (#244 merged as 9186; 9185 is #256) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- fireSense_spreadPredict.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index c30cb20..9e68d3d 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -17,7 +17,7 @@ defineModule(sim, list( documentation = list("README.txt", "fireSense_spreadPredict.Rmd"), reqdPkgs = list("data.table", "magrittr", "Matrix", "methods", "terra", "SpaDES.core (>=3.0.4)", "stats", "ggplot2", "viridis", - "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9185)"), # 9185: splitSpreadClimate(), climateSplitRefPixels(), elfCellLabels() (fireSenseUtils#244, version not yet released; CHECK after it merges); 9183: spreadLinkInputs(activationIntercept =), spreadClimateTxt (fireSenseUtils#255); 9181: spreadLinkInputs(), powerLawPc50 (fireSenseUtils#250); 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9186)"), # 9186: splitSpreadClimate(), climateSplitRefPixels(), elfCellLabels() (fireSenseUtils#244); 9183: spreadLinkInputs(activationIntercept =), spreadClimateTxt (fireSenseUtils#255); 9181: spreadLinkInputs(), powerLawPc50 (fireSenseUtils#250); 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape parameters = bindrows( defineParameter(name = "lowerSpreadProb", class = "numeric", default = fireSenseUtils::spreadProbFloor, desc = paste("Lower asymptote of the 2- and 3-parameter logistic. Default", From 6af6f52a2d6ff9d5d1e1fe4b270a85d4d49051e0 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 20 Nov 2026 22:53:08 -0700 Subject: [PATCH 6/6] Split fit with linear fuel predicts: set the fuel by reference so splitSpreadClimate() can add its columns; test of a CMD_yr:fuel interaction Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 ++ fireSense_spreadPredict.R | 2 +- tests/testthat/test-climateSplit.R | 23 +++++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 02b4b9f..cc36f51 100644 --- a/NEWS.md +++ b/NEWS.md @@ -9,6 +9,8 @@ - New parameter `.plots` (default `"screen"`): the spread probability map (`fireSense_SpreadPredicted`) is plotted each `run` (`SpreadProbability_yr`). `NA` or `NULL` for none. - A ledger row with an interaction coefficient (`a:b`, e.g. `CMD:dom_agb_Pice_mar`, from a `fireSense_spreadFit` fitted with `fireSense_dataPrepFit`'s `spreadInteractions = "climate:fuel"`) predicts with it: `spreadProbOneELF()` needs the covariates `a` and `b` (and their ranges in `covMinMax_spread`), and `fireSenseUtils::spreadProbFromIntegerCovs()` forms their product after each is rescaled and centred with the row's `covCentre_spread` entry for it (0 where `youngAge` cleared the fuel), and multiplies it by the coefficient, as the fit does. A row without interactions predicts exactly as before. Needs fireSenseUtils >= 0.2.3.9177 (#242). + +- A split fit with fuel in the linear range (every fit with `spreadClimateSplit` and fuel) predicted nothing: `spreadProbOneELF()` turned the logged fuel to linear with `covs[[cn]] <-`, which copies the table, so `fireSenseUtils::splitSpreadClimate()` then could not add `CMD_yr` and `CMD_dev` and the prediction stopped with "fitted coefficients CMD_yr, CMD_dev have no covariate". It now sets the fuel by reference. A test covers a `CMD_yr:fuel` interaction with an intercept, centres and `youngAge`. * A ledger row fitted with the split climate covariate (`fireSense_dataPrepFit`'s `spreadClimateSplit`: parameters `_yr` and `_dev`) is predicted with the same two terms: `spreadProbOneELF()` makes them from the year's climate with `fireSenseUtils::splitSpreadClimate()`, the median being over the ELF's own burnable pixels (`elfPixels`: every row with one fitted ELF, the ELF's own pixels of `rasterToMatchLargeELF` with several, not the blend zone), and only its flammable pixels (`fireSenseUtils::climateSplitRefPixels()`, the choice the fit makes). `ELFblendWeights()` reads the cells' ELF labels with `fireSenseUtils::elfCellLabels()`. A row without split terms predicts as before. Needs fireSenseUtils with `splitSpreadClimate()` (Depends-on PredictiveEcology/fireSenseUtils); the `reqdPkgs` floor is set after that merges. - With `paramSets`: the cache of a parameter set's surface no longer reads all the values of `flammableRTM` and `rasterToMatchLargeELF` every replicate (a new raster object or a change at 1000 sampled cells is a change) and returns the stored surface without copying it (a changed stored surface is recomputed). On a 20-million-cell raster a replicate that reuses a surface takes 0.35 s instead of 0.9 s, most of it SpaDES. `paramSets` stops if the ledger rows have the simulated ELF twice, or if a file of ledger rows has none for it. diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index 9e68d3d..83d81dc 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -569,7 +569,7 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp fuelCols <- character() for (cn in intersect(names(covMinMax), names(covs))) { if (fireSenseUtils::isLinearFuelRange(covMinMax[[cn]])) { - covs[[cn]] <- fireSenseUtils::fuelLogToLinear(covs[[cn]]) + data.table::set(covs, NULL, cn, fireSenseUtils::fuelLogToLinear(covs[[cn]])) # by reference: `[[<-` copies, and splitSpreadClimate() below then cannot add columns fuelCols <- c(fuelCols, cn) } } diff --git a/tests/testthat/test-climateSplit.R b/tests/testthat/test-climateSplit.R index c52a9be..53d35e9 100644 --- a/tests/testthat/test-climateSplit.R +++ b/tests/testthat/test-climateSplit.R @@ -109,3 +109,26 @@ test_that("an interaction of a split term is made from the split term, so the fi x <- 1.5 * yr + 0.8 * dev + fuel - 2 * yr * fuel expect_equal(predVals(toyRun(ins))[cellsPL], handLogistic3(x), tolerance = 1e-7) }) + +test_that("a fit with an intercept, centres and a _yr:fuel interaction predicts the product of the centred terms, 0 where youngAge cleared the fuel, and no _dev interaction", { + covs <- toyCovariates() + p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, icpt = 0.4, MDC_yr = 1.5, MDC_dev = 0.8, + youngAge = -0.5, fuelA = 1, `MDC_yr:fuelA` = -2, check.names = FALSE) + names(p)[4] <- fireSenseUtils::spreadInterceptTxt + ## fuel arrives logged, with the fit's linear range (only then is it cleared where youngAge is 1) + biomass <- c(0, 0, 4000, 0, 8000, 8000, 2000) + data.table::set(covs, j = "fuelA", value = fireSenseUtils::logMinB(biomass)) + ins <- toyInputs(covs = covs, params = p, formula = "~ 1 + MDC_yr + MDC_dev + youngAge + fuelA + MDC_yr:fuelA") + ins$covMinMax_spread <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), youngAge = c(0, 1), + fuelA = fireSenseUtils::fuelLinearRange) + centre <- list(MDC_yr = 0.4, MDC_dev = 0.5, youngAge = 0.2, fuelA = 0.3) + ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitCovCentreTxt]] <- list(centre) + o <- order(covs$pixelID) + med <- stats::median(covs$MDC) + yr <- med / 200 - 0.4; dev <- (covs$MDC[o] - med + 100) / 200 - 0.5 + ya <- covs$youngAge[o]; fuel <- biomass[o] / fireSenseUtils::fuelLinearRange[2] + fuelC <- ifelse(ya > 0, 0, fuel) - 0.3 # fuel is cleared where youngAge is non-zero, then centred + inter <- ifelse(ya > 0, 0, yr * fuelC) # the interaction is 0 there, and is not centred again + x <- 0.4 + 1.5 * yr + 0.8 * dev - 0.5 * (ya - 0.2) + 1 * fuelC - 2 * inter + expect_equal(predVals(toyRun(ins))[cellsPL], handLogistic3(x), tolerance = 1e-7) +})