diff --git a/NAMESPACE b/NAMESPACE index 5a11cd4..a04f2bf 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -26,6 +26,8 @@ export(ELFsNotFitted) export(ELFsSkipped) export(ELFsizePlan) export(ELFtemplateRaster) +export(activationDudYearShare) +export(activationInterceptTxt) export(adWeightAuto) export(addBufferEdge) export(addFitClimateVariables) @@ -227,10 +229,13 @@ export(scorePopulationTerms) export(setXgbThreads) export(simulateFireSizes) export(sizeRuleLandCover) +export(spreadActivationInterceptBounds) export(spreadAddInteractions) export(spreadAsymptoteLinks) export(spreadClimateCols) +export(spreadClimateOptions) export(spreadClimateRef) +export(spreadClimateTxt) export(spreadCovCentre) export(spreadCovCols) export(spreadDesignCols) @@ -239,6 +244,7 @@ export(spreadFitAdditionalColNamesTxt) export(spreadFitClimateRefTxt) export(spreadFitClimateVariables) export(spreadFitCovCentreTxt) +export(spreadFitDudYearShareTxt) export(spreadFitFileTag) export(spreadFitFilenameFor) export(spreadFitFuelScaleTxt) @@ -247,6 +253,7 @@ export(spreadFitLedgerFolder) export(spreadFitLedgerInputLists) export(spreadFitLedgerInputs) export(spreadFitLowerAsymptoteTxt) +export(spreadFitPcAtP50Txt) export(spreadFitPowerLawGammaTxt) export(spreadFitPowerLawPc50Txt) export(spreadFitPowerLawPcMarginTxt) diff --git a/NEWS.md b/NEWS.md index e62e8aa..ce4e03d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # fireSenseUtils (development version) +* A third place for climate in the spread link, `spreadClimate = "activation"` in `fireSense_spreadFit`: fuel sets each pixel's own ceiling and climate decides how much of it is reached. `spreadLinkInputs()` (and `spreadProbFromCovs()`) take `activationIntercept`: then `pc_i = f + (p50 - f) * plogis(eta_i)`, with `eta_i` the linear predictor of the non-climate columns, and `x_i = activationIntercept + sum(beta_clim * (climate - climateRef))`, so `p <= p50` everywhere and the ratio of `p - f` between two pixels does not change with climate. It needs `climateRef`, `powerLawPc50` and `"powerLawSmooth"` with `lowerAsymptote = lowerSpreadProb` (below the floor the other forms fall faster for a higher `pc`, which would rank rich fuel below poor in a wet year). In the fit's parameters `activationIntercept` (`activationInterceptTxt`, default bounds `spreadActivationInterceptBounds`, `c(-10, 10)`) comes right before the random-effect sds and `maxAsymptote` is not fitted: the objective puts `powerLawPc50` in its place, so the gates and the saturation summary use p50 as the ceiling, and they look at `p`, not at `p` at the reference climate. `spreadRandomEffectArgs()` sets the objective's new `fitActivationIntercept` from the bounds, as for the random effects, so `runDEoptim()`, its re-score and an emulator pass it; `spreadProbGates()` and `spreadFitValidationData()` find it by name. New ledger constants `spreadClimateTxt` (`"spreadClimate"`, the mode of a fit) and `spreadClimateOptions`. The same mechanism fixes p_c at p50 in the "predictor" link: with the new `pcAtP50 = TRUE` (`.objfunSpreadFit()`, `runDEoptim()`, `spreadProbGates()`, `spreadFitValidationData()`; `fireSense_spreadFit`'s `powerLawPcAtP50`) `maxAsymptote` is left out of the fitted parameters and the objective puts `powerLawPc50` in its place, so the bounds never have a zero width (an emulator start divides by it). New `activationDudYearShare()`: the share of years whose year-effect draw puts every pixel at the floor at the reference climate, `pnorm(-activationIntercept / yearSpreadSD)`, which `fireSense_spreadFit` stores in an activation row (`spreadFitDudYearShareTxt`); `spreadFitPcAtP50Txt` marks a row whose p_c was fixed. With `powerLawPc50` given, the objective now stops on an unnamed `par` whose length does not match the formula and the link (a missing `pcAtP50` would otherwise read the first coefficient as p_c), and `runDEoptim()`'s start-up message lists `activationIntercept` apart from the logistic parameters. Fits without `activationIntercept` or `pcAtP50` give what they gave, and their calls and cache keys are unchanged. * New `yearClimateColumn()`, `yearClimateMeans()` and `yearClimateMultiplier()`: the one place the year-level climate term of the expected ignitions lives. `fireSense_ignitionFit` fits `exp(beta * z)` (`beta >= 0`, `z` the standardised yearly mean of one climate covariate) and stores `list(variable, center, scale, beta)`; `fireSense_ignitionPredict` applies it with `yearClimateMultiplier()`. * The spread and ignition ledgers now have separate Google Drive folders, in a new `FireSenseData` folder: `spreadFitLedgerFolder()` is `FireSenseData/SpreadFitParams` (the old `FireSense_SCANFI` folder, renamed; same id) and `ignitionFitLedgerFolder()` is `FireSenseData/IgnitionFitParams`, each with its own `"testing"` subfolder (`testing = TRUE`) and an `"archived"` subfolder for superseded ledgers. `options(fireSenseUtils.ignitionFitLedgerFolder = )` no longer follows `fireSenseUtils.spreadFitLedgerFolder`: set each option on its own. New `elfCacheFolder()` (option `fireSenseUtils.elfCacheFolder`), `FireSenseData/ELFs`, is where fireSense_ELFs shares the national ELF map, which was cached in the spread ledger folder. * Climate can move the spread ceiling toward the landscape's runaway threshold. With a power-law link (`"powerLaw"`, `"powerLawSmooth"`), a `climateRef` and the landscape's `powerLawPc50` ([calibratePowerLaw()]`$p50`), each pixel's `pc` is `max(p50 - (p50 - pc0) * exp(-shift), lowerSpreadProb)`, `shift = sum(beta_clim * (climate - climateRef))`, and the linear predictor holds only the non-climate columns. `p` never passes `p50`, `pc = pc0` at the reference climate, and `log(p50 - pc)` is linear in climate, so log mean fire size is too. The one place the split and `pc` are computed is the new exported `spreadLinkInputs()` (linear predictor and link parameters, a matrix with one row per pixel in this mode); `spreadProbFromCovs()` and the objective call it, and the objective gives `spreadCpp()` a per-cell `linkPars` matrix on the whole landscape (cells, and rows with no climate, that cannot burn get `unburnableLinkPars()`). `logisticAll()`, `spreadProbFromCovs()` and the objective compute every linear link through `spreadLinkInputs()`; with `climateRef` it stops when `pc0` is above `powerLawPc50`, and `plotSpreadFitResponse()` draws `p50` as the ceiling. `spreadProbFromCovs()`, `.objfunSpreadFit()`, `runDEoptim()`, `spreadFitValidationData()`, `spreadProbGates()` and `plotSpreadFitResponse()` take `powerLawPc50`; `powerLawPcBounds(climateCeiling = TRUE)` bounds `pc0` above by `p50`. Before, `climateRef` with a power-law link stopped, and without `climateRef` nothing changes. diff --git a/R/DEoptim_fns.R b/R/DEoptim_fns.R index 454c627..63af8c3 100644 --- a/R/DEoptim_fns.R +++ b/R/DEoptim_fns.R @@ -91,7 +91,9 @@ deoptimPopulationSize <- function(nParams) { #' If named and including `yearSpreadSD` (which must be last), the per-year random effect (a seasonal departure) of #' [.objfunSpreadFit()] (`fitYearSpreadSD`) is fitted, in the fit and in the re-score. Likewise `fireSpreadSD`, the #' per-fire random effect (`fitFireSpreadSD`; needs `wholeLandscape = TRUE`), which comes just before -#' `yearSpreadSD`, or last without it. A fit without `fireSpreadSD` keeps its cache keys. +#' `yearSpreadSD`, or last without it. A fit without `fireSpreadSD` keeps its cache keys. With `activationIntercept` +#' ([activationInterceptTxt]), right before them and without `maxAsymptote`, the fit is `spreadClimate = "activation"` +#' (`fitActivationIntercept` of [.objfunSpreadFit()]); it needs `climateRef` and `powerLawPc50`. #' #' @param upper Numeric vector. Upper bounds for the parameters being optimized. #' Passed to [DEoptim::DEoptim]. @@ -117,6 +119,8 @@ deoptimPopulationSize <- function(nParams) { #' @param powerLawPc50 Passed to [.objfunSpreadFit()] with `climateRef`: `NULL` (default), or the landscape's runaway #' threshold ([calibratePowerLaw()]), which with a power-law `link` puts climate in the ceiling ([spreadLinkInputs()]). #' `NULL` leaves the call and its cache key as they were. +#' @param pcAtP50 Passed to [.objfunSpreadFit()] like `powerLawPc50`: `TRUE` when `lower` has no `maxAsymptote` because +#' p_c is fixed at `powerLawPc50`. `NULL` (default) leaves the call and its cache key as they were. #' @param powerLawGamma The `"powerLaw"` and `"powerLawSmooth"` links' `gamma` ([powerLawLink()]), passed to [.objfunSpreadFit()] in the #' fit and the re-score. Used only with those links; with any other link it is left out of the cache #' keys ([powerLawOmitArgs()]) and the re-score's arguments, so they are what they were. @@ -277,6 +281,7 @@ runDEoptim <- function(landscape, convergence = NULL, climateRef = NULL, powerLawPc50 = NULL, + pcAtP50 = NULL, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, @@ -346,9 +351,11 @@ runDEoptim <- function(landscape, ## name the parameters from `lower`. termsInDEoptim() called every non-formula parameter a "logit" ## term, so yearSpreadSD was reported as a third logistic parameter. covTerms <- spreadDesignCols(formulaToFit) # includes the intercept, if the formula has one - logisticTerms <- setdiff(names(lower), c(covTerms, spreadRandomEffectTxt)) - message("Fitting ", length(lower), " parameters: logistic: ", paste(logisticTerms, collapse = ", "), + logisticTerms <- setdiff(names(lower), c(covTerms, spreadRandomEffectTxt, activationInterceptTxt)) + message("Fitting ", length(lower), " parameters: logistic: ", + if (length(logisticTerms)) paste(logisticTerms, collapse = ", ") else "none (maxAsymptote fixed at powerLawPc50)", "; covariates: ", paste(covTerms, collapse = ", "), + if (activationInterceptTxt %in% names(lower)) paste0("; activation: ", activationInterceptTxt), if (fireSpreadSDTxt %in% names(lower)) paste0("; fire effect: ", fireSpreadSDTxt), if (yearSpreadSDTxt %in% names(lower)) paste0("; year effect: ", yearSpreadSDTxt)) ## the random effects are fitted when the bounds include them; DEoptim passes `par` unnamed, so the objective is @@ -356,6 +363,7 @@ runDEoptim <- function(landscape, reArgs <- spreadRandomEffectArgs(lower, wholeLandscape) fitYearSpreadSD <- reArgs$fitYearSpreadSD fitFireSpreadSDArg <- reArgs$fitFireSpreadSD + fitActivationInterceptArg <- reArgs$fitActivationIntercept # NULL without it: the call and its key are what they were ## clusterSetup() digested the objects it shipped once; the fit, its re-score, profile and simulated members ## all run the objective on them @@ -378,6 +386,7 @@ runDEoptim <- function(landscape, covCentre = covCentre, climateRef = climateRef, powerLawPc50 = powerLawPc50, + pcAtP50 = pcAtP50, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, @@ -402,6 +411,7 @@ runDEoptim <- function(landscape, link = link, fitYearSpreadSD = fitYearSpreadSD, fitFireSpreadSD = fitFireSpreadSDArg, + fitActivationIntercept = fitActivationInterceptArg, escapeSizeHa = escapeSizeHa, jumpTries = jumpTries, jumpMeanDist = jumpMeanDist, @@ -424,7 +434,8 @@ runDEoptim <- function(landscape, if (identical(gateRefusal, "minLik")) "gateRefusal", omitNullArgs(crpsWeights = crpsWeights, covCentre = covCentre, runawayBufferMultiple = runawayBufferMultiple, convergence = convergence, climateRef = climateRef, powerLawPc50 = powerLawPc50, wholeLandscape = wholeLandscapeArg, - fitFireSpreadSD = fitFireSpreadSDArg)), + fitFireSpreadSD = fitFireSpreadSDArg, fitActivationIntercept = fitActivationInterceptArg, + pcAtP50 = pcAtP50)), ## The data the objective runs on reaches the workers through clusterSetup(objsNeeded), not as an ## argument above, so it is not in this key by itself: two held-out folds of one ELF shared their ## whole fit (2026-09-29). clusterSetup() digested those objects once; use that digest. @@ -455,6 +466,7 @@ runDEoptim <- function(landscape, rescoreArgs$covCentre <- covCentre rescoreArgs$climateRef <- climateRef rescoreArgs$powerLawPc50 <- powerLawPc50 + rescoreArgs$pcAtP50 <- pcAtP50 omitted <- powerLawOmitArgs(link, powerLawShape) for (nm in setdiff(c("powerLawGamma", "powerLawShape", "lowerAsymptote", "richardsNu"), omitted)) rescoreArgs[[nm]] <- get(nm) @@ -462,6 +474,7 @@ runDEoptim <- function(landscape, rescoreArgs$crpsWeights <- crpsWeights rescoreArgs$wholeLandscape <- wholeLandscapeArg rescoreArgs$fitFireSpreadSD <- fitFireSpreadSDArg + rescoreArgs$fitActivationIntercept <- fitActivationInterceptArg if (!identical(gateRefusal, "minLik")) rescoreArgs$gateRefusal <- gateRefusal if (isTRUE(rescoreReps > 0) && !is.null(finalPop)) { colnames(finalPop) <- names(lower) diff --git a/R/constants.R b/R/constants.R index 02a5724..dff4d02 100644 --- a/R/constants.R +++ b/R/constants.R @@ -91,13 +91,29 @@ #' [scoreFireSizesByYear()]; areas are in pixels. A fit without the diagnostics (a cross-validation fold, `simulateMembers = 0`) #' writes no such column, and a row written before it has none. #' - `spreadPowerLawPGrid`: `numeric`. The spread probabilities [calibratePowerLaw()] simulates by default. +#' - `spreadClimateTxt`: `character(1)`. Name of the ledger column that holds where a fit put climate +#' (`"spreadClimate"`): one of `spreadClimateOptions`. A row without it (written before it existed) is +#' `"ceiling"` when it has `"climateRef_spread"` and a power-law `"spreadLink"`, else `"predictor"`. +#' - `spreadClimateOptions`: `character`. The values of `fireSense_spreadFit`'s `spreadClimate`: `"predictor"` +#' (climate in the linear predictor with the fuels), `"ceiling"` (climate moves the power-law ceiling, +#' [spreadLinkInputs()]) and `"activation"` (fuel sets each pixel's ceiling, climate is the linear predictor). +#' - `activationInterceptTxt`: `character(1)`. Name of the parameter of `spreadClimate = "activation"` that is +#' the linear predictor at the reference climate (`"activationIntercept"`); in `lower`/`upper` and in a ledger +#' row's `params` it comes right after the covariate coefficients, before the random-effect sds. +#' - `spreadActivationInterceptBounds`: `numeric(2)`. Its default bounds, `c(-10, 10)`. +#' - `spreadFitDudYearShareTxt`: `character(1)`. Name of the ledger column of an `"activation"` fit with the share of +#' years whose draw of the year effect puts every pixel at the floor at the reference climate, one per parameter set +#' ([activationDudYearShare()]; `"dudYearShare_spread"`). +#' - `spreadFitPcAtP50Txt`: `character(1)`. Name of the ledger column that marks a fit whose `maxAsymptote` was fixed at +#' p50, not fitted (`fireSense_spreadFit`'s `powerLawPcAtP50`; `"pcAtP50_spread"`), so its value is not read as a +#' fitted one at its bound. #' #' - `treedWetlandAgbTxt`: `character(1)`. Name of the pooled treed-wetland biomass column #' built by `fireSenseCovariatesCreate(fuelCovariates = "domSecWetland")` (currently #' `"treedWetland_agb"`). #' #' @name fireSenseUtils-constants -#' @aliases polygonIDTxt nonNFColNamesTxt yearTxt polyCauseColTxt polySizeColTxt youngAgeTxt burnableHaTxt treedWetlandTxt treedWetlandAgbTxt ignitionsTxt escapesTxt coreFractionTxt ignitionObjectiveTxt spreadFitAdditionalColNamesTxt ignitionFitAdditionalColNamesTxt spreadInterceptTxt spreadFitCovCentreTxt spreadLinkTxt spreadFitClimateRefTxt spreadFitPowerLawGammaTxt spreadFitPowerLawShapeTxt spreadLinkOptions spreadFitLowerAsymptoteTxt spreadFitRichardsNuTxt spreadRichardsNu spreadRichardsB spreadLowerAsymptoteMin spreadLinearLinks spreadPowerLawLinks spreadAsymptoteLinks spreadLinkParNames spreadPowerLawGamma spreadPowerLawShape spreadFitPowerLawPc50Txt spreadFitPowerLawR2Txt spreadFitPowerLawPcMarginTxt spreadFitInSampleSizesTxt spreadPowerLawPGrid +#' @aliases polygonIDTxt nonNFColNamesTxt yearTxt polyCauseColTxt polySizeColTxt youngAgeTxt burnableHaTxt treedWetlandTxt treedWetlandAgbTxt ignitionsTxt escapesTxt coreFractionTxt ignitionObjectiveTxt spreadFitAdditionalColNamesTxt ignitionFitAdditionalColNamesTxt spreadInterceptTxt spreadFitCovCentreTxt spreadLinkTxt spreadFitClimateRefTxt spreadFitPowerLawGammaTxt spreadFitPowerLawShapeTxt spreadLinkOptions spreadFitLowerAsymptoteTxt spreadFitRichardsNuTxt spreadRichardsNu spreadRichardsB spreadLowerAsymptoteMin spreadLinearLinks spreadPowerLawLinks spreadAsymptoteLinks spreadLinkParNames spreadPowerLawGamma spreadPowerLawShape spreadFitPowerLawPc50Txt spreadFitPowerLawR2Txt spreadFitPowerLawPcMarginTxt spreadFitInSampleSizesTxt spreadPowerLawPGrid spreadClimateTxt spreadClimateOptions activationInterceptTxt spreadActivationInterceptBounds spreadFitDudYearShareTxt spreadFitPcAtP50Txt NULL #' @export @@ -170,6 +186,24 @@ spreadFitPowerLawShapeTxt <- "powerLawShape_spread" #' @export spreadLinkOptions <- c("ceiling", "climateOutside", "powerLaw", "powerLawSmooth", "richards") +#' @export +spreadClimateTxt <- "spreadClimate" + +#' @export +spreadClimateOptions <- c("predictor", "ceiling", "activation") + +#' @export +activationInterceptTxt <- "activationIntercept" + +#' @export +spreadActivationInterceptBounds <- c(-10, 10) + +#' @export +spreadFitDudYearShareTxt <- "dudYearShare_spread" + +#' @export +spreadFitPcAtP50Txt <- "pcAtP50_spread" + #' @export spreadFitLowerAsymptoteTxt <- "lowerAsymptote_spread" diff --git a/R/helpers.R b/R/helpers.R index b5fc190..36aa220 100644 --- a/R/helpers.R +++ b/R/helpers.R @@ -206,12 +206,22 @@ richardsLink <- function(x, pc, lower = spreadProbFloor, nu = spreadRichardsNu, #' `fireSense_spreadPredict` for a ledger row. `lower` must be one number from [spreadLowerAsymptoteMin] to [spreadProbFloor] with #' `"powerLawSmooth"` and `"richards"`; `nu` one number, 0 or more, with `"richards"`. Other links have nothing to check. #' +#' With `activation` (`spreadClimate = "activation"`, [spreadLinkInputs()]) the link must be `"powerLawSmooth"` with +#' `lower` equal to `floor`: below the floor the other forms fall faster for a higher `pc`, and with the activation `pc` +#' is set by fuel, so a wet year would rank rich fuel below poor. +#' #' @param link The spread link. #' @param lower,nu The `lowerAsymptote` and `richardsNu` to check; `NULL` is not a number. +#' @param activation Logical; `TRUE` for a fit or a ledger row with `spreadClimate = "activation"`. +#' @param floor The `lowerSpreadProb` the activation's `lower` must equal; default [spreadProbFloor]. #' @return `TRUE`, invisibly; an error otherwise. #' @export -checkLinkParams <- function(link, lower = NULL, nu = NULL) { +checkLinkParams <- function(link, lower = NULL, nu = NULL, activation = FALSE, floor = spreadProbFloor) { one <- function(v) is.numeric(v) && length(v) == 1L && is.finite(v) + if (isTRUE(activation) && !(identical(link, "powerLawSmooth") && one(lower) && isTRUE(all.equal(lower, floor)))) + stop("spreadClimate = 'activation' needs the link 'powerLawSmooth' with lowerAsymptote = lowerSpreadProb (", + format(floor), "); got ", dQuote(format(link), FALSE), " and ", format(lower), ". Below the floor the other ", + "forms fall faster for a higher pc, so a wet year would rank rich fuel below poor.", call. = FALSE) if (any(link %in% spreadAsymptoteLinks) && !(one(lower) && lower >= spreadLowerAsymptoteMin && lower <= spreadProbFloor)) stop("lowerAsymptote must be one number from ", spreadLowerAsymptoteMin, " to ", spreadProbFloor, "; got ", format(lower), diff --git a/R/objFunSpread.R b/R/objFunSpread.R index 6b805bc..849b532 100644 --- a/R/objFunSpread.R +++ b/R/objFunSpread.R @@ -20,7 +20,8 @@ utils::globalVariables(c( #' #' @param par parameters: the logistic parameters (`maxAsymptote` first, then `upperTail1` if the link has #' one; without `hillSlope1` and `inflectionPoint1`, which are fixed at 1 -- see `fixLogisticPars()`), then the covariate coefficients (the intercept's first, when -#' the formula has one -- see [spreadDesignCols()]), and optionally +#' the formula has one -- see [spreadDesignCols()]), then `activationIntercept` with `fitActivationIntercept` (which has no +#' `maxAsymptote`), and optionally #' `fireSpreadSD` (see `fitFireSpreadSD`) and `yearSpreadSD` last (see `fitYearSpreadSD`), in that order. #' #' @param landscape A `SpatRaster` with extent, resolution, and projection (crs) used for @@ -172,7 +173,17 @@ utils::globalVariables(c( #' instead: it moves `pc` toward `powerLawPc50`, never past it ([spreadLinkInputs()]). #' @param powerLawPc50 `NULL` (default), or the landscape's runaway threshold ([calibratePowerLaw()]). With `climateRef` and #' a power-law link it puts climate in the ceiling; needed then. The year effect and the per-fire effect stay on the -#' fuel linear predictor. Ignored without `climateRef`. +#' fuel linear predictor. Without `climateRef` it is used only as the fixed `maxAsymptote` of `pcAtP50`. +#' @param fitActivationIntercept If `TRUE`, `spreadClimate = "activation"` ([spreadLinkInputs()]): the element of `par` +#' right before the random-effect sds is `activationIntercept` ([activationInterceptTxt]), the linear predictor at the +#' reference climate, and `maxAsymptote` is not in `par` (it is `powerLawPc50`, [splitSpreadPar()]). Fuel then sets each +#' pixel's ceiling and climate, with the year and fire effects, is the linear predictor; the gates and the saturation +#' summary look at `p`. Needs `climateRef`, `powerLawPc50` and `link = "powerLawSmooth"` with +#' `lowerAsymptote = lowerSpreadProb`. `NULL` (default): `TRUE` when `par` is named and has `activationIntercept`. +#' DEoptim passes `par` unnamed, so `runDEoptim()` sets it explicitly ([spreadRandomEffectArgs()]). +#' @param pcAtP50 `NULL` (default) or `TRUE`: `maxAsymptote` (p_c of a power-law `link`) is not fitted and not in +#' `par`; it is `powerLawPc50` (`fireSense_spreadFit`'s `powerLawPcAtP50`, [splitSpreadPar()]). A named `par` that has +#' `maxAsymptote` (a ledger row's) keeps it. The activation (`fitActivationIntercept`) implies it. #' #' @param returnSims If `TRUE`, return the simulated fires instead of the objective value: a #' `data.table` with one row per fire year x fire x replicate -- `yr`, `rep`, `initialLocus`, `ids`, @@ -300,6 +311,8 @@ utils::globalVariables(c( runawayBufferMultiple = NULL, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL, + fitActivationIntercept = NULL, + pcAtP50 = NULL, # bufferedRealHistoricalFiresList, verbose = 2, crpsWeights = NULL, @@ -318,7 +331,8 @@ utils::globalVariables(c( if (isTRUE(returnBurned)) returnSims <- TRUE ## the per-year random effect's sd, fitted as the LAST element of `par` ## and hillSlope1 and inflectionPoint1 are fixed at 1, not fitted -- see fixLogisticPars() for why. - parSplit <- splitSpreadPar(par, fitYearSpreadSD, fitFireSpreadSD) + unnamedPar <- is.null(names(par)) + parSplit <- splitSpreadPar(par, fitYearSpreadSD, fitFireSpreadSD, fitActivationIntercept, powerLawPc50, pcAtP50) par <- parSplit$par yearSpreadSD <- parSplit$yearSpreadSD fireSpreadSD <- parSplit$fireSpreadSD @@ -361,6 +375,15 @@ utils::globalVariables(c( colsToUse <- spreadDesignCols(formulaToFit) # How many of the parameters belong to the model? parsModel <- length(colsToUse) + ## An unnamed `par` (DEoptim's) is split by position only: in a fit that may leave p_c out (one with `powerLawPc50`: + ## the ceiling, the activation, pcAtP50) a missing flag would read its first coefficient as maxAsymptote, silently. + ## After the split it holds exactly the logistic parameters (maxAsymptote and the fixed two) and the coefficients. + ## Other calls are not checked: callers (and tests) give other layouts there, as they always could. + nLogistic <- length(fixedLogisticPars) + 1L + identical(link, "logistic3pUpper") + if (unnamedPar && !is.null(powerLawPc50) && length(par) != parsModel + nLogistic) + stop(".objfunSpreadFit(): an unnamed `par` gives ", length(par) - parsModel - length(fixedLogisticPars), + " logistic parameter(s) before the ", parsModel, " coefficients; the link needs ", nLogistic - length(fixedLogisticPars), + ". With p_c not fitted pass `pcAtP50 = TRUE`; check the fit* flags against `lower`.", call. = FALSE) ncells <- ncell(landscape) r <- rast(landscape) @@ -436,6 +459,7 @@ utils::globalVariables(c( cells = cells, covCentre = covCentre, link = link, climateRef = climateRef, powerLawPc50 = powerLawPc50, + activationIntercept = parSplit$activationIntercept, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, richardsNu = richardsNu, returnSims = returnSims, returnBurned = returnBurned, stopCutFires = isTRUE(penaliseRunaways), @@ -771,7 +795,7 @@ objFunInner <- function(yr, annDTx1000, par, parsModel, # normal doYearArea = FALSE, climateRef = NULL, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, doCrps = FALSE, gateRefusal = "minLik", - wholeLandscape = FALSE, powerLawPc50 = NULL) { + wholeLandscape = FALSE, powerLawPc50 = NULL, activationIntercept = NULL) { if (isTRUE(plot.it)) plot.it <- "screen" # needed because data.table objects were recovered from disk @@ -795,9 +819,10 @@ objFunInner <- function(yr, annDTx1000, par, parsModel, # normal shortAnnDT <- covsOfYear(annDTx1000, nonAnnualDTx1000, doAssertions) mat <- as.matrix(shortAnnDT[, ..colsToUse]) ## the linear predictor and link parameters of the year; with climateRef and a power-law link (climate in the - ## ceiling) the parameters are per pixel - linkIn <- if (linearLink) spreadLinkInputs(mat, logisticPars, covPars, lowerSpreadProb, link, climateRef, powerLawPc50, - powerLawGamma, powerLawShape, lowerAsymptote, richardsNu) + ## ceiling, or the activation) the parameters are per pixel. An activation with another link stops there. + linkIn <- if (linearLink || !is.null(activationIntercept)) spreadLinkInputs(mat, logisticPars, covPars, lowerSpreadProb, link, climateRef, powerLawPc50, + powerLawGamma, powerLawShape, lowerAsymptote, richardsNu, + activationIntercept = activationIntercept) ## The gates only skip hopeless parameter sets (gateRefusal = "minLik"); under "simulate" they never run, and ## the plots leave out their panel. runGates <- !identical(gateRefusal, "simulate") @@ -810,8 +835,9 @@ objFunInner <- function(yr, annDTx1000, par, parsModel, # normal ## What the gates and the saturation summary look at. With climate outside the ceiling (climateRef) it is ## p0, the spread probability at the reference climate: the part the ceiling applies to. A dry year ## legitimately takes p past maxFireSpread under that link, and a gate on p would refuse exactly the - ## years that carry the climate signal. Without climateRef it is spreadProb itself, as always. - pGate <- if (!needP) NULL else if (is.null(climateRef)) shortAnnDT$spreadProb else + ## years that carry the climate signal. Without climateRef it is spreadProb itself, as always, and so with the + ## activation: its climate moves each pixel below its own ceiling, never past p50 (= logisticPars[1] then). + pGate <- if (!needP) NULL else if (is.null(climateRef) || !is.null(activationIntercept)) shortAnnDT$spreadProb else as.numeric(spreadProbFromCovs(mat, logisticPars, covPars, lowerSpreadProb, link, climateRef = climateRef, climateAtRef = TRUE, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, richardsNu = richardsNu, powerLawPc50 = powerLawPc50)) @@ -1570,19 +1596,28 @@ areaWeightedCvM <- function(sim, obs) { #' @param lower Named lower bounds of the fit, as `runDEoptim(lower = )`. #' @param wholeLandscape As in `runDEoptim()`: `fireSpreadSD` needs `TRUE` (an error otherwise). #' +#' The same holds for `activationIntercept` ([activationInterceptTxt], `spreadClimate = "activation"`), which must come +#' right before them. +#' #' @return A list of [.objfunSpreadFit()] arguments: `fitYearSpreadSD` (logical) and, only when `lower` has -#' `fireSpreadSD`, `fitFireSpreadSD = TRUE`. A fit without the per-fire effect does not get that argument, so its -#' cache keys are those it had before the effect existed. +#' `fireSpreadSD`, `fitFireSpreadSD = TRUE`, and only when it has `activationIntercept`, `fitActivationIntercept = TRUE`. +#' A fit without the per-fire effect (or the activation) does not get that argument, so its cache keys are those it had +#' before the argument existed. #' @export spreadRandomEffectArgs <- function(lower, wholeLandscape = FALSE) { reTerms <- intersect(spreadRandomEffectTxt, names(lower)) if (length(reTerms) && !identical(utils::tail(names(lower), length(reTerms)), reTerms)) stop("runDEoptim: `", paste(reTerms, collapse = "` then `"), "` must be the last element", if (length(reTerms) > 1) "s", " of `lower` and `upper`") + fitActivationIntercept <- activationInterceptTxt %in% names(lower) + if (fitActivationIntercept && + !identical(utils::tail(names(lower), length(reTerms) + 1L)[1L], activationInterceptTxt)) + stop("runDEoptim: `", activationInterceptTxt, "` must come right before the random-effect sds in `lower` and `upper`") fitFireSpreadSD <- fireSpreadSDTxt %in% names(lower) checkFireSpreadSD(fitFireSpreadSD, wholeLandscape) out <- list(fitYearSpreadSD = yearSpreadSDTxt %in% names(lower)) if (fitFireSpreadSD) out$fitFireSpreadSD <- TRUE + if (fitActivationIntercept) out$fitActivationIntercept <- TRUE out } diff --git a/R/spreadFitValidation.R b/R/spreadFitValidation.R index 2921cf9..dc458fa 100644 --- a/R/spreadFitValidation.R +++ b/R/spreadFitValidation.R @@ -32,7 +32,7 @@ #' probability, without the per-year random effect), and one column per covariate of the formula #' with its raw value (the stored integer / 1000, before rescaling and mutual exclusivity). #' `attr(, "spreadFitValidation")` holds what the plots need: the parameters, `covMinMax`, -#' `covCentre`, `lowerSpreadProb`, `link`, `climateRef`, `powerLawPc50`, `powerLawGamma`, `powerLawShape`, `lowerAsymptote`, `richardsNu`, `Nreps`, the names of the covariates and of the +#' `covCentre`, `lowerSpreadProb`, `link`, `climateRef`, `powerLawPc50`, `activationIntercept`, `powerLawGamma`, `powerLawShape`, `lowerAsymptote`, `richardsNu`, `Nreps`, the names of the covariates and of the #' annual (climate) ones, and `yearsNotSimulated` -- years the objective declined to simulate, #' which have no rows. #' @@ -45,7 +45,8 @@ spreadFitValidationData <- function(par, landscape, annualDTx1000, nonAnnualDTx1 maxFireSpread = spreadProbCeiling, link = NULL, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL, wholeLandscape = FALSE, climateRef = NULL, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, - richardsNu = spreadRichardsNu, seed = NULL, powerLawPc50 = NULL, ...) { + richardsNu = spreadRichardsNu, seed = NULL, powerLawPc50 = NULL, + fitActivationIntercept = NULL, pcAtP50 = NULL, ...) { if (!is.null(seed)) withr::local_seed(seed) objArgs <- utils::modifyList( list(lanscape1stQuantileThresh = Inf, doAssertions = FALSE, verbose = 0), @@ -56,14 +57,16 @@ spreadFitValidationData <- function(par, landscape, annualDTx1000, nonAnnualDTx1 historicalFires = historicalFires, fireBufferedListDT = fireBufferedListDT, covMinMax = covMinMax, mutuallyExclusive = mutuallyExclusive, covCentre = covCentre, Nreps = Nreps, lowerSpreadProb = lowerSpreadProb, maxFireSpread = maxFireSpread, link = link, - fitYearSpreadSD = fitYearSpreadSD, fitFireSpreadSD = fitFireSpreadSD, wholeLandscape = wholeLandscape, - climateRef = climateRef, powerLawPc50 = powerLawPc50, powerLawGamma = powerLawGamma, + fitYearSpreadSD = fitYearSpreadSD, fitFireSpreadSD = fitFireSpreadSD, fitActivationIntercept = fitActivationIntercept, + pcAtP50 = pcAtP50, + wholeLandscape = wholeLandscape, climateRef = climateRef, powerLawPc50 = powerLawPc50, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, richardsNu = richardsNu, returnBurned = TRUE), objArgs)) burned <- attr(sims, "burned") ## the parameters as the objective uses them - par <- splitSpreadPar(par, fitYearSpreadSD, fitFireSpreadSD)$par + parSplit <- splitSpreadPar(par, fitYearSpreadSD, fitFireSpreadSD, fitActivationIntercept, powerLawPc50, pcAtP50) + par <- parSplit$par colsToUse <- spreadDesignCols(formulaToFit) covCols <- spreadCovCols(colsToUse) pp <- paramsSeparate(par, length(colsToUse)) @@ -79,7 +82,8 @@ spreadFitValidationData <- function(par, landscape, annualDTx1000, nonAnnualDTx1 p <- as.numeric(spreadProbFromCovs(as.matrix(used[, ..colsToUse]), pp$logisticPars, pp$covPars, lowerSpreadProb, link = link, climateRef = climateRef, powerLawPc50 = powerLawPc50, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, - lowerAsymptote = lowerAsymptote, richardsNu = richardsNu)) + lowerAsymptote = lowerAsymptote, richardsNu = richardsNu, + activationIntercept = parSplit$activationIntercept)) raw <- spreadProbFromIntegerCovs(NULL, ann, nonAnnualDTx1000, indexNonAnnual, y, NULL, NULL, colsToUse, FALSE, pp$logisticPars, pp$covPars, maxFireSpread, lowerSpreadProb) @@ -101,7 +105,8 @@ spreadFitValidationData <- function(par, landscape, annualDTx1000, nonAnnualDTx1 data.table::setattr(out, "spreadFitValidation", list( logisticPars = pp$logisticPars, covPars = pp$covPars, covMinMax = if (!is.null(covMinMax)) as.list(covMinMax), covCentre = covCentre, - lowerSpreadProb = lowerSpreadProb, link = link, climateRef = climateRef, powerLawPc50 = powerLawPc50, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, + lowerSpreadProb = lowerSpreadProb, link = link, climateRef = climateRef, powerLawPc50 = powerLawPc50, + activationIntercept = parSplit$activationIntercept, powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, richardsNu = richardsNu, Nreps = Nreps, covariates = covCols, intercept = spreadInterceptTxt %in% colsToUse, climateCols = intersect(covCols, names(annualDTx1000[[1]])), @@ -233,6 +238,7 @@ plotSpreadFitResponse <- function(d, covariates = NULL, bins = 40L, title = NULL if (isTRUE(info$intercept)) mat <- cbind(1, mat) stats::qlogis(as.numeric(spreadProbFromCovs(mat, info$logisticPars, info$covPars, info$lowerSpreadProb, link = info$link, climateRef = info$climateRef, powerLawPc50 = info$powerLawPc50, + activationIntercept = info$activationIntercept, powerLawGamma = info$powerLawGamma, powerLawShape = if (is.null(info$powerLawShape)) spreadPowerLawShape else info$powerLawShape, lowerAsymptote = if (is.null(info$lowerAsymptote)) spreadProbFloor else info$lowerAsymptote, @@ -264,7 +270,8 @@ plotSpreadFitResponse <- function(d, covariates = NULL, bins = 40L, title = NULL lv <- intersect(covs, unique(cur$covariate)) set(pts, NULL, "covariate", factor(pts$covariate, levels = lv)) set(cur, NULL, "covariate", factor(cur$covariate, levels = lv)) - ## with climate in the ceiling the ceiling is p50, which pc approaches; else the fitted pc + ## with climate in the ceiling the ceiling is p50, which pc approaches; with the activation p50 bounds every pixel's own + ## ceiling; else the fitted pc ceiling <- if (length(info$climateRef) && !is.null(info$powerLawPc50)) info$powerLawPc50 else info$logisticPars[[1]] limits <- stats::qlogis(c(spreadLinkLower(info$link, info$lowerSpreadProb, info$lowerAsymptote), ceiling)) limits <- limits[is.finite(limits)] diff --git a/R/spreadProbGates.R b/R/spreadProbGates.R index d25b425..13222b7 100644 --- a/R/spreadProbGates.R +++ b/R/spreadProbGates.R @@ -192,15 +192,20 @@ spreadClimateRef <- function(annualDTx1000, nonAnnualDTx1000, formulaToFit, covM #' held at its reference: what the ceiling applies to. The objective's gates and its saturation summary #' look at `p0`, because under this link a dry year legitimately takes the landscape past `maxFireSpread` #' and a gate on `p` would refuse the years that carry the climate signal. Ignored without `climateRef`. +#' @param activationIntercept `NULL` (default), or with `climateRef`, `powerLawPc50` and `link = "powerLawSmooth"` the +#' fitted intercept of `spreadClimate = "activation"`: fuel sets each pixel's ceiling and climate is the linear +#' predictor ([spreadLinkInputs()]). #' @return A one-column numeric matrix, one value per row of `mat` (as [logisticAll()]). #' @export spreadProbFromCovs <- function(mat, logisticPars, covPars, lowerSpreadProb, link = NULL, climateRef = NULL, climateAtRef = FALSE, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, - richardsNu = spreadRichardsNu, powerLawPc50 = NULL) { - if (any(link %in% spreadLinearLinks)) { + richardsNu = spreadRichardsNu, powerLawPc50 = NULL, activationIntercept = NULL) { + ## an activation with another link is refused there + if (any(link %in% spreadLinearLinks) || !is.null(activationIntercept)) { inputs <- spreadLinkInputs(mat, logisticPars, covPars, lowerSpreadProb, link, climateRef, powerLawPc50, - powerLawGamma, powerLawShape, lowerAsymptote, richardsNu, climateAtRef) + powerLawGamma, powerLawShape, lowerAsymptote, richardsNu, climateAtRef, + activationIntercept) return(linearLinkProb(inputs$x, link, inputs$pars)) } if (is.null(climateRef) || !length(climateRef)) @@ -240,23 +245,38 @@ spreadClimateSplit <- function(mat, climateRef, covPars, shift = TRUE) { #' `powerLawPc50` ([calibratePowerLaw()]), never past it. With `shift = sum(beta_clim * (climate - climateRef))` over #' the climate columns of `mat`, `pc = max(p50 - (p50 - pc0) * exp(-shift), lowerSpreadProb)` and `x` is the linear #' predictor of every other column. At the reference climate `pc = pc0 = logisticPars[1]`; `log(p50 - pc)` is linear in -#' climate, so log mean fire size is too. `pars` is then a matrix, one row per row of `mat`. +#' climate. `pars` is then a matrix, one row per row of `mat`. +#' +#' With `activationIntercept` as well (`spreadClimate = "activation"` in `fireSense_spreadFit`) the roles are swapped: +#' fuel sets each pixel's own ceiling and climate is the linear predictor. With `eta` the linear predictor of the +#' non-climate columns (the intercept, fuels, youngAge, non-forest, ...) and `f` = `lowerSpreadProb`, +#' `pc = f + (p50 - f) * plogis(eta)`, so `pc <= p50`, and `x = activationIntercept + shift`. `pc0` is not used +#' (`logisticPars[1]`, which the objective sets to `p50`, [splitSpreadPar()]). Above the floor every pixel's +#' `p - f = (pc - f) * (1 - exp(-(x / gamma)^shape))`, so the ratio of `p - f` between two pixels of a year is the ratio of +#' their `plogis(eta)`, whatever the climate. It needs `"powerLawSmooth"` with `lowerAsymptote = lowerSpreadProb` +#' ([checkLinkParams()]). #' #' @inheritParams spreadProbFromCovs #' @param logisticPars,covPars,lowerSpreadProb As for [spreadProbFromCovs()]. #' @param link One of [spreadLinearLinks]. #' @param powerLawPc50 The landscape's runaway threshold `p50` ([calibratePowerLaw()]); needed, finite, with `climateRef`. #' @param climateAtRef Logical. With `climateRef`, `TRUE` returns the inputs at the reference climate: `x` of the -#' non-climate columns and the vector `pars` with `pc = pc0`. +#' non-climate columns and the vector `pars` with `pc = pc0`; with `activationIntercept`, `x = activationIntercept`. +#' @param activationIntercept `NULL` (default), or the fitted `x` at the reference climate of `spreadClimate = +#' "activation"` ([activationInterceptTxt]); needs `climateRef`. #' @return A list: `x`, a numeric vector, one per row of `mat`; `pars`, a named vector as [linearLinkPars()] gives, or with #' `climateRef` a matrix with one row per row of `mat` and the columns [spreadLinkParNames] gives for `link`. #' @export spreadLinkInputs <- function(mat, logisticPars, covPars, lowerSpreadProb, link, climateRef = NULL, powerLawPc50 = NULL, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, - lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, climateAtRef = FALSE) { + lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, climateAtRef = FALSE, + activationIntercept = NULL) { if (!any(link %in% spreadLinearLinks)) stop("spreadLinkInputs(): `link` must be one of ", paste(dQuote(spreadLinearLinks, FALSE), collapse = ", "), "; got ", dQuote(link, FALSE), call. = FALSE) + activation <- !is.null(activationIntercept) + if (activation && (is.null(climateRef) || !length(climateRef))) + stop("spreadLinkInputs(): `activationIntercept` (spreadClimate = 'activation') needs `climateRef`", call. = FALSE) pc0 <- logisticPars[[1L]] pars <- linearLinkPars(link, pc0, powerLawGamma, lowerSpreadProb, powerLawShape, lowerAsymptote, richardsNu) if (is.null(climateRef) || !length(climateRef)) @@ -266,15 +286,28 @@ spreadLinkInputs <- function(mat, logisticPars, covPars, lowerSpreadProb, link, paste(dQuote(spreadPowerLawLinks, FALSE), collapse = ", "), "); got ", dQuote(link, FALSE), call. = FALSE) if (!(length(powerLawPc50) == 1L && is.finite(powerLawPc50))) stop("spreadLinkInputs(): climate in the ceiling (`climateRef`) needs a finite `powerLawPc50`", call. = FALSE) - if (pc0 > powerLawPc50) + if (activation) { + if (!(length(activationIntercept) == 1L && is.finite(activationIntercept))) + stop("spreadLinkInputs(): `activationIntercept` must be one finite number; got ", format(activationIntercept), + call. = FALSE) + checkLinkParams(link, lowerAsymptote, richardsNu, activation = TRUE, floor = lowerSpreadProb) + } else if (pc0 > powerLawPc50) stop("spreadLinkInputs(): the fitted pc (", format(pc0), ") is above `powerLawPc50` (", format(powerLawPc50), "); with climate in the ceiling bound it by powerLawPcBounds(climateCeiling = TRUE)", call. = FALSE) split <- spreadClimateSplit(mat, climateRef, covPars, shift = !isTRUE(climateAtRef)) - x <- as.vector(mat[, !split$isClim, drop = FALSE] %*% covPars[!split$isClim]) + ## the linear predictor of the non-climate columns: x of the ceiling, eta (the fuel potential) of the activation + lpOther <- as.vector(mat[, !split$isClim, drop = FALSE] %*% covPars[!split$isClim]) ## the climate columns left out: p at the reference climate, with pc = pc0 - if (isTRUE(climateAtRef)) return(list(x = x, pars = pars)) + if (isTRUE(climateAtRef) && !activation) return(list(x = lpOther, pars = pars)) pars <- matrix(pars, nrow = nrow(mat), ncol = length(pars), byrow = TRUE, dimnames = list(NULL, names(pars))) - pars[, "pc"] <- pmax(powerLawPc50 - (powerLawPc50 - pc0) * exp(-as.vector(split$shift)), lowerSpreadProb) + if (activation) { + x <- activationIntercept + if (isTRUE(climateAtRef)) numeric(nrow(mat)) else as.vector(split$shift) + ## a pixel with no fuel term (NA) gives NA here, and is made unburnable below + pars[, "pc"] <- lowerSpreadProb + (powerLawPc50 - lowerSpreadProb) * stats::plogis(lpOther) + } else { + x <- lpOther + pars[, "pc"] <- pmax(powerLawPc50 - (powerLawPc50 - pc0) * exp(-as.vector(split$shift)), lowerSpreadProb) + } ## a row with no climate (or no covariate) gives NA, and spreadCpp() accepts no NA parameter: it cannot burn bad <- is.na(x) | rowSums(is.na(pars)) > 0 if (any(bad)) { @@ -286,10 +319,23 @@ spreadLinkInputs <- function(mat, logisticPars, covPars, lowerSpreadProb, link, #' Split `par` as the objective does: drop the trailing random-effect sds (`fireSpreadSD`, then `yearSpreadSD`) and #' insert the fixed `hillSlope1` and `inflectionPoint1` +#' +#' With `fitActivationIntercept` (`spreadClimate = "activation"`) the parameter before the sds is +#' `activationIntercept` ([activationInterceptTxt]), taken out too, and `maxAsymptote` is not fitted: `powerLawPc50` is +#' put first unless a named `par` has `maxAsymptote` (a ledger row's, written with it). It is the ceiling of every +#' pixel's `p` in that mode, so whatever reads `logisticPars[1]` as the ceiling (the gates, the saturation summary) +#' reads `p50`. With `pcAtP50` (`fireSense_spreadFit`'s `powerLawPcAtP50`) `maxAsymptote` is not fitted either, and is +#' `powerLawPc50` in the same way. +#' @param fitActivationIntercept `NULL` (default): `TRUE` when `par` is named and has `activationIntercept`. +#' @param pcAtP50 `NULL` or `FALSE` (default): `maxAsymptote` is in `par`, unless `fitActivationIntercept`. `TRUE`: it is +#' not, and `powerLawPc50` takes its place. +#' @return A list: `par`, `yearSpreadSD`, `fireSpreadSD` and `activationIntercept` (`NULL` without it). #' @keywords internal -splitSpreadPar <- function(par, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL) { +splitSpreadPar <- function(par, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL, fitActivationIntercept = NULL, + powerLawPc50 = NULL, pcAtP50 = NULL) { if (is.null(fitYearSpreadSD)) fitYearSpreadSD <- yearSpreadSDTxt %in% names(par) if (is.null(fitFireSpreadSD)) fitFireSpreadSD <- fireSpreadSDTxt %in% names(par) + if (is.null(fitActivationIntercept)) fitActivationIntercept <- activationInterceptTxt %in% names(par) sds <- c(fireSpreadSD = 0, yearSpreadSD = 0) trailing <- spreadRandomEffectTxt[c(isTRUE(fitFireSpreadSD), isTRUE(fitYearSpreadSD))] n <- length(trailing) @@ -299,8 +345,26 @@ splitSpreadPar <- function(par, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL) sds[trailing] <- unname(utils::tail(par, n)) par <- utils::head(par, -n) } + activationIntercept <- NULL + if (isTRUE(fitActivationIntercept)) { + if (!is.null(names(par)) && !identical(utils::tail(names(par), 1L), activationInterceptTxt)) + stop("`", activationInterceptTxt, "` must come right before the random-effect sds, after the covariates") + activationIntercept <- unname(utils::tail(par, 1L)) + par <- utils::head(par, -1L) + } + ## maxAsymptote not fitted (the activation, or pc fixed at p50): p50 in its place + if (isTRUE(fitActivationIntercept) || isTRUE(pcAtP50)) { + maxAsymptote <- logisticParamNames[["3p"]][[1L]] + if (is.null(names(par)) || !maxAsymptote %in% names(par)) { + if (!(length(powerLawPc50) == 1L && is.finite(powerLawPc50))) + stop("`maxAsymptote` is not fitted (", if (isTRUE(fitActivationIntercept)) "spreadClimate = 'activation'" else "pcAtP50", + "): it needs a finite `powerLawPc50`") + par <- c(stats::setNames(unname(powerLawPc50), if (!is.null(names(par))) maxAsymptote), par) + } + } ## hillSlope1 and inflectionPoint1 are fixed at 1, not fitted -- see fixLogisticPars() for why. - list(par = fixLogisticPars(par), yearSpreadSD = sds[["yearSpreadSD"]], fireSpreadSD = sds[["fireSpreadSD"]]) + list(par = fixLogisticPars(par), yearSpreadSD = sds[["yearSpreadSD"]], fireSpreadSD = sds[["fireSpreadSD"]], + activationIntercept = activationIntercept) } #' The observed fires of each year, at or above `minFireSize`, one row per cell; years left with none @@ -342,7 +406,9 @@ effectiveMinFireSize <- function(minFireSize, escapeMinPx) { #' @param annualDTx1000,nonAnnualDTx1000,historicalFires,covMinMax,mutuallyExclusive,covCentre,link,climateRef,maxFireSpread,lowerSpreadProb,lanscape1stQuantileThresh,minFireSize,escapeSizeHa,landscape #' As in [.objfunSpreadFit()] (`landscape` is needed only with `escapeSizeHa`). With `climateRef` the gates #' test the spread probability at the reference climate, as the objective does ([spreadProbFromCovs()]). -#' @param powerLawGamma,powerLawShape,lowerAsymptote,richardsNu,powerLawPc50 As in [.objfunSpreadFit()]. +#' @param powerLawGamma,powerLawShape,lowerAsymptote,richardsNu,powerLawPc50 As in [.objfunSpreadFit()]. A `par` with +#' `activationIntercept` ([activationInterceptTxt]) is a set of `spreadClimate = "activation"`, gated on `p`. +#' @param pcAtP50 As in [.objfunSpreadFit()]. #' @param formulaToFit character; the spread formula, as in the objective. #' @param years character; the years to test. Default: the objective's first block. #' @param doAssertions logical; as in the objective. @@ -357,7 +423,7 @@ spreadProbGates <- function(par, annualDTx1000, nonAnnualDTx1000, historicalFire landscape = NULL, years = NULL, doAssertions = FALSE, climateRef = NULL, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, - powerLawPc50 = NULL) { + powerLawPc50 = NULL, pcAtP50 = NULL) { data.table::setDTthreads(1) formulaToFit <- as.formula(formulaToFit, env = .GlobalEnv) colsToUse <- spreadDesignCols(formulaToFit) @@ -372,21 +438,23 @@ spreadProbGates <- function(par, annualDTx1000, nonAnnualDTx1000, historicalFire indexNonAnnual <- nonAnnualIndex(nonAnnualDTx1000) single <- !is.list(par) pars <- if (single) list(par) else par - pars <- lapply(pars, function(p) splitSpreadPar(p)$par) - firstLogistic <- paramsSeparate(pars[[1]], parsModel) + pars <- lapply(pars, splitSpreadPar, powerLawPc50 = powerLawPc50, pcAtP50 = pcAtP50) + firstLogistic <- paramsSeparate(pars[[1]]$par, parsModel) ## covariates do not depend on par: prepare each year once covs <- lapply(years, function(yr) as.matrix( spreadProbCovsOfYear(yr, annualDTx1000[[yr]], nonAnnualDTx1000, indexNonAnnual, covMinMax, mutuallyExclusive, colsToUse, doAssertions, firstLogistic$logisticPars, firstLogistic$covPars, maxFireSpread, lowerSpreadProb, covCentre = covCentre)[, ..colsToUse])) - res <- lapply(pars, function(p) { - ps <- paramsSeparate(p, parsModel) + res <- lapply(pars, function(sp) { + ps <- paramsSeparate(sp$par, parsModel) + ## as the objective: p at the reference climate, except with the activation, whose climate moves every pixel + ## below its own ceiling, never past p50: the gates see p g <- lapply(covs, function(cv) spreadProbGateTest(spreadProbFromCovs(cv, ps$logisticPars, ps$covPars, lowerSpreadProb, link, - climateRef = climateRef, climateAtRef = TRUE, + climateRef = climateRef, climateAtRef = is.null(sp$activationIntercept), powerLawGamma = powerLawGamma, powerLawShape = powerLawShape, lowerAsymptote = lowerAsymptote, richardsNu = richardsNu, - powerLawPc50 = powerLawPc50), + powerLawPc50 = powerLawPc50, activationIntercept = sp$activationIntercept), ps$logisticPars[1], spreadLinkLower(link, lowerSpreadProb, lowerAsymptote), maxFireSpread, lanscape1stQuantileThresh, spreadOut = spreadHasCovariates(colsToUse))) list(pass = all(vapply(g, `[[`, logical(1), "pass")), @@ -399,3 +467,24 @@ spreadProbGates <- function(par, annualDTx1000, nonAnnualDTx1000, historicalFire notSpread = vapply(res, `[[`, logical(1), "notSpread"), medianOK = vapply(res, `[[`, logical(1), "medianOK")) } + +#' The share of dud years of a `spreadClimate = "activation"` fit +#' +#' With the activation, `x = activationIntercept + climate term + eps_Y`, and with the `"powerLawSmooth"` link at the +#' floor every pixel is at the floor when `x < 0`. At the reference climate a year is such a "dud" when its draw +#' `eps_Y ~ N(0, yearSpreadSD^2)` is below `-activationIntercept`: a share `pnorm(-activationIntercept / yearSpreadSD)`. +#' A large share means the year effect acts as an on/off switch (Fable review H1); `fireSense_spreadFit` stores it in +#' the ledger row ([spreadFitDudYearShareTxt]) and reports it, so a fit can be judged on it. +#' +#' @param params A `data.frame` or named numeric vector of parameter sets, with `activationIntercept` +#' ([activationInterceptTxt]) and, if the year effect was fitted, `yearSpreadSD`. +#' @return A numeric vector, one per set: 0 without a year effect (or with sd 0) and a non-negative intercept, 1 with a +#' negative one. +#' @export +activationDudYearShare <- function(params) { + p <- as.list(params) + a <- p[[activationInterceptTxt]] + if (is.null(a)) stop("activationDudYearShare(): `params` has no '", activationInterceptTxt, "'", call. = FALSE) + sd <- if (is.null(p[[yearSpreadSDTxt]])) rep(0, length(a)) else p[[yearSpreadSDTxt]] + ifelse(sd > 0, stats::pnorm(-a / sd), as.numeric(a < 0)) +} diff --git a/man/activationDudYearShare.Rd b/man/activationDudYearShare.Rd new file mode 100644 index 0000000..6ffe58b --- /dev/null +++ b/man/activationDudYearShare.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/spreadProbGates.R +\name{activationDudYearShare} +\alias{activationDudYearShare} +\title{The share of dud years of a \code{spreadClimate = "activation"} fit} +\usage{ +activationDudYearShare(params) +} +\arguments{ +\item{params}{A \code{data.frame} or named numeric vector of parameter sets, with \code{activationIntercept} +(\link{activationInterceptTxt}) and, if the year effect was fitted, \code{yearSpreadSD}.} +} +\value{ +A numeric vector, one per set: 0 without a year effect (or with sd 0) and a non-negative intercept, 1 with a +negative one. +} +\description{ +With the activation, \verb{x = activationIntercept + climate term + eps_Y}, and with the \code{"powerLawSmooth"} link at the +floor every pixel is at the floor when \code{x < 0}. At the reference climate a year is such a "dud" when its draw +\code{eps_Y ~ N(0, yearSpreadSD^2)} is below \code{-activationIntercept}: a share \code{pnorm(-activationIntercept / yearSpreadSD)}. +A large share means the year effect acts as an on/off switch (Fable review H1); \code{fireSense_spreadFit} stores it in +the ledger row (\link{spreadFitDudYearShareTxt}) and reports it, so a fit can be judged on it. +} diff --git a/man/checkLinkParams.Rd b/man/checkLinkParams.Rd index 5eae6f4..db95081 100644 --- a/man/checkLinkParams.Rd +++ b/man/checkLinkParams.Rd @@ -4,12 +4,22 @@ \alias{checkLinkParams} \title{Check the parameters of the links with a lower asymptote} \usage{ -checkLinkParams(link, lower = NULL, nu = NULL) +checkLinkParams( + link, + lower = NULL, + nu = NULL, + activation = FALSE, + floor = spreadProbFloor +) } \arguments{ \item{link}{The spread link.} \item{lower, nu}{The \code{lowerAsymptote} and \code{richardsNu} to check; \code{NULL} is not a number.} + +\item{activation}{Logical; \code{TRUE} for a fit or a ledger row with \code{spreadClimate = "activation"}.} + +\item{floor}{The \code{lowerSpreadProb} the activation's \code{lower} must equal; default \link{spreadProbFloor}.} } \value{ \code{TRUE}, invisibly; an error otherwise. @@ -19,3 +29,8 @@ The one check of \code{lowerAsymptote} and \code{richardsNu}, used by \code{fire \code{fireSense_spreadPredict} for a ledger row. \code{lower} must be one number from \link{spreadLowerAsymptoteMin} to \link{spreadProbFloor} with \code{"powerLawSmooth"} and \code{"richards"}; \code{nu} one number, 0 or more, with \code{"richards"}. Other links have nothing to check. } +\details{ +With \code{activation} (\code{spreadClimate = "activation"}, \code{\link[=spreadLinkInputs]{spreadLinkInputs()}}) the link must be \code{"powerLawSmooth"} with +\code{lower} equal to \code{floor}: below the floor the other forms fall faster for a higher \code{pc}, and with the activation \code{pc} +is set by fuel, so a wet year would rank rich fuel below poor. +} diff --git a/man/dot-objfunSpreadFit.Rd b/man/dot-objfunSpreadFit.Rd index 5468cc9..d937333 100644 --- a/man/dot-objfunSpreadFit.Rd +++ b/man/dot-objfunSpreadFit.Rd @@ -50,6 +50,8 @@ runawayBufferMultiple = NULL, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL, + fitActivationIntercept = NULL, + pcAtP50 = NULL, verbose = 2, crpsWeights = NULL, gateRefusal = c("minLik", "simulate"), @@ -60,7 +62,8 @@ \arguments{ \item{par}{parameters: the logistic parameters (\code{maxAsymptote} first, then \code{upperTail1} if the link has one; without \code{hillSlope1} and \code{inflectionPoint1}, which are fixed at 1 -- see \code{fixLogisticPars()}), then the covariate coefficients (the intercept's first, when -the formula has one -- see \code{\link[=spreadDesignCols]{spreadDesignCols()}}), and optionally +the formula has one -- see \code{\link[=spreadDesignCols]{spreadDesignCols()}}), then \code{activationIntercept} with \code{fitActivationIntercept} (which has no +\code{maxAsymptote}), and optionally \code{fireSpreadSD} (see \code{fitFireSpreadSD}) and \code{yearSpreadSD} last (see \code{fitYearSpreadSD}), in that order.} \item{landscape}{A \code{SpatRaster} with extent, resolution, and projection (crs) used for @@ -202,7 +205,7 @@ instead: it moves \code{pc} toward \code{powerLawPc50}, never past it (\code{\li \item{powerLawPc50}{\code{NULL} (default), or the landscape's runaway threshold (\code{\link[=calibratePowerLaw]{calibratePowerLaw()}}). With \code{climateRef} and a power-law link it puts climate in the ceiling; needed then. The year effect and the per-fire effect stay on the -fuel linear predictor. Ignored without \code{climateRef}.} +fuel linear predictor. Without \code{climateRef} it is used only as the fixed \code{maxAsymptote} of \code{pcAtP50}.} \item{powerLawGamma}{The \code{"powerLaw"} and \code{"powerLawSmooth"} links' \code{gamma} (\code{\link[=powerLawLink]{powerLawLink()}}), fixed, not fitted; used only with those links.} @@ -266,6 +269,18 @@ the year's draw), so fires of one year can differ in how readily they spread. On the objective is exactly the one without it. \code{NULL} (default): \code{TRUE} when \code{par} is named and includes \code{fireSpreadSD}. DEoptim passes \code{par} unnamed, so \code{runDEoptim()} sets it explicitly.} +\item{fitActivationIntercept}{If \code{TRUE}, \code{spreadClimate = "activation"} (\code{\link[=spreadLinkInputs]{spreadLinkInputs()}}): the element of \code{par} +right before the random-effect sds is \code{activationIntercept} (\link{activationInterceptTxt}), the linear predictor at the +reference climate, and \code{maxAsymptote} is not in \code{par} (it is \code{powerLawPc50}, \code{\link[=splitSpreadPar]{splitSpreadPar()}}). Fuel then sets each +pixel's ceiling and climate, with the year and fire effects, is the linear predictor; the gates and the saturation +summary look at \code{p}. Needs \code{climateRef}, \code{powerLawPc50} and \code{link = "powerLawSmooth"} with +\code{lowerAsymptote = lowerSpreadProb}. \code{NULL} (default): \code{TRUE} when \code{par} is named and has \code{activationIntercept}. +DEoptim passes \code{par} unnamed, so \code{runDEoptim()} sets it explicitly (\code{\link[=spreadRandomEffectArgs]{spreadRandomEffectArgs()}}).} + +\item{pcAtP50}{\code{NULL} (default) or \code{TRUE}: \code{maxAsymptote} (p_c of a power-law \code{link}) is not fitted and not in +\code{par}; it is \code{powerLawPc50} (\code{fireSense_spreadFit}'s \code{powerLawPcAtP50}, \code{\link[=splitSpreadPar]{splitSpreadPar()}}). A named \code{par} that has +\code{maxAsymptote} (a ledger row's) keeps it. The activation (\code{fitActivationIntercept}) implies it.} + \item{verbose}{If >= 2, then this will show more information about \code{spreadProb} fitting.} \item{crpsWeights}{Named list of the multipliers of the \code{"crps"} test's terms, \code{fire}, \code{adTest}, \code{areaDist}, diff --git a/man/fireSenseUtils-constants.Rd b/man/fireSenseUtils-constants.Rd index fb048c9..dbb8108 100644 --- a/man/fireSenseUtils-constants.Rd +++ b/man/fireSenseUtils-constants.Rd @@ -40,6 +40,12 @@ \alias{spreadFitPowerLawPcMarginTxt} \alias{spreadFitInSampleSizesTxt} \alias{spreadPowerLawPGrid} +\alias{spreadClimateTxt} +\alias{spreadClimateOptions} +\alias{activationInterceptTxt} +\alias{spreadActivationInterceptBounds} +\alias{spreadFitDudYearShareTxt} +\alias{spreadFitPcAtP50Txt} \alias{yearSpreadSDTxt} \alias{fireSpreadSDTxt} \alias{spreadRandomEffectTxt} @@ -132,6 +138,22 @@ validation (\code{"inSampleSizes_spread"}): a list of \code{sizes}, the one-row \code{\link[=scoreFireSizesByYear]{scoreFireSizesByYear()}}; areas are in pixels. A fit without the diagnostics (a cross-validation fold, \code{simulateMembers = 0}) writes no such column, and a row written before it has none. \item \code{spreadPowerLawPGrid}: \code{numeric}. The spread probabilities \code{\link[=calibratePowerLaw]{calibratePowerLaw()}} simulates by default. +\item \code{spreadClimateTxt}: \code{character(1)}. Name of the ledger column that holds where a fit put climate +(\code{"spreadClimate"}): one of \code{spreadClimateOptions}. A row without it (written before it existed) is +\code{"ceiling"} when it has \code{"climateRef_spread"} and a power-law \code{"spreadLink"}, else \code{"predictor"}. +\item \code{spreadClimateOptions}: \code{character}. The values of \code{fireSense_spreadFit}'s \code{spreadClimate}: \code{"predictor"} +(climate in the linear predictor with the fuels), \code{"ceiling"} (climate moves the power-law ceiling, +\code{\link[=spreadLinkInputs]{spreadLinkInputs()}}) and \code{"activation"} (fuel sets each pixel's ceiling, climate is the linear predictor). +\item \code{activationInterceptTxt}: \code{character(1)}. Name of the parameter of \code{spreadClimate = "activation"} that is +the linear predictor at the reference climate (\code{"activationIntercept"}); in \code{lower}/\code{upper} and in a ledger +row's \code{params} it comes right after the covariate coefficients, before the random-effect sds. +\item \code{spreadActivationInterceptBounds}: \code{numeric(2)}. Its default bounds, \code{c(-10, 10)}. +\item \code{spreadFitDudYearShareTxt}: \code{character(1)}. Name of the ledger column of an \code{"activation"} fit with the share of +years whose draw of the year effect puts every pixel at the floor at the reference climate, one per parameter set +(\code{\link[=activationDudYearShare]{activationDudYearShare()}}; \code{"dudYearShare_spread"}). +\item \code{spreadFitPcAtP50Txt}: \code{character(1)}. Name of the ledger column that marks a fit whose \code{maxAsymptote} was fixed at +p50, not fitted (\code{fireSense_spreadFit}'s \code{powerLawPcAtP50}; \code{"pcAtP50_spread"}), so its value is not read as a +fitted one at its bound. \item \code{treedWetlandAgbTxt}: \code{character(1)}. Name of the pooled treed-wetland biomass column built by \code{fireSenseCovariatesCreate(fuelCovariates = "domSecWetland")} (currently \code{"treedWetland_agb"}). diff --git a/man/runDEoptim.Rd b/man/runDEoptim.Rd index b61bf83..509c443 100644 --- a/man/runDEoptim.Rd +++ b/man/runDEoptim.Rd @@ -67,6 +67,7 @@ runDEoptim( convergence = NULL, climateRef = NULL, powerLawPc50 = NULL, + pcAtP50 = NULL, powerLawGamma = spreadPowerLawGamma, powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, @@ -144,7 +145,9 @@ Passed to \link[DEoptim:DEoptim]{DEoptim::DEoptim}. If named and including \code{yearSpreadSD} (which must be last), the per-year random effect (a seasonal departure) of \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}} (\code{fitYearSpreadSD}) is fitted, in the fit and in the re-score. Likewise \code{fireSpreadSD}, the per-fire random effect (\code{fitFireSpreadSD}; needs \code{wholeLandscape = TRUE}), which comes just before -\code{yearSpreadSD}, or last without it. A fit without \code{fireSpreadSD} keeps its cache keys.} +\code{yearSpreadSD}, or last without it. A fit without \code{fireSpreadSD} keeps its cache keys. With \code{activationIntercept} +(\link{activationInterceptTxt}), right before them and without \code{maxAsymptote}, the fit is \code{spreadClimate = "activation"} +(\code{fitActivationIntercept} of \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}}); it needs \code{climateRef} and \code{powerLawPc50}.} \item{upper}{Numeric vector. Upper bounds for the parameters being optimized. Passed to \link[DEoptim:DEoptim]{DEoptim::DEoptim}.} @@ -263,6 +266,9 @@ key are what they were; a named numeric (\code{\link[=spreadClimateRef]{spreadCl threshold (\code{\link[=calibratePowerLaw]{calibratePowerLaw()}}), which with a power-law \code{link} puts climate in the ceiling (\code{\link[=spreadLinkInputs]{spreadLinkInputs()}}). \code{NULL} leaves the call and its cache key as they were.} +\item{pcAtP50}{Passed to \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}} like \code{powerLawPc50}: \code{TRUE} when \code{lower} has no \code{maxAsymptote} because +p_c is fixed at \code{powerLawPc50}. \code{NULL} (default) leaves the call and its cache key as they were.} + \item{powerLawGamma}{The \code{"powerLaw"} and \code{"powerLawSmooth"} links' \code{gamma} (\code{\link[=powerLawLink]{powerLawLink()}}), passed to \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}} in the fit and the re-score. Used only with those links; with any other link it is left out of the cache keys (\code{\link[=powerLawOmitArgs]{powerLawOmitArgs()}}) and the re-score's arguments, so they are what they were.} diff --git a/man/splitSpreadPar.Rd b/man/splitSpreadPar.Rd index 29451fb..9c7a759 100644 --- a/man/splitSpreadPar.Rd +++ b/man/splitSpreadPar.Rd @@ -5,10 +5,30 @@ \title{Split \code{par} as the objective does: drop the trailing random-effect sds (\code{fireSpreadSD}, then \code{yearSpreadSD}) and insert the fixed \code{hillSlope1} and \code{inflectionPoint1}} \usage{ -splitSpreadPar(par, fitYearSpreadSD = NULL, fitFireSpreadSD = NULL) +splitSpreadPar( + par, + fitYearSpreadSD = NULL, + fitFireSpreadSD = NULL, + fitActivationIntercept = NULL, + powerLawPc50 = NULL, + pcAtP50 = NULL +) +} +\arguments{ +\item{fitActivationIntercept}{\code{NULL} (default): \code{TRUE} when \code{par} is named and has \code{activationIntercept}.} + +\item{pcAtP50}{\code{NULL} or \code{FALSE} (default): \code{maxAsymptote} is in \code{par}, unless \code{fitActivationIntercept}. \code{TRUE}: it is +not, and \code{powerLawPc50} takes its place.} +} +\value{ +A list: \code{par}, \code{yearSpreadSD}, \code{fireSpreadSD} and \code{activationIntercept} (\code{NULL} without it). } \description{ -Split \code{par} as the objective does: drop the trailing random-effect sds (\code{fireSpreadSD}, then \code{yearSpreadSD}) and -insert the fixed \code{hillSlope1} and \code{inflectionPoint1} +With \code{fitActivationIntercept} (\code{spreadClimate = "activation"}) the parameter before the sds is +\code{activationIntercept} (\link{activationInterceptTxt}), taken out too, and \code{maxAsymptote} is not fitted: \code{powerLawPc50} is +put first unless a named \code{par} has \code{maxAsymptote} (a ledger row's, written with it). It is the ceiling of every +pixel's \code{p} in that mode, so whatever reads \code{logisticPars[1]} as the ceiling (the gates, the saturation summary) +reads \code{p50}. With \code{pcAtP50} (\code{fireSense_spreadFit}'s \code{powerLawPcAtP50}) \code{maxAsymptote} is not fitted either, and is +\code{powerLawPc50} in the same way. } \keyword{internal} diff --git a/man/spreadFitValidation.Rd b/man/spreadFitValidation.Rd index cb49a65..e4368e9 100644 --- a/man/spreadFitValidation.Rd +++ b/man/spreadFitValidation.Rd @@ -31,6 +31,8 @@ spreadFitValidationData( richardsNu = spreadRichardsNu, seed = NULL, powerLawPc50 = NULL, + fitActivationIntercept = NULL, + pcAtP50 = NULL, ... ) @@ -156,7 +158,19 @@ stream is restored afterwards.} \item{powerLawPc50}{\code{NULL} (default), or the landscape's runaway threshold (\code{\link[=calibratePowerLaw]{calibratePowerLaw()}}). With \code{climateRef} and a power-law link it puts climate in the ceiling; needed then. The year effect and the per-fire effect stay on the -fuel linear predictor. Ignored without \code{climateRef}.} +fuel linear predictor. Without \code{climateRef} it is used only as the fixed \code{maxAsymptote} of \code{pcAtP50}.} + +\item{fitActivationIntercept}{If \code{TRUE}, \code{spreadClimate = "activation"} (\code{\link[=spreadLinkInputs]{spreadLinkInputs()}}): the element of \code{par} +right before the random-effect sds is \code{activationIntercept} (\link{activationInterceptTxt}), the linear predictor at the +reference climate, and \code{maxAsymptote} is not in \code{par} (it is \code{powerLawPc50}, \code{\link[=splitSpreadPar]{splitSpreadPar()}}). Fuel then sets each +pixel's ceiling and climate, with the year and fire effects, is the linear predictor; the gates and the saturation +summary look at \code{p}. Needs \code{climateRef}, \code{powerLawPc50} and \code{link = "powerLawSmooth"} with +\code{lowerAsymptote = lowerSpreadProb}. \code{NULL} (default): \code{TRUE} when \code{par} is named and has \code{activationIntercept}. +DEoptim passes \code{par} unnamed, so \code{runDEoptim()} sets it explicitly (\code{\link[=spreadRandomEffectArgs]{spreadRandomEffectArgs()}}).} + +\item{pcAtP50}{\code{NULL} (default) or \code{TRUE}: \code{maxAsymptote} (p_c of a power-law \code{link}) is not fitted and not in +\code{par}; it is \code{powerLawPc50} (\code{fireSense_spreadFit}'s \code{powerLawPcAtP50}, \code{\link[=splitSpreadPar]{splitSpreadPar()}}). A named \code{par} that has +\code{maxAsymptote} (a ledger row's) keeps it. The activation (\code{fitActivationIntercept}) implies it.} \item{...}{Further arguments to \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}}, e.g. \code{escapeSizeHa}, \code{jumpTries}, \code{jumpMeanDist}: give it what the fit was given. The objective's gates on implausible @@ -180,7 +194,7 @@ of the fire year), \code{pixelID}, \code{observed} (1 if the pixel is inside an probability, without the per-year random effect), and one column per covariate of the formula with its raw value (the stored integer / 1000, before rescaling and mutual exclusivity). \code{attr(, "spreadFitValidation")} holds what the plots need: the parameters, \code{covMinMax}, -\code{covCentre}, \code{lowerSpreadProb}, \code{link}, \code{climateRef}, \code{powerLawPc50}, \code{powerLawGamma}, \code{powerLawShape}, \code{lowerAsymptote}, \code{richardsNu}, \code{Nreps}, the names of the covariates and of the +\code{covCentre}, \code{lowerSpreadProb}, \code{link}, \code{climateRef}, \code{powerLawPc50}, \code{activationIntercept}, \code{powerLawGamma}, \code{powerLawShape}, \code{lowerAsymptote}, \code{richardsNu}, \code{Nreps}, the names of the covariates and of the annual (climate) ones, and \code{yearsNotSimulated} -- years the objective declined to simulate, which have no rows. diff --git a/man/spreadLinkInputs.Rd b/man/spreadLinkInputs.Rd index 4e20561..32388d9 100644 --- a/man/spreadLinkInputs.Rd +++ b/man/spreadLinkInputs.Rd @@ -16,7 +16,8 @@ spreadLinkInputs( powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, - climateAtRef = FALSE + climateAtRef = FALSE, + activationIntercept = NULL ) } \arguments{ @@ -40,7 +41,9 @@ scale of \code{mat} (\code{\link[=spreadClimateRef]{spreadClimateRef()}}). Every \code{"richards"} (\code{\link[=logisticAll]{logisticAll()}}); used only with those links.} \item{climateAtRef}{Logical. With \code{climateRef}, \code{TRUE} returns the inputs at the reference climate: \code{x} of the -non-climate columns and the vector \code{pars} with \code{pc = pc0}.} +non-climate columns and the vector \code{pars} with \code{pc = pc0}; with \code{activationIntercept}, \code{x = activationIntercept}.} + +\item{activationIntercept}{\code{NULL} (default), or the fitted \code{x} at the reference climate of \code{spreadClimate = "activation"} (\link{activationInterceptTxt}); needs \code{climateRef}.} } \value{ A list: \code{x}, a numeric vector, one per row of \code{mat}; \code{pars}, a named vector as \code{\link[=linearLinkPars]{linearLinkPars()}} gives, or with @@ -57,5 +60,14 @@ With \code{climateRef} (climate in the ceiling; \code{spreadClimate = "ceiling"} \code{powerLawPc50} (\code{\link[=calibratePowerLaw]{calibratePowerLaw()}}), never past it. With \code{shift = sum(beta_clim * (climate - climateRef))} over the climate columns of \code{mat}, \code{pc = max(p50 - (p50 - pc0) * exp(-shift), lowerSpreadProb)} and \code{x} is the linear predictor of every other column. At the reference climate \code{pc = pc0 = logisticPars[1]}; \code{log(p50 - pc)} is linear in -climate, so log mean fire size is too. \code{pars} is then a matrix, one row per row of \code{mat}. +climate. \code{pars} is then a matrix, one row per row of \code{mat}. + +With \code{activationIntercept} as well (\code{spreadClimate = "activation"} in \code{fireSense_spreadFit}) the roles are swapped: +fuel sets each pixel's own ceiling and climate is the linear predictor. With \code{eta} the linear predictor of the +non-climate columns (the intercept, fuels, youngAge, non-forest, ...) and \code{f} = \code{lowerSpreadProb}, +\code{pc = f + (p50 - f) * plogis(eta)}, so \code{pc <= p50}, and \code{x = activationIntercept + shift}. \code{pc0} is not used +(\code{logisticPars[1]}, which the objective sets to \code{p50}, \code{\link[=splitSpreadPar]{splitSpreadPar()}}). Above the floor every pixel's +\code{p - f = (pc - f) * (1 - exp(-(x / gamma)^shape))}, so the ratio of \code{p - f} between two pixels of a year is the ratio of +their \code{plogis(eta)}, whatever the climate. It needs \code{"powerLawSmooth"} with \code{lowerAsymptote = lowerSpreadProb} +(\code{\link[=checkLinkParams]{checkLinkParams()}}). } diff --git a/man/spreadProbFromCovs.Rd b/man/spreadProbFromCovs.Rd index 8c38799..41e5465 100644 --- a/man/spreadProbFromCovs.Rd +++ b/man/spreadProbFromCovs.Rd @@ -16,7 +16,8 @@ spreadProbFromCovs( powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, - powerLawPc50 = NULL + powerLawPc50 = NULL, + activationIntercept = NULL ) } \arguments{ @@ -43,6 +44,10 @@ and a gate on \code{p} would refuse the years that carry the climate signal. Ign \item{powerLawPc50}{The landscape's runaway threshold (\code{\link[=calibratePowerLaw]{calibratePowerLaw()}}); with \code{climateRef} and a power-law link it puts climate in the ceiling (\code{\link[=spreadLinkInputs]{spreadLinkInputs()}}). Needed then, ignored otherwise.} + +\item{activationIntercept}{\code{NULL} (default), or with \code{climateRef}, \code{powerLawPc50} and \code{link = "powerLawSmooth"} the +fitted intercept of \code{spreadClimate = "activation"}: fuel sets each pixel's ceiling and climate is the linear +predictor (\code{\link[=spreadLinkInputs]{spreadLinkInputs()}}).} } \value{ A one-column numeric matrix, one value per row of \code{mat} (as \code{\link[=logisticAll]{logisticAll()}}). diff --git a/man/spreadProbGates.Rd b/man/spreadProbGates.Rd index 0444573..854775f 100644 --- a/man/spreadProbGates.Rd +++ b/man/spreadProbGates.Rd @@ -27,7 +27,8 @@ spreadProbGates( powerLawShape = spreadPowerLawShape, lowerAsymptote = spreadProbFloor, richardsNu = spreadRichardsNu, - powerLawPc50 = NULL + powerLawPc50 = NULL, + pcAtP50 = NULL ) } \arguments{ @@ -43,7 +44,10 @@ test the spread probability at the reference climate, as the objective does (\co \item{doAssertions}{logical; as in the objective.} -\item{powerLawGamma, powerLawShape, lowerAsymptote, richardsNu, powerLawPc50}{As in \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}}.} +\item{powerLawGamma, powerLawShape, lowerAsymptote, richardsNu, powerLawPc50}{As in \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}}. A \code{par} with +\code{activationIntercept} (\link{activationInterceptTxt}) is a set of \code{spreadClimate = "activation"}, gated on \code{p}.} + +\item{pcAtP50}{As in \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}}.} } \value{ for one \code{par}, a list of logicals \code{pass} (every tested year passes), \code{burny} and \code{notSpread} diff --git a/man/spreadRandomEffectArgs.Rd b/man/spreadRandomEffectArgs.Rd index 768078e..dd2751e 100644 --- a/man/spreadRandomEffectArgs.Rd +++ b/man/spreadRandomEffectArgs.Rd @@ -9,12 +9,16 @@ spreadRandomEffectArgs(lower, wholeLandscape = FALSE) \arguments{ \item{lower}{Named lower bounds of the fit, as \code{runDEoptim(lower = )}.} -\item{wholeLandscape}{As in \code{runDEoptim()}: \code{fireSpreadSD} needs \code{TRUE} (an error otherwise).} +\item{wholeLandscape}{As in \code{runDEoptim()}: \code{fireSpreadSD} needs \code{TRUE} (an error otherwise). + +The same holds for \code{activationIntercept} (\link{activationInterceptTxt}, \code{spreadClimate = "activation"}), which must come +right before them.} } \value{ A list of \code{\link[=.objfunSpreadFit]{.objfunSpreadFit()}} arguments: \code{fitYearSpreadSD} (logical) and, only when \code{lower} has -\code{fireSpreadSD}, \code{fitFireSpreadSD = TRUE}. A fit without the per-fire effect does not get that argument, so its -cache keys are those it had before the effect existed. +\code{fireSpreadSD}, \code{fitFireSpreadSD = TRUE}, and only when it has \code{activationIntercept}, \code{fitActivationIntercept = TRUE}. +A fit without the per-fire effect (or the activation) does not get that argument, so its cache keys are those it had +before the argument existed. } \description{ A spread fit fits a random effect when its bounds name it: \code{fireSpreadSD} and \code{yearSpreadSD} diff --git a/tests/testthat/test-climateActivation.R b/tests/testthat/test-climateActivation.R new file mode 100644 index 0000000..e3f879f --- /dev/null +++ b/tests/testthat/test-climateActivation.R @@ -0,0 +1,331 @@ +## spreadClimate = "activation" (spreadLinkInputs(activationIntercept =)): fuel sets each pixel's own ceiling, +## pc_i = f + (p50 - f) * plogis(eta_i), eta_i the linear predictor of the non-climate columns, and climate is the +## linear predictor, x_i = a + sum(beta_clim * (clim - climateRef)); p_i = powerLawSmooth(x_i; pc_i), lower = floor. +## Fixture: helper-spreadLinkFixture.R (f = 0.13, lp3, matOf(), climFix, spreadProbSeenC()). + +p50 <- 0.3 +a <- 1.2 +b <- c(clim = 1.5, fuel = 3, youngAge = -1) +ref <- list(clim = 0.3) +gam <- 1.9 +shp <- 0.5 +actInputs <- function(mat, ...) spreadLinkInputs(mat, lp3, b, f, "powerLawSmooth", ref, p50, powerLawGamma = gam, + powerLawShape = shp, lowerAsymptote = f, activationIntercept = a, ...) + +test_that("p of each pixel is the formula: pc_i from the fuel terms, x_i from climate and the activation intercept", { + mat <- matOf("2005") + inputs <- actInputs(mat) + eta <- unname(mat[, "fuel"] * b[["fuel"]] + mat[, "youngAge"] * b[["youngAge"]]) + pc <- f + (p50 - f) * plogis(eta) + x <- unname(a + b[["clim"]] * (mat[, "clim"] - ref$clim)) + expect_equal(unname(inputs$pars[, "pc"]), pc) + expect_equal(inputs$x, x) + expect_true(all(inputs$pars[, "floor"] == f) && all(inputs$pars[, "lower"] == f)) + expect_true(all(inputs$pars[, "gamma"] == gam) && all(inputs$pars[, "shape"] == shp)) + ## by hand: the power law above the floor, the floor below it (lower = floor) + byHand <- ifelse(x >= 0, pc - (pc - f) * exp(-(pmax(x, 0) / gam)^shp), f) + p <- spreadProbFromCovs(mat, lp3, b, f, link = "powerLawSmooth", climateRef = ref, powerLawPc50 = p50, + powerLawGamma = gam, powerLawShape = shp, lowerAsymptote = f, activationIntercept = a) + expect_equal(as.numeric(p), byHand) + expect_identical(as.numeric(p), linearLinkProb(inputs$x, "powerLawSmooth", inputs$pars)) + ## pc0 (logisticPars[1]) plays no part + expect_identical(spreadLinkInputs(mat, c(0.2, 1, 1), b, f, "powerLawSmooth", ref, p50, powerLawGamma = gam, + powerLawShape = shp, lowerAsymptote = f, activationIntercept = a)$x, inputs$x) + ## at the reference climate x is the activation intercept + expect_equal(actInputs(mat, climateAtRef = TRUE)$x, rep(a, nrow(mat))) +}) + +test_that("the ratio of p - floor between two pixels does not change with climate", { + mat <- matOf("2004")[1:6, ] + mat[, "fuel"] <- c(0.05, 0.1, 0.2, 0.4, 0.6, 0.9) + mat[, "youngAge"] <- 0 + ratios <- sapply(c(0.35, 0.6, 1, 2, 4), function(clim) { + m <- mat; m[, "clim"] <- clim + p <- as.numeric(linearLinkProb(actInputs(m)$x, "powerLawSmooth", actInputs(m)$pars)) + expect_true(all(p < actInputs(m)$pars[, "pc"])) # p is still below every pixel's ceiling + (p - f) / (p[1] - f) + }) + for (i in seq_len(nrow(ratios))) expect_equal(ratios[i, ], rep(ratios[i, 1], ncol(ratios))) + ## and it is the ratio of the fuel potentials + expect_equal(ratios[, 1], plogis(3 * mat[, "fuel"]) / plogis(3 * mat[1, "fuel"]), ignore_attr = TRUE) +}) + +test_that("p never exceeds p50, whatever the fuel and the climate", { + mat <- matOf("2005") + for (clim in c(-50, -1, 0.3, 2, 50, 1e3)) for (fuelBy in c(-100, 0, 1, 100)) { + m <- mat; m[, "clim"] <- clim; m[, "fuel"] <- m[, "fuel"] * fuelBy + inputs <- actInputs(m) + expect_true(all(inputs$pars[, "pc"] <= p50)) + p <- linearLinkProb(inputs$x, "powerLawSmooth", inputs$pars) + expect_lte(max(p), p50) + expect_gte(min(p), f) + } +}) + +test_that("rows with no climate or no fuel cannot burn", { + mat <- matOf("2005") + mat[3, "clim"] <- NA + mat[7, "fuel"] <- NA + inputs <- actInputs(mat) + expect_false(anyNA(inputs$pars)) + expect_true(all(is.na(inputs$x[c(3, 7)]))) + expect_false(anyNA(inputs$x[-c(3, 7)])) + expect_identical(inputs$pars[c(3, 7), , drop = FALSE], unburnableLinkPars("powerLawSmooth", 2L)) + expect_true(all(is.na(spreadProbFromCovs(mat, lp3, b, f, link = "powerLawSmooth", climateRef = ref, powerLawPc50 = p50, + lowerAsymptote = f, activationIntercept = a)[c(3, 7)]))) +}) + +test_that("the activation stops without what it needs", { + mat <- matOf("2004") + call <- function(...) { + args <- utils::modifyList(list(mat = mat, logisticPars = lp3, covPars = b, lowerSpreadProb = f, link = "powerLawSmooth", + climateRef = ref, powerLawPc50 = p50, lowerAsymptote = f, activationIntercept = a), + list(...)) + do.call(spreadLinkInputs, args) + } + expect_error(call(climateRef = NULL), "needs `climateRef`") + expect_error(call(powerLawPc50 = NA_real_), "powerLawPc50") + expect_error(call(link = "powerLaw"), "powerLawSmooth") + expect_error(call(link = "richards"), "power-law link") + expect_error(call(lowerAsymptote = 0.05), "lowerAsymptote = lowerSpreadProb") + expect_error(call(activationIntercept = NA_real_), "one finite number") + ## a logistic link cannot take it either + expect_error(spreadProbFromCovs(mat, lp3, b, f, link = NULL, climateRef = ref, powerLawPc50 = p50, + activationIntercept = a), "must be one of") + ## the same check the module makes of its parameters and of a ledger row + expect_true(checkLinkParams("powerLawSmooth", f, activation = TRUE, floor = f)) + expect_error(checkLinkParams("powerLawSmooth", 0.05, activation = TRUE), "lowerAsymptote = lowerSpreadProb") + expect_error(checkLinkParams("powerLaw", f, activation = TRUE, floor = f), "powerLawSmooth") + expect_true(checkLinkParams("powerLaw", 5)) # without the activation, nothing new is checked + ## pc0 above p50 is no error here: it is not used + expect_silent(call(logisticPars = c(0.4, 1, 1))) +}) + +test_that("splitSpreadPar() takes the activation intercept out and puts p50 first as maxAsymptote", { + split <- fireSenseUtils:::splitSpreadPar + ## as DEoptim gives it: unnamed, covariates, the intercept, the year sd + s <- split(c(1.5, 3, -1, a, 0.7), fitYearSpreadSD = TRUE, fitActivationIntercept = TRUE, powerLawPc50 = p50) + expect_identical(unname(s$par), c(p50, 1, 1, 1.5, 3, -1)) + expect_identical(s$activationIntercept, a) + expect_identical(s$yearSpreadSD, 0.7) + ## named, as drawActivePars() and the validation give it: found by name + nm <- c(clim = 1.5, fuel = 3, youngAge = -1, activationIntercept = a, yearSpreadSD = 0.7) + s2 <- split(nm, powerLawPc50 = p50) + expect_identical(unname(s2$par), unname(s$par)) + expect_identical(names(s2$par)[1:3], c("maxAsymptote", "hillSlope1", "inflectionPoint1")) + ## a ledger row's set already has maxAsymptote (p50, with the fixed parameters): kept, not doubled + row <- c(maxAsymptote = p50, hillSlope1 = 1, inflectionPoint1 = 1, nm) + expect_identical(split(row)$par, s2$par) + expect_identical(split(row)$activationIntercept, a) + expect_error(split(c(nm[c(1, 2, 4, 3)], yearSpreadSD = 0.7), powerLawPc50 = p50), "right before the random-effect") + expect_error(split(nm), "powerLawPc50") + ## without it nothing changes, and the element is NULL + old <- split(c(0.27, 1.5, 3, -1, 0.7), fitYearSpreadSD = TRUE) + expect_identical(unname(old$par), c(0.27, 1, 1, 1.5, 3, -1)) + expect_null(old$activationIntercept) +}) + +test_that("spreadRandomEffectArgs() sets fitActivationIntercept only for bounds that have it", { + lo <- c(clim = 0, fuel = 0, activationIntercept = -10, yearSpreadSD = 0) + expect_identical(spreadRandomEffectArgs(lo), list(fitYearSpreadSD = TRUE, fitActivationIntercept = TRUE)) + expect_identical(spreadRandomEffectArgs(lo[-4]), list(fitYearSpreadSD = FALSE, fitActivationIntercept = TRUE)) + ## the other fits get what they got + expect_identical(spreadRandomEffectArgs(c(maxAsymptote = 0.14, clim = 0, yearSpreadSD = 0)), list(fitYearSpreadSD = TRUE)) + expect_error(spreadRandomEffectArgs(lo[c(3, 1, 2, 4)]), "right before the random-effect sds") +}) + +test_that("the objective uses the formula, and its gates and saturation summary look at p with p50 as the ceiling", { + par <- c(clim = 1.5, fuel = 3, youngAge = -1, activationIntercept = a) + args <- list(link = "powerLawSmooth", powerLawPc50 = p50, powerLawGamma = gam, powerLawShape = shp, lowerAsymptote = f) + for (yr in c("2004", "2005")) { + ## objFunInner() gets what .objfunSpreadFit() hands it: p50 first, the intercept on its own + got <- do.call(spreadProbSeenC, c(list(c(maxAsymptote = p50, par), yr, climateRef = ref), args, + list(activationIntercept = a))) + ## the year's p as fireSense_spreadPredict computes it (spreadProbFromCovs() on the same design matrix) + p <- as.numeric(spreadProbFromCovs(matOf(yr), lp3, b, f, link = "powerLawSmooth", climateRef = ref, powerLawPc50 = p50, + powerLawGamma = gam, powerLawShape = shp, lowerAsymptote = f, activationIntercept = a)) + ign <- climFix$historicalFires[[yr]]$cells # the ignition cell is 1 + expect_true(got$reached) + expect_equal(got$sp[-ign], p[-ign]) + expect_identical(got$pSummary, spreadProbSummary(p, ceiling = p50)) + } + ## spreadProbGates() agrees: the same p, the same ceiling + g <- do.call(spreadProbGates, c(list(par = par, annualDTx1000 = climFix$annualDTx1000, + nonAnnualDTx1000 = climFix$nonAnnualDTx1000, historicalFires = climFix$historicalFires, + formulaToFit = formC, climateRef = ref, years = "2005", mutuallyExclusive = NULL, + lanscape1stQuantileThresh = 0.2, maxFireSpread = 0.28), args)) + p5 <- as.numeric(spreadProbFromCovs(matOf("2005"), lp3, b, f, link = "powerLawSmooth", climateRef = ref, powerLawPc50 = p50, + powerLawGamma = gam, powerLawShape = shp, lowerAsymptote = f, activationIntercept = a)) + expect_identical(g$pass, spreadProbGateTest(p5, p50, f, 0.28, 0.2)$pass) +}) + +test_that("on the whole landscape spreadCpp() gets per-cell pc from fuel, and burns as the full probability vector", { + skip_if_not_installed("SpaDES.tools") + args <- list(clim = function(pix) 0.5 + 0.4 * cos(pix), link = "powerLawSmooth", powerLawGamma = 1.9, powerLawShape = 0.5, + lowerAsymptote = 0.05, climateRef = c(clim = 0.5), powerLawPc50 = 0.5, activationIntercept = 1, + returnSims = TRUE, returnBurned = TRUE, seed = 3) + for (more in list(list(), list(yearSpreadSD = 0.5))) { + full <- do.call(wlObjective, c(list(fx = closedBuffer(), annPix = seq_len(3600L)), args, more)) + lazy <- do.call(wlObjective, c(list(whole = TRUE), args, more)) + expect_identical(lazy$burned, full$burned) + expect_identical(lazy$sims, full$sims) + } + ## a drier year (climate above its reference) gives bigger fires + hot <- do.call(wlObjective, utils::modifyList(c(list(whole = TRUE), args), list(clim = function(pix) rep(1.5, length(pix))))) + ref0 <- do.call(wlObjective, utils::modifyList(c(list(whole = TRUE), args), list(clim = function(pix) rep(0.5, length(pix))))) + expect_gt(mean(hot$sims$sim), mean(ref0$sims$sim)) +}) + +test_that("spreadFitValidationData() predicts p with the activation and records its intercept", { + par <- c(clim = 1.5, fuel = 3, youngAge = -1, activationIntercept = a) + r <- terra::rast(nrows = 20, ncols = 20, xmin = 0, xmax = 20, ymin = 0, ymax = 20, vals = 1) + fb <- lapply(climFix$historicalFires, function(h) dtC(pixelID = 1:nPixC, buffer = as.integer(1:nPixC <= 30), ids = 1L)) + d <- spreadFitValidationData(par, r, climFix$annualDTx1000, climFix$nonAnnualDTx1000, formC, + climFix$historicalFires, fb, mutuallyExclusive = NULL, Nreps = 2L, link = "powerLawSmooth", + powerLawGamma = gam, powerLawShape = shp, lowerAsymptote = f, climateRef = ref, + powerLawPc50 = p50, seed = 1) + info <- attr(d, "spreadFitValidation") + expect_identical(info$activationIntercept, a) + expect_identical(info$logisticPars[[1]], p50) + expect_lte(max(d$p), p50) + g <- plotSpreadFitResponse(d) + hl <- Filter(function(l) inherits(l$geom, "GeomHline"), g$layers)[[1]] + expect_equal(hl$data$yintercept[2], qlogis(p50)) +}) + +test_that("runDEoptim() tells the fit and the re-score of the activation, and leaves the other fits' calls as they were", { + seen <- new.env() + testthat::local_mocked_bindings( + clusterSetup = function(...) list(itermax = 5, trace = FALSE, strategy = 2L, NP = 40L, cluster = NULL), + DEoptimIterative = function(fn, lower, ...) { seen$fit <- list(...)$fitActivationIntercept; list(list(member = list(pop = matrix(lower + 0.1, 1)))) }, + .package = "clusters") + testthat::local_mocked_bindings( + rescorePopulation = function(pop, fn, reps, cl, seed = 1L, fnArgs = list()) { + seen$rescore <- fnArgs; data.table::data.table(member = 1L, rep = 1L, value = 1) }) + seen$omit <- list() + testthat::local_mocked_bindings(Cache = function(FUN, ..., omitArgs = NULL, cachePath = NULL, .functionName = NULL, + .cacheExtra = NULL, useCache = NULL) { + seen$omit[[length(seen$omit) + 1L]] <- omitArgs + if (is.function(FUN)) FUN(...) else FUN + }, .package = "fireSenseUtils") + run <- function(lower) suppressMessages(runDEoptim( + landscape = NULL, annualDTx1000 = NULL, nonAnnualDTx1000 = NULL, fireBufferedListDT = NULL, + historicalFires = NULL, itermax = 5, trace = FALSE, strategy = 2L, cores = c("hostA", "hostB"), + paths = list(cachePath = withr::local_tempdir()), lower = lower, upper = lower + 1, + mutuallyExclusive = NULL, formulaToFit = "~ 0 + clim + fuel", objFunCoresInternal = 1L, covMinMax = NULL, + maxFireSpread = 0.3, Nreps = 1L, .verbose = FALSE, climateRef = list(clim = 0.4), powerLawPc50 = p50)) + run(c(clim = 0, fuel = 0, activationIntercept = -10)) + expect_true(seen$fit) + expect_true(seen$rescore$fitActivationIntercept) + expect_false("fitActivationIntercept" %in% seen$omit[[1]]) + seen$omit <- list() + run(c(maxAsymptote = 0.25, clim = 0, fuel = 0)) + expect_null(seen$fit) + expect_false("fitActivationIntercept" %in% names(seen$rescore)) + expect_true("fitActivationIntercept" %in% seen$omit[[1]]) +}) + +test_that("'predictor' and 'ceiling' give the values they gave before the activation existed", { + ## computed with fireSenseUtils 0.2.3.9181 (origin/development 970e7b5), the last version without it + m <- matOf("2005") + pred <- spreadLinkInputs(m, lp3, b, f, "powerLawSmooth", lowerAsymptote = 0.05, powerLawShape = 0.5) + expect_equal(pred$x[1:4], c(2.3085, 3.0975, 1.589, 2.7405), tolerance = 1e-12) + expect_equal(unname(pred$pars), c(0.27, 1.9, 0.13, 0.5, 0.05)) + ceil <- spreadLinkInputs(m, lp3, b, f, "powerLawSmooth", ref, p50, lowerAsymptote = 0.05, powerLawShape = 0.5) + expect_equal(unname(ceil$pars[1:4, "pc"]), c(0.285198960990328, 0.286472868874645, 0.289501867526665, 0.286594066845817), + tolerance = 1e-12) + expect_equal(ceil$x[1:4], c(1.152, 1.851, 0.089, 1.485), tolerance = 1e-12) +}) + +## pcAtP50 (fireSense_spreadFit's powerLawPcAtP50): the "predictor" link with p_c fixed at p50, by the same mechanism as the +## activation: maxAsymptote is left out of the fitted parameters and the objective puts p50 in its place. + +test_that("splitSpreadPar(pcAtP50 = TRUE) puts p50 first as maxAsymptote, unless a named set has it", { + split <- fireSenseUtils:::splitSpreadPar + s <- split(c(1.5, 3, -1, 0.7), fitYearSpreadSD = TRUE, powerLawPc50 = p50, pcAtP50 = TRUE) + expect_identical(unname(s$par), c(p50, 1, 1, 1.5, 3, -1)) + expect_null(s$activationIntercept) + expect_identical(s$yearSpreadSD, 0.7) + nm <- split(c(clim = 1.5, fuel = 3, youngAge = -1), powerLawPc50 = p50, pcAtP50 = TRUE)$par + expect_identical(names(nm)[1:3], c("maxAsymptote", "hillSlope1", "inflectionPoint1")) + ## a ledger row's set (p50 as maxAsymptote, written by the fit) is kept as it is + row <- c(maxAsymptote = p50, hillSlope1 = 1, inflectionPoint1 = 1, clim = 1.5, fuel = 3, youngAge = -1) + expect_identical(split(row, pcAtP50 = TRUE, powerLawPc50 = p50)$par, nm) + expect_error(split(c(1.5, 3, -1), pcAtP50 = TRUE), "pcAtP50.*powerLawPc50") + ## NULL and FALSE: as before + expect_identical(split(c(0.27, 1.5), pcAtP50 = FALSE)$par, split(c(0.27, 1.5))$par) +}) + +test_that("with pcAtP50 the gates and the validation use p50 as p_c, as a set with maxAsymptote = p50 does", { + par <- c(clim = 1.5, fuel = 3, youngAge = -1) + args <- list(annualDTx1000 = climFix$annualDTx1000, nonAnnualDTx1000 = climFix$nonAnnualDTx1000, + historicalFires = climFix$historicalFires, formulaToFit = formC, years = c("2004", "2005"), + mutuallyExclusive = NULL, link = "powerLawSmooth", powerLawShape = 0.5, lanscape1stQuantileThresh = 0.2, + maxFireSpread = 0.28) + fixed <- do.call(spreadProbGates, c(list(par = list(par, par * 2)), args, list(powerLawPc50 = p50, pcAtP50 = TRUE))) + given <- do.call(spreadProbGates, c(list(par = list(c(maxAsymptote = p50, par), c(maxAsymptote = p50, par * 2))), args)) + expect_identical(fixed, given) + r <- terra::rast(nrows = 20, ncols = 20, xmin = 0, xmax = 20, ymin = 0, ymax = 20, vals = 1) + fb <- lapply(climFix$historicalFires, function(h) dtC(pixelID = 1:nPixC, buffer = as.integer(1:nPixC <= 30), ids = 1L)) + val <- function(par, ...) spreadFitValidationData(par, r, climFix$annualDTx1000, climFix$nonAnnualDTx1000, formC, + climFix$historicalFires, fb, mutuallyExclusive = NULL, Nreps = 2L, + link = "powerLawSmooth", powerLawShape = 0.5, seed = 1, ...) + d <- val(par, powerLawPc50 = p50, pcAtP50 = TRUE) + expect_identical(attr(d, "spreadFitValidation")$logisticPars[[1]], p50) + expect_identical(d$p, val(c(maxAsymptote = p50, par))$p) +}) + +test_that("runDEoptim() hands pcAtP50 to the fit and the re-score, and leaves it out of the key when NULL", { + seen <- new.env() + testthat::local_mocked_bindings( + clusterSetup = function(...) list(itermax = 5, trace = FALSE, strategy = 2L, NP = 40L, cluster = NULL), + DEoptimIterative = function(fn, lower, ...) { seen$fit <- list(...)$pcAtP50; list(list(member = list(pop = matrix(lower + 0.1, 1)))) }, + .package = "clusters") + testthat::local_mocked_bindings( + rescorePopulation = function(pop, fn, reps, cl, seed = 1L, fnArgs = list()) { + seen$rescore <- fnArgs; data.table::data.table(member = 1L, rep = 1L, value = 1) }) + seen$omit <- list() + testthat::local_mocked_bindings(Cache = function(FUN, ..., omitArgs = NULL, cachePath = NULL, .functionName = NULL, + .cacheExtra = NULL, useCache = NULL) { + seen$omit[[length(seen$omit) + 1L]] <- omitArgs + if (is.function(FUN)) FUN(...) else FUN + }, .package = "fireSenseUtils") + run <- function(lower, ...) suppressMessages(runDEoptim( + landscape = NULL, annualDTx1000 = NULL, nonAnnualDTx1000 = NULL, fireBufferedListDT = NULL, + historicalFires = NULL, itermax = 5, trace = FALSE, strategy = 2L, cores = c("hostA", "hostB"), + paths = list(cachePath = withr::local_tempdir()), lower = lower, upper = lower + 1, + mutuallyExclusive = NULL, formulaToFit = "~ 0 + clim + fuel", objFunCoresInternal = 1L, covMinMax = NULL, + maxFireSpread = 0.3, Nreps = 1L, .verbose = FALSE, link = "powerLawSmooth", ...)) + run(c(clim = 0, fuel = 0), powerLawPc50 = p50, pcAtP50 = TRUE) + expect_true(seen$fit) + expect_true(seen$rescore$pcAtP50) + expect_false("pcAtP50" %in% seen$omit[[1]]) + seen$omit <- list() + run(c(maxAsymptote = 0.25, clim = 0, fuel = 0)) + expect_null(seen$fit) + expect_false("pcAtP50" %in% names(seen$rescore)) + expect_true("pcAtP50" %in% seen$omit[[1]]) +}) + +test_that("activationDudYearShare() is pnorm(-a / yearSpreadSD), 0 or 1 without a year effect", { + pars <- data.frame(clim = 1, activationIntercept = c(0.5, 3, -1, 2), yearSpreadSD = c(1, 1, 0, 0)) + expect_equal(activationDudYearShare(pars), c(pnorm(-0.5), pnorm(-3), 1, 0)) + expect_identical(activationDudYearShare(c(clim = 1, activationIntercept = 2)), 0) + expect_error(activationDudYearShare(c(clim = 1)), "activationIntercept") +}) + +test_that("the objective stops on an unnamed par whose length does not fit the formula and the link", { + r <- terra::rast(nrows = 20, ncols = 20, xmin = 0, xmax = 20, ymin = 0, ymax = 20, vals = 1) + fb <- lapply(climFix$historicalFires, function(h) dtC(pixelID = 1:nPixC, buffer = as.integer(1:nPixC <= 30), ids = 1L)) + obj <- function(par, ...) .objfunSpreadFit(par, landscape = r, annualDTx1000 = climFix$annualDTx1000, + nonAnnualDTx1000 = climFix$nonAnnualDTx1000, formulaToFit = formC, + historicalFires = climFix$historicalFires, fireBufferedListDT = fb, + mutuallyExclusive = NULL, Nreps = 1L, link = "powerLawSmooth", + verbose = 0, returnSims = TRUE, ...) + ## p_c left out of par (as with powerLawPcAtP50) but the flag forgotten: the first coefficient would be read as p_c + expect_error(obj(c(1.5, 3, -1), powerLawPc50 = p50), "unnamed `par` gives 0 logistic") + expect_error(obj(c(0.27, 0.1, 1.5, 3, -1), powerLawPc50 = p50), "gives 2 logistic") + ## with the flag, or with p_c in it, it runs + expect_s3_class(obj(c(1.5, 3, -1), pcAtP50 = TRUE, powerLawPc50 = p50), "data.table") + expect_s3_class(obj(c(0.27, 1.5, 3, -1)), "data.table") +})