Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# fireSense_spreadPredict (development version)

- A fit made with `fireSense_dataPrepFit`'s `spreadClimateCurve` has a coefficient `<var>_curve` for each climate variable. Prediction builds that covariate, `softplus(<var> - k, s)`, from the pixel's own value and the `k` and `s` stored in the ledger row (`climateCurvePars_spread`, `fireSenseUtils::ledgerClimateCurvePars()`, `fireSenseUtils::addClimateCurve()`), as the fit did, and no new parameter is needed. A curve coefficient with no `k` and `s` in its row stops. A row without curve terms predicts as before. Needs fireSenseUtils with `addClimateCurve()` (>= 0.2.3.9196).

- The functions that read a ledger row (`ledgerLinkArgs()`, `ledgerCovCentre()`, `ledgerClimateRef()`, `ledgerPowerLawPc50()`, `ledgerSpreadClimate()`, `ledgerCovMinMax()` and their helpers) now live in `fireSenseUtils`, which also uses them (`spreadFuelEffect()`, the fuel effect on the ELF map), so a row is read in one place. They are moved unchanged; the only difference is that their errors say "spread ledger row" instead of "fireSense_spreadPredict: ledger row". Needs fireSenseUtils >= 0.2.3.9191 (PredictiveEcology/fireSenseUtils#260, version to be set after it merges).

- A ledger row of `fireSense_spreadFit`'s `spreadClimate = "activation"` predicts as that fit: fuel sets each pixel's ceiling `pc` below p50 and climate is the linear predictor (`fireSenseUtils::spreadLinkInputs(activationIntercept =)`). The row's mode is read by the new `ledgerSpreadClimate()` (column `fireSenseUtils::spreadClimateTxt`); a row without it is "ceiling" when it has `climateRef_spread` and a power-law link, else "predictor", as before. The parameter set's `activationIntercept` is not a covariate coefficient: it goes to the link, and a set and its row that disagree stop. `fireSense_SpreadPowerLaw` is then a per-pixel raster, and `fireSense_SpreadLinear` is the climate term, so `fireSense_burn` adds the year effect to it unchanged. A row that records its mode is predicted by it: "predictor" keeps climate in x even with a `climateRef_spread`, and "ceiling" or "activation" without one stops. An activation ELF is not blended with an ELF of another mode (an error, beside the one for different links; ceiling with predictor still blends), and the activation's lower-asymptote check uses the run's `lowerSpreadProb`. Other rows predict as before. Needs fireSenseUtils >= 0.2.3.9183 (PredictiveEcology/fireSenseUtils#255).
Expand Down
26 changes: 25 additions & 1 deletion fireSense_spreadPredict.R
Original file line number Diff line number Diff line change
Expand Up @@ -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.9191)"), # 9191 (placeholder until fireSenseUtils#260 merges and is bumped): the ledger*() row readers (fireSenseUtils#260); 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
"PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9196)"), # 9196 (fireSenseUtils#265): ledgerClimateCurvePars(), addClimateCurve(), isClimateTermCol(), climateTermBase(); 9191 (placeholder until fireSenseUtils#260 merges and is bumped): the ledger*() row readers (fireSenseUtils#260); 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",
Expand Down Expand Up @@ -260,6 +260,7 @@ spreadPredictRun <- function(sim) {
yr = time(sim),
maxFireSpread = P(sim)$maxFireSpread, lowerSpreadProb = P(sim)$lowerSpreadProb,
covCentre = fireSenseUtils::ledgerCovCentre(sa, 1L), climateRef = fireSenseUtils::ledgerClimateRef(sa, 1L),
climateCurvePars = fireSenseUtils::ledgerClimateCurvePars(sa, 1L),
powerLawPc50 = fireSenseUtils::ledgerPowerLawPc50(sa, 1L)), lk1))
for (nm in names(randomEffectOutputs)) sim[[nm]] <- randomEffectSDOf(params1, randomEffectOutputs[[nm]])
sim$fireSense_SpreadLink <- lk1$link
Expand Down Expand Up @@ -309,6 +310,7 @@ spreadPredictRun <- function(sim) {
lowerSpreadProb = P(sim)$lowerSpreadProb,
elfPixels = if (isSplit[i]) which(elfLab %in% ids[i]),
covCentre = fireSenseUtils::ledgerCovCentre(sa, i), climateRef = fireSenseUtils::ledgerClimateRef(sa, i),
climateCurvePars = fireSenseUtils::ledgerClimateCurvePars(sa, i),
powerLawPc50 = fireSenseUtils::ledgerPowerLawPc50(sa, i)), lks[[i]]))
rows <- these[match(p$pixelID, covs$pixelID[these])]
acc[rows] <- acc[rows] + w[rows, i] * p$spreadProb
Expand Down Expand Up @@ -505,6 +507,11 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) {
#' the covariates are rescaled and centred, as in the fit. A coefficient named `a:b` is an interaction: `covs` must
#' 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 climateCurvePars the ELF's `climateCurvePars_spread` (`fireSenseUtils::ledgerClimateCurvePars()`): `k` and `s` of each
#' climate variable of a fit made with `fireSense_dataPrepFit`'s `spreadClimateCurve`. A coefficient named `<var>_curve`
#' multiplies `fireSenseUtils::softplus(<var> - k, s)` of the pixel's own value, made as in the fit (`fireSenseUtils::addClimateCurve()`), before
#' the split terms replace the variable. `NULL` (a fit without curve terms, or an older ledger row) makes none; a curve
#' coefficient without its `k` and `s` stops.
#' @param climateRef the ELF's `climateRef_spread` (`fireSenseUtils::ledgerClimateRef()`): with a fit made with climate outside the
#' `maxAsymptote` ceiling (`fireSense_spreadFit`'s `spreadLink = "climateOutside"`) or moving it (`spreadClimate =
#' "ceiling"`), the reference value of each climate covariate; `fireSenseUtils::spreadProbFromCovs()` and
Expand Down Expand Up @@ -535,6 +542,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) {
#' the ceiling a matrix with one row per pixel.
spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, elfPixels = NULL, flammableRTM = NULL,
covCentre = NULL, climateRef = NULL, powerLawPc50 = NULL, powerLawGamma = NULL,
climateCurvePars = NULL,
powerLawShape = fireSenseUtils::spreadPowerLawShape,
link = if (!is.null(powerLawGamma)) "powerLaw",
lowerAsymptote = fireSenseUtils::spreadProbFloor,
Expand Down Expand Up @@ -581,6 +589,22 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp
fitted <- setdiff(names(params), c(unlist(fireSenseUtils::logisticParamNames), fireSenseUtils::spreadInterceptTxt))
## 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 spreadClimateCurve has `<var>_curve` = softplus(var - k, s), `k` and `s` from the ledger row;
## made from the pixel's own value, so before the split below removes the variable
curveCols <- needed[fireSenseUtils::isClimateTermCol(needed, fireSenseUtils::climateCurveSuffix)]
if (length(curveCols)) {
curveVars <- fireSenseUtils::climateTermBase(curveCols, fireSenseUtils::climateCurveSuffix)
noPars <- setdiff(curveVars, names(climateCurvePars))
if (length(noPars))
stop(moduleName, "> the fitted coefficients ", paste(curveCols[curveVars %in% noPars], collapse = ", "), " need `k` and `s`, but the ledger row's '",
fireSenseUtils::spreadFitClimateCurveParsTxt, "' has ", if (length(climateCurvePars)) paste(names(climateCurvePars), collapse = ", ") else "none",
call. = FALSE)
noClimate <- setdiff(curveVars, names(covs))
if (length(noClimate))
stop(moduleName, "> the fitted curve coefficients ", paste(curveCols[curveVars %in% noClimate], collapse = ", "),
" have no climate covariate ", paste(noClimate, collapse = ", "), call. = FALSE)
fireSenseUtils::addClimateCurve(covs, climateCurvePars[curveVars])
}
## a fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as `<var>_yr` and `<var>_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
Expand Down
63 changes: 63 additions & 0 deletions tests/testthat/test-climateCurve.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
## A fit made with fireSense_dataPrepFit's spreadClimateCurve has `MDC_curve = softplus(MDC - k, s)`, k and s the ELF's median and sd stored in the
## ledger row (`climateCurvePars_spread`). Prediction builds the term from the pixel's own MDC and those
## (fireSenseUtils::addClimateCurve(), the function the fit used), rescaled with c(0, 100) (fireSenseUtils::climateCurveRanges()).

curveParams <- function(curve = 1.2, fuel = 1) {
data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC = 1.5, MDC_curve = curve, fuelA = fuel)
}
curveInputs <- function(knots = list(MDC = c(k = 100, s = 40)), params = curveParams(), covs = toyCovariates()) {
ins <- toyInputs(covs = covs, params = params, formula = "~ MDC + MDC_curve + fuelA - 1")
ins$covMinMax_spread <- data.table::data.table(MDC = c(0, 200), MDC_curve = c(0, 100), fuelA = c(0, 8))
if (!is.null(knots)) ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitClimateCurveParsTxt]] <- I(list(knots))
ins
}

test_that("the curve is built from the pixel's MDC and the ledger row's k and s, as the fit built it", {
covs <- toyCovariates()
v <- predVals(toyRun(curveInputs(covs = covs)))
o <- order(covs$pixelID)
mdc <- covs$MDC[o]; fuel <- covs$fuelA[o]
## the fit's own function, on the same raw values
fit <- data.table::data.table(MDC = mdc)
fireSenseUtils::addClimateCurve(fit, list(MDC = c(k = 100, s = 40)))
expect_equal(fit$MDC_curve, 40 * log1p(exp((mdc - 100) / 40)))
x <- 1.5 * (mdc / 200) + 1.2 * (fit$MDC_curve / 100) + 1 * (fuel / 8)
cells <- c(1, 2, 3, 4, 6, 7, 8)
expect_equal(v[cells], handLogistic3(x), tolerance = 1e-4)
})

test_that("a positive curve coefficient raises the prediction everywhere (smooth: no pixel is exactly unchanged), a negative one lowers it", {
with0 <- predVals(toyRun(curveInputs(params = curveParams(curve = 0))))
pos <- predVals(toyRun(curveInputs(params = curveParams(curve = 1.2))))
neg <- predVals(toyRun(curveInputs(params = curveParams(curve = -1.2))))
cells <- c(1, 2, 3, 4, 6, 7, 8)
expect_true(all(pos[cells] > with0[cells]))
expect_true(all(neg[cells] < with0[cells]))
})

test_that("a curve coefficient with no k and s in the ledger row stops, naming it", {
expect_error(toyRun(curveInputs(knots = NULL)), "MDC_curve.*need `k` and `s`")
expect_error(toyRun(curveInputs(knots = list(CMD = c(k = 5, s = 1)))), "MDC_curve.*need `k` and `s`")
})

test_that("a fit without curve terms predicts as before, even with k and s in its row", {
base <- predVals(toyRun())
ins <- toyInputs()
ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitClimateCurveParsTxt]] <- I(list(list(MDC = c(k = 100, s = 40))))
expect_identical(predVals(toyRun(ins)), base)
expect_false(any(fireSenseUtils::isClimateTermCol(names(toyParams()), fireSenseUtils::climateCurveSuffix)))
})

test_that("with a split fit the curve is of the pixel's own value, beside the split terms", {
covs <- toyCovariates()
p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, MDC_curve = 1.2, fuelA = 1)
ins <- toyInputs(covs = covs, params = p, formula = "~ MDC_yr + MDC_dev + MDC_curve + fuelA - 1")
ins$covMinMax_spread <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), MDC_curve = c(0, 100), fuelA = c(0, 8))
ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitClimateCurveParsTxt]] <- I(list(list(MDC = c(k = 100, s = 40))))
v <- predVals(toyRun(ins))
o <- order(covs$pixelID)
mdc <- covs$MDC[o]; fuel <- covs$fuelA[o]
med <- stats::median(covs$MDC)
x <- 1.5 * (med / 200) + 0.8 * ((mdc - med + 100) / 200) + 1.2 * (40 * log1p(exp((mdc - 100) / 40)) / 100) + 1 * (fuel / 8)
expect_equal(v[c(1, 2, 3, 4, 6, 7, 8)], handLogistic3(x), tolerance = 1e-4)
})
Loading