From 57606f66f6acddbd4a961b83daa43d1e3ed405d8 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 18 Nov 2026 20:24:20 -0700 Subject: [PATCH 1/2] Climate moves the power-law ceiling toward p50 (spreadClimate = "ceiling") Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 2 + fireSense_spreadPredict.R | 112 +++++++++++++++++---------- tests/testthat/setup-toySpread.R | 21 +++++ tests/testthat/test-climateCeiling.R | 92 ++++++++++++++++++++++ tests/testthat/test-powerLaw.R | 19 +---- 5 files changed, 188 insertions(+), 58 deletions(-) create mode 100644 tests/testthat/test-climateCeiling.R diff --git a/NEWS.md b/NEWS.md index 487d5c8..3d8b646 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fireSense_spreadPredict (development version) +- A ledger row from a `fireSense_spreadFit` with `spreadClimate = "ceiling"` (a power-law `spreadLink` with `climateRef_spread` and `powerLawPc50_spread`) is predicted with climate moving the ceiling `pc` toward p50 (`fireSenseUtils::spreadLinkInputs()`): new `ledgerPowerLawPc50()`; `spreadProbOneELF()` takes `powerLawPc50`, returns the fuels' linear predictor as `linearPredictor` and the link's parameters as the attribute `linkPars` (one row per pixel here). `fireSense_SpreadPowerLaw` is then a raster with a `pc` per pixel even for one ELF, and several ELFs blend the per-pixel parameters (the vector `powerLawParsOf()` is gone: `spreadLinkInputs()` makes the parameters). Rows without `climateRef_spread` predict exactly as before. `fireSense_burn` already reads a per-cell raster of the link's parameters. Needs fireSenseUtils >= 0.2.3.9181 (PredictiveEcology/fireSenseUtils#250). + - 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). diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index c67d07e..3f910d7 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.9177)"), # 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9181)"), # 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", @@ -129,7 +129,9 @@ defineModule(sim, list( "`fireSenseUtils::powerLawLink()`; \"powerLawSmooth\" also `lower` (the row's", "`lowerAsymptote`, at least `fireSenseUtils::spreadLowerAsymptoteMin`, 0.001: `fireSenseUtils::checkLinkParams()`); \"richards\": `pc`, `lower`, `nu` (the row's `richardsNu`) and `B`.", "A numeric vector with one fitted ELF; with several, a raster with one layer per name,", - "blended like `fireSense_SpreadSD`.")), + "blended like `fireSense_SpreadSD`. With a fit made with climate in the ceiling", + "(`fireSense_spreadFit`'s `spreadClimate = \"ceiling\"`: a ledger row with `climateRef_spread` and a", + "power-law link), `pc` differs by pixel and year, so it is a raster even with one ELF.")), createsOutput(objectName = "fireSense_SpreadLinear", objectClass = "SpatRaster", desc = paste("Only for a fit made with a link of `fireSenseUtils::spreadLinearLinks` (else NULL): the linear predictor x of", "each flammable pixel (covariates %*% coefficients), the step before", @@ -254,10 +256,13 @@ spreadPredictRun <- function(sim) { pred <- do.call(spreadProbOneELF, c(list(covs, params = params1, 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)), lk1)) + covCentre = ledgerCovCentre(sa, 1L), climateRef = ledgerClimateRef(sa, 1L), + powerLawPc50 = ledgerPowerLawPc50(sa, 1L)), lk1)) for (nm in names(randomEffectOutputs)) sim[[nm]] <- randomEffectSDOf(params1, randomEffectOutputs[[nm]]) sim$fireSense_SpreadLink <- lk1$link - sim$fireSense_SpreadPowerLaw <- do.call(powerLawParsOf, c(list(params1, lowerSpreadProb = P(sim)$lowerSpreadProb), lk1)) + ## the link's parameters: a vector, or with climate in the ceiling (`spreadClimate = "ceiling"`) one row per pixel + linkPars <- attr(pred, "linkPars") + sim$fireSense_SpreadPowerLaw <- if (is.matrix(linkPars)) linkParsRas(sim$flammableRTM, pred$pixelID, linkPars) else linkPars if (!is.null(lk1$link)) sim$fireSense_SpreadLinear <- linearPredictorRas(sim$flammableRTM, pred) } else { ids <- as.character(sa[[fireSenseUtils::polygonIDTxt]]) @@ -288,12 +293,16 @@ 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, - covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i)), lks[[i]])) + covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i), + powerLawPc50 = ledgerPowerLawPc50(sa, i)), lks[[i]])) rows <- these[match(p$pixelID, covs$pixelID[these])] acc[rows] <- acc[rows] + w[rows, i] * p$spreadProb accSD[rows, ] <- accSD[rows, ] + w[rows, i] * rep(vapply(randomEffectOutputs, function(txt) randomEffectSDOf(parsI, txt), numeric(1)), each = length(rows)) if (!is.null(lks[[i]]$link)) { - accPL[rows, ] <- accPL[rows, ] + w[rows, i] * rep(do.call(powerLawParsOf, c(list(parsI, lowerSpreadProb = P(sim)$lowerSpreadProb), lks[[i]])), each = length(rows)) + ## one row per pixel with climate in the ceiling, else the ELF's one vector for all its pixels + linkParsI <- attr(p, "linkPars") + if (!is.matrix(linkParsI)) linkParsI <- matrix(linkParsI, length(rows), length(linkParsI), byrow = TRUE) + accPL[rows, ] <- accPL[rows, ] + w[rows, i] * linkParsI accX[rows] <- accX[rows] + w[rows, i] * p$linearPredictor wsumPL[rows] <- wsumPL[rows] + w[rows, i] } @@ -483,8 +492,9 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' have `a` and `b`, and `fireSenseUtils::spreadProbFromIntegerCovs()` multiplies them after each is #' rescaled and centred (0 where `youngAge` cleared the fuel), exactly as in the fit. #' @param climateRef the ELF's `climateRef_spread` (`ledgerClimateRef()`): with a fit made with climate outside the -#' `maxAsymptote` ceiling (`fireSense_spreadFit`'s `spreadLink = "climateOutside"`), the reference value of each -#' climate covariate; `fireSenseUtils::spreadProbFromCovs()` then applies that link, exactly as the fit did. +#' `maxAsymptote` ceiling (`fireSense_spreadFit`'s `spreadLink = "climateOutside"`) or moving it (`spreadClimate = +#' "ceiling"`), the reference value of each climate covariate; `fireSenseUtils::spreadProbFromCovs()` and +#' `spreadLinkInputs()` then apply that link, exactly as the fit did. #' `NULL` (a fit with climate under the ceiling, or an older ledger row) is the link as it always was. #' @param powerLawGamma the ELF's `powerLawGamma_spread` (`ledgerPowerLawGamma()`): with a fit made with #' `fireSense_spreadFit`'s `spreadLink = "powerLaw"`, its `gamma`; `fireSenseUtils::spreadProbFromCovs()` then @@ -497,10 +507,15 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' others existed. #' @param lowerAsymptote,richardsNu the ELF's `lowerAsymptote_spread` and `richardsNu_spread` (`ledgerLowerAsymptote()`, #' `ledgerRichardsNu()`): with `"powerLawSmooth"` and `"richards"`, the lower asymptote, and `nu` of `"richards"`. +#' @param powerLawPc50 the ELF's `powerLawPc50_spread` (`ledgerPowerLawPc50()`): with `climateRef` and a power-law `link` +#' (a fit with `fireSense_spreadFit`'s `spreadClimate = "ceiling"`), the runaway threshold the ceiling moves toward; +#' `fireSenseUtils::spreadLinkInputs()` ignores it without `climateRef`. #' @return `data.table` with `pixelID` and `spreadProb`, from the one parameter set in `params`; with a `link` -#' also `linearPredictor`, the `x` that `spreadProb` is the link of. +#' 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, - covCentre = NULL, climateRef = NULL, powerLawGamma = NULL, + covCentre = NULL, climateRef = NULL, powerLawPc50 = NULL, powerLawGamma = NULL, powerLawShape = fireSenseUtils::spreadPowerLawShape, link = if (!is.null(powerLawGamma)) "powerLaw", lowerAsymptote = fireSenseUtils::spreadProbFloor, @@ -592,15 +607,24 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp matching <- intersect(names(covPars), colnames(mat)) ## the one function the fit computes its spread probability with, so the prediction cannot differ from it - out <- data.table(pixelID = shortAnnDT$pixelID, - spreadProb = spreadProbFromCovs(mat[, matching, drop = FALSE], logisticPars, covPars, lowerSpreadProb, - link = link, - climateRef = climateRef, powerLawGamma = powerLawGamma, - powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, - richardsNu = richardsNu)) + mat <- mat[, matching, drop = FALSE] + if (is.null(link)) + return(data.table(pixelID = shortAnnDT$pixelID, + spreadProb = spreadProbFromCovs(mat, logisticPars, covPars, lowerSpreadProb, link = link, + climateRef = climateRef, powerLawGamma = powerLawGamma, + powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, + richardsNu = richardsNu))) + ## a link of `fireSenseUtils::spreadLinearLinks`: x and the link's parameters, which `spreadProbFromCovs()` turns + ## into p the same way. With climate in the ceiling x is the fuels' only and the parameters (`pc`) are one row per pixel. + ## "richards" has no gamma, and does not use one + if (is.null(powerLawGamma)) powerLawGamma <- fireSenseUtils::spreadPowerLawGamma + inputs <- spreadLinkInputs(mat, logisticPars, covPars, lowerSpreadProb, link, climateRef, powerLawPc50, + powerLawGamma = powerLawGamma, + powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, richardsNu = richardsNu) ## the link's input: the power law clips it at 0, so it cannot be recovered from spreadProb - if (!is.null(link)) - set(out, NULL, "linearPredictor", as.vector(mat[, matching, drop = FALSE] %*% covPars)) + out <- data.table(pixelID = shortAnnDT$pixelID, spreadProb = linearLinkProb(inputs$x, link, inputs$pars), + linearPredictor = inputs$x) + setattr(out, "linkPars", inputs$pars) out } @@ -625,28 +649,20 @@ randomEffectOutputs <- list(fireSense_SpreadFireSD = fireSenseUtils::fireSpreadS surfaceOutputs <- c("fireSense_SpreadPredicted", names(randomEffectOutputs), "fireSense_SpreadLink", "fireSense_SpreadPowerLaw", "fireSense_SpreadLinear") -#' What `fireSense_burn` needs to add the year effect on the linear predictor of a power-law or Richards fit -#' -#' A fit made with `spreadLink = "powerLaw"`, `"powerLawSmooth"` or `"richards"` adds its year effect (`yearSpreadSD`) -#' to the linear predictor `x`, not to the logit of `p`. `fireSense_burn` adds the effect to `x` and maps back with the -#' link (`fireSenseUtils::linearLinkProb()`), with these parameters. -#' -#' @param params one-row `data.frame`: the parameter set in use (`paramSetForRep()`); `maxAsymptote` is `pc`. -#' @param powerLawGamma the row's `gamma` (`ledgerPowerLawGamma()`); `NULL` for a link without one. -#' @param lowerSpreadProb the `floor`. -#' @param powerLawShape the row's `shape` (`ledgerPowerLawShape()`). -#' @param link the row's link (`ledgerLinkArgs()`); by default `"powerLaw"` when `powerLawGamma` is given. -#' @param lowerAsymptote,richardsNu the row's `lowerAsymptote` and `richardsNu`. -#' @return A named numeric vector (`fireSenseUtils::spreadLinkParNames` of the link; `fireSenseUtils::linearLinkPars()`), -#' or `NULL` for another link. -powerLawParsOf <- function(params, powerLawGamma = NULL, lowerSpreadProb, powerLawShape = fireSenseUtils::spreadPowerLawShape, - link = if (!is.null(powerLawGamma)) "powerLaw", lowerAsymptote = fireSenseUtils::spreadProbFloor, - richardsNu = fireSenseUtils::spreadRichardsNu) { - if (is.null(link)) return(NULL) - ## "richards" has no gamma, and does not use one - if (is.null(powerLawGamma)) powerLawGamma <- fireSenseUtils::spreadPowerLawGamma - fireSenseUtils::linearLinkPars(link, params[["maxAsymptote"]][1L], powerLawGamma, lowerSpreadProb, powerLawShape, - lowerAsymptote, richardsNu) +#' `fireSense_SpreadPowerLaw` with a parameter per pixel: the link's parameters on the grid of `flammableRTM` +#' +#' With climate in the ceiling `pc` differs by pixel (`fireSenseUtils::spreadLinkInputs()`), so the parameters are a raster +#' with one layer per name, as with several ELFs. +#' +#' @param template `sim$flammableRTM`. +#' @param pixelID cells of `template`, one per row of `pars`. +#' @param pars matrix, one column per parameter (`fireSenseUtils::spreadLinkParNames` of the link). +#' @return A `SpatRaster`, `NA` outside `pixelID`. +linkParsRas <- function(template, pixelID, pars) { + r <- rast(template, nlyrs = ncol(pars)) + names(r) <- colnames(pars) + for (nm in colnames(pars)) r[[nm]][pixelID] <- pars[, nm] + r } #' The covariate ranges of one ledger row @@ -685,6 +701,22 @@ ledgerClimateRef <- function(sa, i) { if (is.list(ref) && length(ref)) ref else NULL } +#' The runaway threshold of one ledger row +#' +#' A fit made with `fireSense_spreadFit`'s `spreadClimate = "ceiling"` moves `maxAsymptote` toward the landscape's +#' runaway threshold `p50`, stored in the ledger row (`fireSenseUtils::spreadFitPowerLawPc50Txt`) as for every power-law +#' fit. Only a row with `climateRef_spread` (`ledgerClimateRef()`) uses it. +#' +#' @param sa `sim$studyAreaWithSpreadParams`, one row per ELF. +#' @param i integer; the row. +#' @return `p50`, or `NULL` for a row without the column or with `NA`. +ledgerPowerLawPc50 <- function(sa, i) { + col <- fireSenseUtils::spreadFitPowerLawPc50Txt + if (!col %in% names(sa)) return(NULL) + p50 <- sa[[col]][[i]] + if (is.null(p50) || is.na(p50)) NULL else p50 +} + #' The power-law exponent of one ledger row #' #' A fit made with `fireSense_spreadFit`'s `spreadLink = "powerLaw"` or `"powerLawSmooth"` stores its `gamma` in the ledger row diff --git a/tests/testthat/setup-toySpread.R b/tests/testthat/setup-toySpread.R index 47d14c6..9016cdf 100644 --- a/tests/testthat/setup-toySpread.R +++ b/tests/testthat/setup-toySpread.R @@ -99,3 +99,24 @@ multiInputs <- function() { studyAreaWithSpreadParams = sa, fireSense_spreadFormula = "~ MDC + fuelA - 1", covMinMax_spread = cmm("fuelA")) } + +## A power-law ledger row on the toy inputs (test-powerLaw.R, test-climateCeiling.R); the toy covariates and coefficients +## are those of test-spreadProb-values.R +linkColPL <- fireSenseUtils::spreadLinkTxt +gammaColPL <- fireSenseUtils::spreadFitPowerLawGammaTxt +shapeColPL <- fireSenseUtils::spreadFitPowerLawShapeTxt +cellsPL <- c(1, 2, 3, 4, 6, 7, 8) + +inputsPL <- function(gamma = 1.9, link = "powerLaw") { + ins <- toyInputs() + if (!is.null(link)) ins$studyAreaWithSpreadParams[[linkColPL]] <- link + if (!is.null(gamma)) ins$studyAreaWithSpreadParams[[gammaColPL]] <- gamma + ins +} + +## by hand, in cell order +pHandPL <- function(gamma = 1.9, pc = 0.25, floor = 0.13, shape = 1) { + cv <- toyCovariates(); o <- order(cv$pixelID) + x <- 1.5 * cv$MDC[o] / 200 - 0.5 * cv$youngAge[o] + 1 * cv$fuelA[o] / 8 + pmax(pc - (pc - floor) * exp(-sign(x) * abs(x / gamma)^shape), 0) +} diff --git a/tests/testthat/test-climateCeiling.R b/tests/testthat/test-climateCeiling.R new file mode 100644 index 0000000..5270c54 --- /dev/null +++ b/tests/testthat/test-climateCeiling.R @@ -0,0 +1,92 @@ +## A ledger row from a fit made with fireSense_spreadFit's spreadClimate = "ceiling" has a power-law link, the climate +## reference (fireSenseUtils::spreadFitClimateRefTxt) and the landscape's p50 (spreadFitPowerLawPc50Txt). Climate then +## moves the ceiling pc toward p50 (fireSenseUtils::spreadLinkInputs()) and x holds the fuels only: +## shift = sum(beta_clim * (climate - climateRef)); pc = max(p50 - (p50 - pc0) * exp(-shift), floor). +## A row without a climateRef predicts as it always did. Toy covariates and coefficients: test-powerLaw.R (MDC is the climate). + +pc50ColCC <- fireSenseUtils::spreadFitPowerLawPc50Txt +refColCC <- fireSenseUtils::spreadFitClimateRefTxt + +## MDC / 200 is its rescaled value; the toy fit's climate reference is 0.4 on that scale +inputsCC <- function(gamma = 1.9, link = "powerLaw", ref = list(MDC = 0.4), p50 = 0.3) { + ins <- inputsPL(gamma = gamma, link = link) + if (!is.null(ref)) ins$studyAreaWithSpreadParams[[refColCC]] <- list(ref) + if (!is.null(p50)) ins$studyAreaWithSpreadParams[[pc50ColCC]] <- p50 + ins +} + +## by hand, in cell order +handCC <- function(gamma = 1.9, pc0 = 0.25, floor = 0.13, p50 = 0.3, ref = 0.4) { + cv <- toyCovariates(); o <- order(cv$pixelID) + shift <- 1.5 * (cv$MDC[o] / 200 - ref) + x <- -0.5 * cv$youngAge[o] + 1 * cv$fuelA[o] / 8 + pc <- pmax(p50 - (p50 - pc0) * exp(-shift), floor) + list(p = pmax(pc - (pc - floor) * exp(-sign(x) * abs(x / gamma)), 0), pc = pc, x = x) +} + +test_that("ledgerPowerLawPc50() reads the row's p50, NULL when absent or NA", { + sa <- toyInputs()$studyAreaWithSpreadParams + expect_null(ledgerPowerLawPc50(sa, 1L)) + sa[[pc50ColCC]] <- 0.3 + expect_identical(ledgerPowerLawPc50(sa, 1L), 0.3) + sa[[pc50ColCC]] <- NA_real_ + expect_null(ledgerPowerLawPc50(sa, 1L)) +}) + +test_that("a row with climateRef and a power-law link predicts with climate moving the ceiling toward p50", { + sim <- toyRun(inputsCC()) + h <- handCC() + expect_equal(predVals(sim)[cellsPL], h$p, tolerance = 1e-9) + ## the climate is in the ceiling, not in x + expect_equal(terra::values(sim$fireSense_SpreadLinear, mat = FALSE)[cellsPL], h$x, tolerance = 1e-9) + ## pc never passes p50, and the climate at the reference gives pc0 + expect_true(all(h$pc <= 0.3)) + expect_equal(handCC(ref = 0.5)$pc[cellsPL == 3L], 0.25) + expect_false(isTRUE(all.equal(predVals(sim), predVals(toyRun(inputsCC(ref = NULL)))))) +}) + +test_that("fireSense_SpreadPowerLaw is a per-pixel raster, with pc per pixel, even for one ELF", { + sim <- toyRun(inputsCC()) + pl <- sim$fireSense_SpreadPowerLaw + expect_s4_class(pl, "SpatRaster") + expect_identical(names(pl), fireSenseUtils::spreadLinkParNames[["powerLaw"]]) + h <- handCC() + expect_equal(terra::values(pl[["pc"]], mat = FALSE)[cellsPL], h$pc, tolerance = 1e-9) + expect_equal(terra::values(pl[["gamma"]], mat = FALSE)[cellsPL], rep(1.9, length(cellsPL))) + ## how fireSense_burn reads it (its powerLawPars(): one column per name, one row per cell) reproduces p from x + pars <- vapply(names(pl), function(nm) terra::values(pl[[nm]], mat = FALSE), numeric(terra::ncell(pl))) + x <- terra::values(sim$fireSense_SpreadLinear, mat = FALSE) + ok <- !is.na(x) + expect_false(anyNA(pars[ok, ])) + expect_equal(fireSenseUtils::linearLinkProb(x[ok], "powerLaw", pars[ok, , drop = FALSE]), predVals(sim)[ok], tolerance = 1e-9) +}) + +test_that("a row without climateRef is unchanged: the same p, x and a vector of parameters", { + sim <- toyRun(inputsCC(ref = NULL)) + expect_equal(predVals(sim)[cellsPL], pHandPL(1.9), tolerance = 1e-9) + expect_identical(sim$fireSense_SpreadPowerLaw, c(pc = 0.25, gamma = 1.9, floor = 0.13, shape = 1)) + expect_identical(predVals(sim), predVals(toyRun(inputsPL()))) +}) + +test_that("a climateRef row without a p50 stops, naming it", { + expect_error(toyRun(inputsCC(p50 = NULL)), "powerLawPc50") +}) + +test_that("with several ELFs the per-pixel parameters are blended, an ELF without climateRef contributing its vector", { + ins <- multiInputs() + ins$studyAreaWithSpreadParams$params <- lapply(ins$studyAreaWithSpreadParams$params, function(p) { p$MDC <- 1; p }) + ins$studyAreaWithSpreadParams[[linkColPL]] <- c("powerLaw", "powerLaw") + ins$studyAreaWithSpreadParams[[gammaColPL]] <- c(2, 4) + ins$studyAreaWithSpreadParams[[pc50ColCC]] <- c(0.3, 0.3) + ins$studyAreaWithSpreadParams[[refColCC]] <- list(list(MDC = 0.25), NULL) # ELF A: climate in the ceiling; ELF B: not + sim <- toyRun(ins, params = list(ELFblendWidth = 20000)) + pl <- sim$fireSense_SpreadPowerLaw + expect_s4_class(pl, "SpatRaster") + pc <- terra::values(pl[["pc"]], mat = FALSE) + ## MDC is 100 everywhere: rescaled 0.5, shift = 1 * (0.5 - 0.25); ELF A's pc, ELF B's maxAsymptote 0.27 + pcA <- 0.3 - (0.3 - 0.25) * exp(-0.25) + expect_equal(pc[1], pcA, tolerance = 1e-9); expect_equal(pc[10], 0.27, tolerance = 1e-9) + expect_true(all(pc >= min(pcA, 0.27) - 1e-9 & pc <= max(pcA, 0.27) + 1e-9, na.rm = TRUE)) + ## x has the fuels only: fuelA / 8 (coefficient 0) = 0 in A; with MDC out of x, x is 0 where MDC was the only term + expect_equal(terra::values(sim$fireSense_SpreadLinear, mat = FALSE)[1], 0, tolerance = 1e-9) +}) diff --git a/tests/testthat/test-powerLaw.R b/tests/testthat/test-powerLaw.R index 65337a3..9d617b6 100644 --- a/tests/testthat/test-powerLaw.R +++ b/tests/testthat/test-powerLaw.R @@ -8,24 +8,7 @@ ## have maxAsymptote = 0.25, hillSlope1 = 2, and coefficients 1.5, -0.5, 1 (the power law ignores hillSlope1: ## the fit fixes it at 1, and it is the linear predictor that p depends on). -linkColPL <- fireSenseUtils::spreadLinkTxt -gammaColPL <- fireSenseUtils::spreadFitPowerLawGammaTxt -shapeColPL <- fireSenseUtils::spreadFitPowerLawShapeTxt -cellsPL <- c(1, 2, 3, 4, 6, 7, 8) - -inputsPL <- function(gamma = 1.9, link = "powerLaw") { - ins <- toyInputs() - if (!is.null(link)) ins$studyAreaWithSpreadParams[[linkColPL]] <- link - if (!is.null(gamma)) ins$studyAreaWithSpreadParams[[gammaColPL]] <- gamma - ins -} - -## by hand, in cell order -pHandPL <- function(gamma = 1.9, pc = 0.25, floor = 0.13, shape = 1) { - cv <- toyCovariates(); o <- order(cv$pixelID) - x <- 1.5 * cv$MDC[o] / 200 - 0.5 * cv$youngAge[o] + 1 * cv$fuelA[o] / 8 - pmax(pc - (pc - floor) * exp(-sign(x) * abs(x / gamma)^shape), 0) -} +## linkColPL, gammaColPL, shapeColPL, cellsPL, inputsPL() and pHandPL() are in setup-toySpread.R (test-climateCeiling.R uses them). test_that("a powerLaw row predicts p = pc - (pc - floor) * exp(-x / gamma), with its own gamma", { v <- predVals(toyRun(inputsPL())) From 900edbe1ef490e3a8d6453f38974aeb72339d9d0 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 18 Nov 2026 21:02:45 -0700 Subject: [PATCH 2/2] ledgerPowerLawPc50() stops for a climate row without p50; blend with linkParsRas() Co-Authored-By: Claude Opus 5.5 --- fireSense_spreadPredict.R | 15 ++++++++------- tests/testthat/test-climateCeiling.R | 12 +++++++++--- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index 3f910d7..6b726c8 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -316,11 +316,8 @@ spreadPredictRun <- function(sim) { sim[[nm]][covs$pixelID[ok]] <- accSD[ok, nm] / wsum[ok] } if (any(wsumPL > 0)) { ## a power-law or Richards fit: the link's parameters blended over those ELFs; NA where there is none - sim$fireSense_SpreadPowerLaw <- rast(sim$flammableRTM, nlyrs = length(linkParNames)) - names(sim$fireSense_SpreadPowerLaw) <- linkParNames okPL <- ok & wsumPL > 0 - for (nm in linkParNames) - sim$fireSense_SpreadPowerLaw[[nm]][covs$pixelID[okPL]] <- accPL[okPL, nm] / wsumPL[okPL] + sim$fireSense_SpreadPowerLaw <- linkParsRas(sim$flammableRTM, covs$pixelID[okPL], accPL[okPL, , drop = FALSE] / wsumPL[okPL]) sim$fireSense_SpreadLinear <- linearPredictorRas(sim$flammableRTM, data.table(pixelID = covs$pixelID[okPL], linearPredictor = accX[okPL] / wsumPL[okPL])) @@ -709,11 +706,15 @@ ledgerClimateRef <- function(sa, i) { #' #' @param sa `sim$studyAreaWithSpreadParams`, one row per ELF. #' @param i integer; the row. -#' @return `p50`, or `NULL` for a row without the column or with `NA`. +#' @return `p50`, or `NULL` for a row without the column or with `NA`. A row with `climateRef_spread` and a power-law +#' link but no finite `p50` stops, naming the row. ledgerPowerLawPc50 <- function(sa, i) { col <- fireSenseUtils::spreadFitPowerLawPc50Txt - if (!col %in% names(sa)) return(NULL) - p50 <- sa[[col]][[i]] + p50 <- if (col %in% names(sa)) sa[[col]][[i]] + if (!is.null(ledgerClimateRef(sa, i)) && any(ledgerSpreadLink(sa, i) %in% fireSenseUtils::spreadPowerLawLinks) && + !(is.numeric(p50) && length(p50) == 1L && is.finite(p50))) + stop("fireSense_spreadPredict: ledger row ", i, " has climate in the ceiling ('", fireSenseUtils::spreadFitClimateRefTxt, + "' and spreadLink '", ledgerSpreadLink(sa, i), "') but no finite '", col, "' (", format(p50), ")", call. = FALSE) if (is.null(p50) || is.na(p50)) NULL else p50 } diff --git a/tests/testthat/test-climateCeiling.R b/tests/testthat/test-climateCeiling.R index 5270c54..4d0100e 100644 --- a/tests/testthat/test-climateCeiling.R +++ b/tests/testthat/test-climateCeiling.R @@ -30,7 +30,7 @@ test_that("ledgerPowerLawPc50() reads the row's p50, NULL when absent or NA", { sa[[pc50ColCC]] <- 0.3 expect_identical(ledgerPowerLawPc50(sa, 1L), 0.3) sa[[pc50ColCC]] <- NA_real_ - expect_null(ledgerPowerLawPc50(sa, 1L)) + expect_null(ledgerPowerLawPc50(sa, 1L)) # no climateRef: not needed }) test_that("a row with climateRef and a power-law link predicts with climate moving the ceiling toward p50", { @@ -68,8 +68,14 @@ test_that("a row without climateRef is unchanged: the same p, x and a vector of expect_identical(predVals(sim), predVals(toyRun(inputsPL()))) }) -test_that("a climateRef row without a p50 stops, naming it", { - expect_error(toyRun(inputsCC(p50 = NULL)), "powerLawPc50") +test_that("a climateRef row without a finite p50 stops, naming the row", { + expect_error(toyRun(inputsCC(p50 = NULL)), "ledger row 1 has climate in the ceiling") + expect_error(toyRun(inputsCC(p50 = NA_real_)), "ledger row 1 has climate in the ceiling") + sa <- inputsCC(p50 = NA_real_)$studyAreaWithSpreadParams + expect_error(ledgerPowerLawPc50(sa, 1L), "no finite") + ## a row without climateRef has no use for it: NULL, no error + sa[[refColCC]] <- NULL + expect_null(ledgerPowerLawPc50(sa, 1L)) }) test_that("with several ELFs the per-pixel parameters are blended, an ELF without climateRef contributing its vector", {