Package 'fireSenseUtils'

Title: Utilities for Working With the 'fireSense' Group of 'SpaDES' Modules
Description: Utilities for working with the 'fireSense' group of 'SpaDES' modules.
Authors: Jean Marchal [aut], Eliot J B McIntire [aut, cre] (ORCID: <https://orcid.org/0000-0002-6914-8316>), Alex M Chubaty [aut] (ORCID: <https://orcid.org/0000-0001-7146-8135>), Ian Eddy [aut] (ORCID: <https://orcid.org/0000-0001-7397-2116>)
Maintainer: Eliot J B McIntire <[email protected]>
License: GPL-3
Version: 0.2.3.9181
Built: 2026-11-19 05:28:02 UTC
Source: https://github.com/PredictiveEcology/fireSenseUtils

Help Index


fireSenseUtils package

Description

Utilities for working with the 'fireSense' group of 'SpaDES' modules.

Author(s)

Maintainer: Eliot J B McIntire [email protected] (ORCID)

Authors:

See Also

Useful links:


Objective function for fireSense_spreadFit module

Description

Objective function for fireSense_spreadFit module

Usage

.objfunSpreadFit(
  par,
  landscape,
  annualDTx1000,
  nonAnnualDTx1000,
  formulaToFit,
  historicalFires,
  fireBufferedListDT,
  covMinMax = NULL,
  maxFireSpread = spreadProbCeiling,
  lowerSpreadProb = spreadProbFloor,
  minFireSize = 2,
  escapeSizeHa = NULL,
  jumpTries = 0,
  jumpMeanDist = 0,
  yearAreaWeight = 0,
  areaDistWeight = 0,
  returnTerms = FALSE,
  tests = "crps",
  Nreps = 10,
  mutuallyExclusive = list(youngAge = c("class", "nf")),
  doAssertions = TRUE,
  plot.it = FALSE,
  objFunCoresInternal = 1,
  lanscape1stQuantileThresh = 0.265,
  covCentre = NULL,
  weighted = TRUE,
  sizeLik = "kde",
  sizeLikDf = 5,
  adWeight = "auto",
  link = NULL,
  climateRef = NULL,
  powerLawPc50 = NULL,
  powerLawGamma = spreadPowerLawGamma,
  powerLawShape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu,
  returnSims = FALSE,
  returnBurned = FALSE,
  penaliseRunaways = TRUE,
  runawayEdgeFrac = fireSenseRunawayEdgeFrac,
  runawayEdgeMin = fireSenseRunawayEdgeMin,
  runawaySize = NULL,
  runawayBufferMultiple = NULL,
  fitYearSpreadSD = NULL,
  fitFireSpreadSD = NULL,
  verbose = 2,
  crpsWeights = NULL,
  gateRefusal = c("minLik", "simulate"),
  wholeLandscape = FALSE,
  ...
)

Arguments

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 fireSpreadSD (see fitFireSpreadSD) and yearSpreadSD last (see fitYearSpreadSD), in that order.

landscape

A SpatRaster with extent, resolution, and projection (crs) used for SpaDES.tools::spread2.

annualDTx1000

A list of data.table class objects. Each list element is data from a single calendar year, and whose name takes the form "yearxxxx", where xxxx is the four-digit year. The columns in the data.table must integers, that are ⁠1000x⁠ their actual values as this function will divide by 1000.

nonAnnualDTx1000

Like annualDTx1000, but with where each list element will be used for >1 year. The names of the list elements must be of the form "yearxxxx_yearyyyy_yearzzzz" where xxxx, yyyy, and zzzz represent the four-digit calendar years for which that list element should be used. The columns are variables that are used for more than 1 year.

formulaToFit

Formula, put provided as a character string, not class formula. (if it is provided as a class formula, then it invariably will have an enormous amount of data hidden in the formula environment; this is bad for DEoptim::DEoptim)

historicalFires

A named list of data.frames (one per year, names matching those of annualDTx1000), each with columns cells (pixel indices of ignitions) and size (fire size in pixels). The observed fire record against which the simulation is compared.

fireBufferedListDT

A named list of data.tables (one per year, names matching annualDTx1000), each with columns pixelID, buffer (1 if the pixel is inside a buffered fire footprint, 0 otherwise), and ids (a unique identifier per fire). Restricts the set of pixels used when fitting and scoring spread.

covMinMax

This is a 2 row by multiple column data.frame indicating the minimum and maximum values of the original covariate data values. These will be used to rescale the covariates internally so that they are all between 0 and 1. It is important to not simply rescale internally here because only 1 year is run at a time; all years must be rescaled for a given covariate by the same amount.

maxFireSpread

A value for spreadProb that is considered impossible to go above. Default spreadProbCeiling, also the upper bound of maxAsymptote. maxAsymptote is the spread-probability ceiling in a typical year. The year random effect (yearSpreadSD) is added on the logit of the final spread probability, after the link, so in a given year p can exceed maxAsymptote or fall below lowerSpreadProb; that is intended. There is no absolute cap, because spreadCpp does not need one; maxAsymptote is bounded because runaway fires are slow to simulate and wasted if the parameters are wrong.

lowerSpreadProb

Numeric. Lower bound for spreadProb; if a candidate spreadProb falls at or below this, the call exits early to avoid wasted simulation work. Default spreadProbFloor.

minFireSize

Integer. Minimum fire size (in pixels) to include when scoring simulated against historical fires; fires smaller than this are filtered out of the comparison. Default 1.

escapeSizeHa

Numeric or NULL. Size (ha) a fire must reach to count as escaped. NULL (the default) keeps the historical behaviour. When set, only observed fires of at least escapeSizePixels() pixels are fitted, and every simulated fire starts as an escaped fire: it burns its first escapeSizePixels() cells regardless of spreadProb (SpaDES.tools::spreadCpp(minSize =)), then spreads with the fitted probabilities. So the spread model is fitted as "given the fire escaped".

jumpTries, jumpMeanDist

Used with escapeSizeHa: passed to SpaDES.tools::spreadCpp(), so a fire stuck below the escape size (no burnable neighbour left) can jump to nearby burnable land. jumpTries is how many times it may try, jumpMeanDist the mean jump distance in pixels. 0 (default) is off.

yearAreaWeight

Weight of the annual-area term: each fit year's observed area burned scored against that year's simulated totals, one per replicate, with the per-fire size likelihood (yearAreaNLL()). 0 (default) leaves it out; "auto" is (number of fitted fires) / (number of fit years), so the year view and the per-fire view carry equal total weight.

areaDistWeight

Weight of the area-weighted size-distribution term (areaWeightedCvM()), which compares simulated and observed fires by the share of area burned they make up. 0 (default) leaves it out; "auto" uses the AD term's weight, adWeightAuto().

returnTerms

Logical. TRUE returns the objective with each term separately (diagnostics).

tests

One or more of "mad", "adTest", "pitAD" or "crps". Default: "crps". ("snll_fs" and "SNLL" were removed; "snll_fs" stops with an error.) "crps" is a different objective made of proper scores, each smooth in the parameters: the per-fire CRPS on log size (crpsFireSizes(), summed over fitted fires), plus the pooled adTest, plus areaDist (areaWeightedCvM()), plus the CRPS of the log total area burned over all fit years (crpsTotalArea()), plus the CRPS of the 10 largest fires (crpsTopFires()), plus, if its weight is not 0, the mean over fit years of the CRPS of each year's log area burned (crpsAnnualArea()), plus, if its weight is not 0, the CRPS of the logit of the share of the area burned by the 10 largest fires (crpsTopShare()), each times its weight in crpsWeights. It takes over the adTest and areaDist terms (their weights come from crpsWeights, not adWeight or areaDistWeight), has its own annual-area term, off by default (crpsWeights$annualArea; yearAreaWeight is not used with it). A cut replicate (burned an open buffer edge pixel) is scored in the per-fire term as at least the observed size, and in the other terms at the size it burned. Combined with the other tests it adds to them. "pitAD" is a rank-based Anderson-Darling term that does not depend on the fit buffers: each fitted fire's observed size ranked among its own replicates (pitMidRank()), scored against Uniform(0, 1) (adUniform()), weighted like "adTest" (adWeight).

Nreps

Integer. The number of replicates, per ignition, to run.

mutuallyExclusive

Named list of vectors describing groups of model terms that must not be active together (mutually exclusive in the formula). Default list("youngAge" = c("class", "nf")).

doAssertions

Logical. If TRUE, the default, the function will test a few minor things for consistency. This should be set to FALSE for operational situations, as the assertions take some small amount of time.

plot.it

Passed to SpaDES.core::Plots(), so will show (TRUE or "screen") or save files of several plots, using ggplot2.

objFunCoresInternal

Internally, this function can use mcmapply to run multiple parallel spread function calls. This should only be > 1L if there are spare threads. It is highly likely that there won't be. However, sometimes the DEoptim::DEoptim is particularly inefficient, it starts X cores, and immediately several of them are stopped inside this function because the parameters are so bad, only two years are attempted. Then the core will stay idle until all other cores for the DEoptim::DEoptim iteration are complete. Similarly, if only physical cores are used for DEoptim::DEoptim, the additional use of hyperthreaded cores here, internally will speed things up (i.e., this maybe could be 2L or 3L).

lanscape1stQuantileThresh

A spreadProb value that represents a threshold for the 1st quantile of the spreadProbs on the landscape; if that quantile is above this number, then the .objFunSpredFit will bail because it is "too burny" a landscape. Default 0.265, meaning if only 25%% of the pixels on the landscape are below this spreadProb, then it will bail.

covCentre

Optional named list or vector of values subtracted from the rescaled covariates of the same name. NULL (default) does no centring. Must be the same at fit and predict. spreadCovCentre() gives the centres to use with an intercept.

weighted

Only picks the constant of adWeight = "auto" (adWeightAuto()): "sqrt" uses the one measured for size-weighted fits, anything else the unweighted one.

sizeLik

How the annual-area term (yearAreaWeight) takes a year's likelihood from its Nreps simulated totals, on the square-root scale. "kde" (default): their kernel density at the observed total (EnvStats::demp()); it is zero away from the simulated totals, so a year they never reach scores the minLik floor however far off it is. "t": a Student-t centred on their mean with their standard deviation as scale; no floor, and a miss costs more the further it is. It also picks the constant of adWeight = "auto".

sizeLikDf

Degrees of freedom of the Student-t when sizeLik = "t". Default 5. Lower values forgive a missed fire more.

adWeight

What the "adTest" statistic is multiplied by. "auto" (default) uses adWeightAuto(). A number is used as given. Not used with "crps", which has its own weight.

link

Passed to logisticAll(): NULL for the form implied by the logistic parameters, or "logistic3pUpper" for the 3-parameter logistic with Stukel's upper tail, whose fourth logistic parameter is upperTail1, or "powerLaw", "powerLawSmooth" or "richards" for powerLawLink(), powerLawSmoothLink() or richardsLink(): maxAsymptote is then p_c, fitted, and the year effect (fitYearSpreadSD) is added to the linear predictor x, not to the logit of p, so a year cannot take p past p_c. Pass it explicitly when fitting: par may arrive unnamed.

climateRef

NULL (default): the climate covariates are inside the logistic, under the maxAsymptote ceiling, as always. A named numeric or list (spreadClimateRef()): climate is taken outside the ceiling, p = plogis(qlogis(p0) + beta_clim * (climate - climateRef)) with p0 the logistic of the other covariates; see spreadProbFromCovs(), which computes both links. The year effect (fitYearSpreadSD) is added on the same logit, after climate. The gates (spreadProbGateTest()) and the saturation summary are then applied to p0, the spread probability at the reference climate, not to p. With a power-law link and powerLawPc50, climate is in the ceiling instead: it moves pc toward powerLawPc50, never past it (spreadLinkInputs()).

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.

powerLawGamma

The "powerLaw" and "powerLawSmooth" links' gamma (powerLawLink()), fixed, not fitted; used only with those links.

powerLawShape

The "powerLaw" and "powerLawSmooth" links' curvature exponent shape (powerLawLink()), fixed, not fitted; used only with those links. Default 1.

lowerAsymptote

The lower asymptote L of the "powerLawSmooth" and "richards" links (powerLawSmoothLink(), richardsLink()), fixed, not fitted, ⁠spreadLowerAsymptoteMin <= L <= spreadProbFloor⁠ (checkLinkParams()); default spreadProbFloor. The spread-probability gates use it as their lower bound with those links (spreadLinkLower()).

richardsNu

The "richards" link's nu, fixed, not fitted; default spreadRichardsNu.

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, the simulated size sim and the observed size, in pixels. A year the objective declines to simulate (its spread probabilities fail the sanity checks) keeps its fires with rep and sim NA, so the caller can count them. Every year is simulated. For diagnostics and validation; the value is not an objective. The result carries attr(, "spreadProb"): the spread probabilities of every fitted pixel-year, summarised by spreadProbSummary(), for linkSaturation().

returnBurned

If TRUE, also record which pixels burned: implies returnSims = TRUE, and the result carries attr(, "burned"), a named list with one element per simulated fire year, each a data.table with the replicate rep and the pixelID of every pixel that burned in it (ignition cells included). A year the objective declines to simulate is NULL. For spreadFitValidationData(). FALSE (default) records nothing and changes nothing.

penaliseRunaways

A simulated fire that burns an open edge pixel of any of its year's buffers (a buffer pixel next to flammable land outside every buffer, see bufferOpen()) is cut: it would have kept burning, so it is "at least this big". The per-fire "crps" term scores it as at least the observed size; the other size-based terms ("adTest", yearAreaWeight, areaDistWeight, "mad") score the size it burned. That is always so. TRUE (default) also stops such a fire at the first open pixel of its own buffer (SpaDES.tools::spreadCpp(stopCells =)), as nothing it burns after that is scored; FALSE lets it burn on. Not with returnSims = TRUE: the simulated sizes are returned as simulated. Fires are not capped at any size: spread is bounded only by the year's buffers. The open pixels are found once per fit (runDEoptim() adds edge and open columns to fireBufferedListDT, addBufferEdge()), or here, for a table without them.

runawayEdgeFrac, runawayEdgeMin

Ignored. A replicate was a runaway when it burned at least max(runawayEdgeMin, ceiling(runawayEdgeFrac * n)) of the n edge pixels of its own buffer, open or not; it is now cut at the first open pixel of any buffer of its year.

runawaySize, runawayBufferMultiple

Ignored, with a warning unless NULL: they set the size a runaway counted as in the size-distribution and area terms. A cut replicate is scored at the size it reached.

fitYearSpreadSD

If TRUE, the last element of par is the sd of a per-year random effect on the logit of spread probability, a seasonal departure: in each replicate the year draws one eps ~ N(0, sd^2) and every pixel of that year spreads with plogis(qlogis(p) + eps), so all of the year's fires are bigger or smaller together. Without it the simulated fire sizes were too alike: medians too large and the largest fires too small at once (2026-09-23). sd = 0 is the model without it, exactly (no random numbers are drawn). NULL (default): TRUE when par is named and includes yearSpreadSD. DEoptim passes par unnamed, so runDEoptim() sets it explicitly.

fitFireSpreadSD

If TRUE, par has the sd of a per-fire random effect, before yearSpreadSD if that is fitted too, else last: in each replicate every fire draws its own eps ~ N(0, sd^2), added to the linear predictor of the cells it spreads to (SpaDES.tools::spreadCpp()'s linkOffset, one per fire, on top of the year's draw), so fires of one year can differ in how readily they spread. Only with wholeLandscape = TRUE (an error otherwise, when the sd is above 0). sd = 0 draws no random numbers, so the objective is exactly the one without it. NULL (default): TRUE when par is named and includes fireSpreadSD. DEoptim passes par unnamed, so runDEoptim() sets it explicitly.

verbose

If >= 2, then this will show more information about spreadProb fitting.

crpsWeights

Named list of the multipliers of the "crps" test's terms, fire, adTest, areaDist, totalArea, top10, annualArea and topShare (the last two 0: left out); names left out take the values of crpsWeightsDefault() (set by the 2026-10-28 profile on ELFs 6.6.2, 14.3 and 11.3, "W3": 1, 0.34, 2.6, 164 and 16.5). NULL is all defaults. Not used without "crps" in tests.

gateRefusal

What a year that fails spreadProbGateTest() gets. "minLik" (default): it is not simulated and scores as if every fire stayed one pixel ("crps"), or the minLik floor (the annual-area term). "simulate": the gates are not applied, the year is simulated and scored like any other, so a parameter set is never refused for its spread probabilities alone.

wholeLandscape

FALSE (default), or TRUE: every fire spreads on all the pixels of annualDTx1000 (the whole landscape's tables) with no buffer edge, so no fire is cut and every term scores the size it burned unbounded. The linear predictor is computed once per year and the spread probability only for the cells a fire reaches (SpaDES.tools::spreadCpp(link = ), the doubles of powerLawLink(), powerLawSmoothLink() or richardsLink()), with no landscape-length vector per replicate, so a fit costs about what a buffered fit does. Needs link one of spreadLinearLinks; not with penaliseRunaways = TRUE, which stops fires at the buffer edge (both an error). FALSE changes nothing.

...

This is not used here, but allows for extraneous arguments to not break this function. The removed arguments capSizes, penaliseCapHits and thresh arrive here: they are ignored with a deprecation warning (fires are no longer capped at a size; use penaliseRunaways).

Value

The objective, to be minimised: the sum of the terms tests asks for. With returnTerms = TRUE, a named vector of the objective and each term.


Abbreviate species names for fuel classes

Description

Abbreviate species names for fuel classes

Usage

abbreviateSpNames(df)

Arguments

df

data.table

Value

data.table


Add the climate variables of existing fits to what is being prepared

Description

For prediction from existing fits, possibly of several ELFs that chose different spread variables (spread = "auto"): every variable a fit uses must be prepared. Variables already in climateVariables keep their definition (and years); only missing ones are added.

Usage

addFitClimateVariables(
  climateVariables,
  fitClimVars,
  historicalYears,
  projectedYears = NULL
)

Arguments

climateVariables

The list for sim$climateVariables (names like historical_CMDsm).

fitClimVars

Climate variables the fits use, ClimateNA names.

historicalYears

Years of historical climate: the fire years for a fit, the simulated years with historical climate for prediction. None (NULL or empty) requests no historical climate; with no projected years either, the result is an empty list.

projectedYears

Projected years, from canClimateProjectedYears(). Projected climate is requested for these years only; none (NULL or empty) requests no projected climate.

Value

climateVariables, with any missing variable added.


The fire models' climate variables with those of stored fits

Description

spread becomes the fits' variables, all of them (prediction blends neighbour ELFs, which may have chosen different ones); ignition (xgboost) keeps its variables and gains the fits'. Names without underscores, as the fire modules use them ("CMDsm").

Usage

addFitClimateVariablesForFire(climateVariablesForFire, fitClimVars)

Arguments

climateVariablesForFire

List with ignition and spread.

fitClimVars

Climate variables the fits use, from spreadFitClimateVariables().

Value

climateVariablesForFire, updated.


Automatic weight for the Anderson-Darling term

Description

The multiplier of the "adTest" term, c * sqrt(nFires): it grows with the number of fitted fires, as the (retired) fire-size likelihood the term was balanced against did. c was measured across six ELFs (138 to 1624 fires), one value per sizeLik and weighted combination, on populations fitted with an older objective, so treat the result as the right order of magnitude rather than exact.

Usage

adWeightAuto(nFires, sizeLik = "kde", weighted = FALSE)

Arguments

nFires

Number of fires being fitted (after minFireSize).

sizeLik

As in .objfunSpreadFit().

weighted

As in .objfunSpreadFit(); TRUE uses the unweighted constants.

Value

A single numeric.


Convert list of annual SpatRaster to data.table

Description

Convert list of annual SpatRaster to data.table

Usage

annualStackToDTx1000(x, whNotNA, ...)

## S3 method for class 'SpatRaster'
annualStackToDTx1000(x, whNotNA, ...)

## S3 method for class 'Raster'
annualStackToDTx1000(x, whNotNA, ...)

## S3 method for class 'list'
annualStackToDTx1000(x, whNotNA, ...)

Arguments

x

RasterStack or list of rasters to convert to data.table and multiply by 1000 to save space.

whNotNA

Pixel indexes that should go through this process (i.e. not NA)

...

Not currently used

Value

data.table of the SpatRaster or the list

Examples

withr::local_package("raster")

r1 <- raster(extent(0, 10, 0, 10), vals = 1:100)
r2 <- raster(extent(0, 10, 0, 10), vals = 100:1)
r3 <- raster(extent(0, 10, 0, 10), vals = 200:101)
r4 <- raster(extent(0, 10, 0, 10), vals = 300:201)

# list of Rasters
lRast <- list(r1, r2, r3)
lRast[[1]][5] <- NA
whNotNA <- setdiff(1:ncell(r1), 5)

# unnamed -- should error
try(out1 <- annualStackToDTx1000(lRast, whNotNA))

# named
names(lRast) <- c("OneToHun", "HunToOne", "TwoHunToOneHun")
out1 <- annualStackToDTx1000(lRast, whNotNA)

# RasterStack
out2 <- annualStackToDTx1000(raster::stack(lRast), whNotNA)

# List of RasterStacks
s1 <- raster::stack(r1, r2)
names(s1) <- names(lRast)[1:2]
s2 <- raster::stack(r4, r3)
names(s2) <- c(names(lRast)[3], "ThreeHunToTwoHun")
out3 <- annualStackToDTx1000(list(s1 = s1, s2 = s2), whNotNA) ## named list required

# With duplicated names -- to remove duplicates;
#  actually, this doesn't make sense: RasterStack can't have duplicated names
names(lRast) <- c("OneToHun", "OneToHun", "TwoHunToOneHun")
out4 <- annualStackToDTx1000(raster::stack(lRast), whNotNA)

## cleanup
withr::deferred_run()

Assert that rescaled spread covariates are usable

Description

Covariates were historically required to lie in ⁠[0, 1]⁠. That upper bound was a convention of the log-biomass parameterisation, not a requirement of the objective function: covariates enter only through exp(mat %*% covPars) inside logistic3p(), which saturates gracefully (exp(Inf)^(-b) is 0, giving maxAsymptote) and never produces NaN. Fuel covariates expressed as biomass / 1e4 legitimately exceed 1, so only non-negativity and finiteness are enforced.

Usage

assertCovariateRange(dt, colsToUse)

Arguments

dt

A data.table of rescaled covariates.

colsToUse

Character vector of covariate column names to check.

Value

invisible(TRUE), or an error.


Semi-automated selection of fuel classed based on GLMs

Description

Semi-automated selection of fuel classed based on GLMs

Usage

assessFuelClasses(
  landscape,
  fuelCol,
  sppEquiv,
  sppEquivCol,
  targetNonForestClasses = 2,
  targetFuelClasses = 5,
  nonforestLCC,
  pValue = 0.001,
  lccShare = NULL,
  minCovariateProp = 0.05
)

Arguments

landscape

data.table created by prepFuelClasses

fuelCol

the column in sppEquiv with default fuel classes

sppEquiv

table with species name equivalencies between the kNN and final naming formats. See data("sppEquivalencies_CA", "LandR"). Only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use data("sppEquivalencies_CA", "LandR").

sppEquivCol

the column name to use from sppEquiv.

targetNonForestClasses

the number of non-forest fuel classes to generate

targetFuelClasses

target number of treed fuel classes to generate

nonforestLCC

vector or list of vectors of non-forest fuel classes

pValue

for glm coefficient significance when deciding to merge fuel classes

lccShare

Optional named numeric: each land-cover class's share of the ELF's flammable pixels, named by class code (see lccFlammableShare()). NULL (default): every non-forest class is clustered.

minCovariateProp

With lccShare, a non-forest class whose share is below this is too rare to place by its own coefficient: it is left out of the clustering and joins the group of the class whose burn coefficient is nearest, as missingForest does. When every non-forest class is that rare, they form a single group.

Value

a list of three objects:

  1. modSppEquiv, a data.table with assigned fuel classes for each tree species;

  2. nonForestedLCCGroups, a named list of non-forest land cover classes grouped by fuel class;

  3. missingLCCgroup, the class in nonForestLCCGroups to assign forested pixels missing from cohortData;


The edge ring of each fire's buffer, and its open part

Description

A simulated fire may spread only inside the year's buffers. bufferEdge() marks the pixels of each fire's buffer (burned or not) with at least one of its eight (queen) neighbours outside that fire's own buffer. "Outside" is anything that is not a row of the same fire in the table: unburned land of another fire's buffer, pixels removed as non-flammable (see removeBufferedFiresOutsideRTM()), NA cells, and the raster's boundary.

Usage

bufferEdge(fireBufferedDT, r)

bufferOpen(fireBufferedDT, r, flammable = cellsFlammable(r))

addBufferEdge(fireBufferedListDT, landscape)

Arguments

fireBufferedDT

A table of one fire year with columns ids (the fire) and pixelID (cell number in r), as in fireBufferedListDT. bufferOpen() uses its edge column if it has one.

r

A raster with the grid pixelID refers to. bufferEdge() uses only its size; bufferOpen() also its values, NA being non-flammable. A raster without values is all flammable.

flammable

Internal: !is.na() of the values of r, when the caller has it already.

fireBufferedListDT

A list of tables as fireBufferedDT, one per fire year.

landscape

As r.

Details

bufferOpen() marks the edge pixels where a fire is actually stopped by the buffer: those with at least one neighbour that is flammable (not NA in r) and outside every buffer of the year. An edge pixel next to non-flammable land or next to another fire's buffer is not open: a fire there could not have kept burning, or keeps burning in the neighbour's buffer. A simulated fire that burns an open pixel of any buffer of its year is cut ("at least this big") by the spread objective (.objfunSpreadFit()).

Value

bufferEdge(), bufferOpen(): a logical vector, one element per row of fireBufferedDT. addBufferEdge(): fireBufferedListDT with these vectors as columns edge and open in every table that does not have both already (the tables are copied, not modified).


Create buffers around polygons based on area target for buffer

Description

Create buffers around polygons based on area target for buffer

Usage

bufferToArea(
  poly,
  rasterToMatch,
  areaMultiplier,
  verb = FALSE,
  polyName = NULL,
  field = NULL,
  minSize = 500,
  cores = 1,
  ...
)

## S3 method for class 'list'
bufferToArea(
  poly,
  rasterToMatch,
  areaMultiplier = 10,
  verb = FALSE,
  polyName = NULL,
  field = NULL,
  minSize = 500,
  cores = 1,
  ...
)

## S3 method for class 'SpatialPolygons'
bufferToArea(
  poly,
  rasterToMatch,
  areaMultiplier = 10,
  verb = FALSE,
  polyName = NULL,
  field = NULL,
  minSize = 500,
  cores = 1,
  ...
)

## S3 method for class 'sf'
bufferToArea(
  poly,
  rasterToMatch,
  areaMultiplier = 10,
  verb = FALSE,
  polyName = NULL,
  field = NULL,
  minSize = 500,
  cores = 1,
  ...
)

Arguments

poly

sf polygons or a list of sf containing polygons to buffer.

rasterToMatch

A SpatRaster with res, origin, extent, crs of desired outputted pixelID values.

areaMultiplier

Either a scalar that will buffer areaMultiplier * fireSize or a function of fireSize. Default is 1. See multiplier() for an example.

verb

Logical or numeric related to how much verbosity is printed. FALSE or 0 is none. TRUE or 1 is some. 2 is much more.

polyName

Optional character string of the polygon layer name (not the individual polygons on a sf polygon object)

field

Passed to fasterize::fasterize. If this is unique (such as polygon id), then each polygon will have its buffer calculated independently for each unique value in field

minSize

The absolute minimum size of the buffer & non-buffer together. This will be imposed after areaMultiplier.

cores

number of processor cores to use

...

passed to fasterize::fasterize

Value

A data.table (or list of data.tables if poly was a list) with 2 columns: buffer and pixelID. buffer is either 1 (the original polygon) or 0 (in the buffer).


Create a variable sized buffer around a set of pixels belonging to the same fire ID

Description

Create a variable sized buffer around a set of pixels belonging to the same fire ID

Usage

bufferToAreaRast(fireIDraster, areaMultiplier, minSize, flammableRTM, verb = 1)

Arguments

fireIDraster

a SpatRaster with values representing distinct fires in a year

areaMultiplier

A scalar that will buffer areaMultiplier * fireSize

minSize

The absolute minimum size of the buffer & non-buffer together. This will be imposed after areaMultiplier.

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

verb

Logical or numeric related to how much verbosity is printed. FALSE or 0 is none. TRUE or 1 is some. 2 is much more.

Value

a data.table with fire ID, buffer status, and pixelID


Modify cohortData with burn column

Description

Modify cohortData with burn column

Usage

buildCohortBurnHistory(cohortData, pixelGroupMap, firePolys, year)

Arguments

cohortData

either a cohortData object or list of cohortData objects named by year.

pixelGroupMap

either a SpatRaster with pixelGroups or list of SpatRasters named by year.

firePolys

the output of getFirePolygons() with YEAR column.

year

length-two vector giving temporal period used to subset firePolys. Closed interval.

Value

cohortData modified with burn status


Zero-out young non-forest pixels across LCC layers and add a youngAge mask

Description

Identifies pixels that have any non-forest presence (based on the non-pixelID columns of landcoverDT) and whose age is below cutoffForYoungAge. It then sets those pixels to 0 across all layers of LCCras and appends a new single-layer raster named youngAge with 1 for the affected pixels and 0 elsewhere (preserving NA where present in the template).

Usage

calcNonForestYoungAge(landcoverDT, NFTSD, LCCras, cutoffForYoungAge)

Arguments

landcoverDT

data.table. A data.table containing a pixelID column of integer cell indices (1-based) and one or more non-forest columns (all columns except pixelID are interpreted as non-forest for the row-sum).

NFTSD

numeric. A numeric vector (or similar) that can be indexed by pixelID to obtain per-cell age values.

LCCras

SpatRaster. A terra::SpatRaster (single- or multi-layer) whose cells correspond to pixelID. Pixels identified as "young non-forest" are set to 0 in all layers. A new youngAge layer is appended.

cutoffForYoungAge

numeric(1). Age threshold; pixels with age <= cutoffForYoungAge and non-forest presence are flagged as young.

Details

The function proceeds as follows:

  1. Determines the set of non-forest columns as all columns in landcoverDT except pixelID, and computes a per-row sum.

  2. Retrieves pixel ages from NFTSD using pixelID as indices.

  3. Selects pixels where the row sum is above 0 and age <= cutoffForYoungAge; these pixels are considered "young non-forest".

  4. Sets those pixels to 0 in every layer of LCCras using cell indexing.

  5. Builds a new single-layer raster with 1 at those pixel locations and 0 elsewhere (respecting NA from the template), and adds it to LCCras as a layer named youngAge.

Assumptions / requirements

  • LCCras is a terra::SpatRaster (possibly multi-layer). Cell indexing with LCCras[pixToChange] <- 0 applies across all layers for the indexed cells.

  • landcoverDT is a data.table with:

    • a pixelID column of integer cell indices (1-based) consistent with LCCras cell numbering, and

    • all other columns representing non-forest variables whose row-wise sum indicates presence (sumRows > 0).

  • NFTSD is a numeric vector (or similar) indexable by pixelID, providing the age (in the same units as cutoffForYoungAge) for each cell.

  • cutoffForYoungAge is a scalar numeric threshold; pixels with age <= cutoffForYoungAge are flagged as "young".

Notes

  • The function modifies LCCras in place (by reference to the object passed in) and returns the modified raster with an extra youngAge layer.

  • NA cells in LCCras remain NA in the created youngAge layer.

  • landcoverDT is not modified.

Value

A terra::SpatRaster identical to LCCras but with:

  • all "young non-forest" pixels set to 0 across its existing layers, and

  • an additional layer named youngAge where flagged pixels are 1, others are 0, and NAs follow the template mask.

References

  • Terra package reference manual and vignettes for SpatRaster operations (Hijmans, R.J.).

  • data.table reference: .SD, ⁠:=⁠, and efficient grouping/filtering (Dowle, M., & Srinivasan, A.).

See Also

  • terra::rast(), terra::values(), terra::setValues() for raster creation and manipulation.

  • data.table semantics for .SD, in-place updates (⁠:=⁠), and fast row/column operations.

Examples

## Not run: 
library(terra)
library(data.table)

# Build a small template raster
r <- rast(nrows = 3, ncols = 3)
values(r) <- c(NA, 0, 0,
               0, 0, NA,
               0, 0, 0)

# Make a 2-layer LCC raster (copy template twice)
LCC <- c(r, r)
names(LCC) <- c("LCC1", "LCC2")

# A data.table with pixel indices and two non-forest columns
dt <- data.table(
  pixelID = c(2, 3, 4, 5, 7, 8, 9),
  NF1 = c(1, 0, 0, 2, 0, 0, 1),
  NF2 = c(0, 1, 0, 0, 0, 3, 0)
)

# Age vector indexed by cell ID (length ncell(LCC))
ages <- seq_len(ncell(LCC)) * 5  # toy ages

out <- calcNonForestYoungAge(
  landcoverDT = dt,
  NFTSD = ages,
  LCCras = LCC,
  cutoffForYoungAge = 15
)

out
names(out)     # "LCC1" "LCC2" "youngAge"
plot(out$youngAge)

## End(Not run)

Iteratively calculate youngAge column in FS covariates

Description

Deprecated: use youngAgeAtYear(). This one treats NA ages as young, only sees the fires in fireBufferedListDT (those being fitted), and needs a raster copy per year.

Usage

calcYoungAge(
  years,
  annualCovariates,
  standAgeMap,
  fireBufferedListDT,
  cutoffForYoungAge = fireSenseYoungAgeCutoff
)

Arguments

years

the years over which to iterate

annualCovariates

list of data.table objects with pixelID

standAgeMap

template SpatRaster

fireBufferedListDT

data.table containing non-annual burn and buffer pixelIDs

cutoffForYoungAge

Numeric. Default is 15. This is the age below which the pixel is considered "young" –> youngAge column will be 1 if age <= 15

Value

a raster layer with unified stand age and time-since-disturbance values


Calibrate the "powerLaw" link's gamma on a flammable map

Description

The "powerLaw" link (powerLawLink()) is p = p_c - (p_c - floor) * exp(-x / gamma). gamma cannot be fitted: it is confounded with the scale of the coefficients. This sets it from the landscape itself, so that one unit of x is the same percent change in fire size in every ELF. Fires are spread with a constant spread probability p on the flammable pixels (0 elsewhere), each from a random start in the largest (8-neighbour) connected flammable patch, with SpaDES.tools::spreadCpp() as fireSense_burn and the fit call it (8 directions, an escaped fire burns its first escapeSizePixels() pixels, jumpTries, jumpMeanDist). A fire runs away when it burns at least runawayShare of that patch.

Usage

calibratePowerLaw(
  flammable,
  pGrid = spreadPowerLawPGrid,
  nFires = 400L,
  cores = 1L,
  seed = 1L,
  escapeSizeHa = 50,
  jumpTries = 20L,
  jumpMeanDist = 3,
  runawayShare = 0.25,
  pFitMin = 0.15
)

Arguments

flammable

A SpatRaster: 1 on flammable pixels, 0 or NA elsewhere (e.g. flammableRTM).

pGrid

Increasing spread probabilities to simulate. The default (spreadPowerLawPGrid) brackets thresholds of 0.22-0.32 with a fine step there.

nFires

Fires per value of p.

cores

Number of forked processes (parallel::mclapply()); 1 runs in this process, as does any value where forking is unavailable (parallelly::supportsMulticore(), e.g. Windows).

seed

Integer seed.

escapeSizeHa, jumpTries, jumpMeanDist

As in .objfunSpreadFit() and fireSense_burn. escapeSizeHa NULL or NA spreads each fire from its start pixel only.

runawayShare

A fire is a runaway if it burns at least this share of the largest flammable patch.

pFitMin

Lowest p used for gamma; very small fires are dominated by the escape size.

Details

p50 is where the share of runaway fires crosses 0.5: the share is made monotone in p with isotonic regression (stats::isoreg(), which needs no smoothing choice) and interpolated linearly between the two grid points that straddle 0.5. gamma is the negative slope of ⁠log(mean fire size, ha)⁠ on log(p50 - p) for the p in pGrid from pFitMin up to p50, with p_c fixed at p50 (more stable per ELF than fitting p_c as well). On five ELFs' flammable maps (240 m) p50 was 0.258-0.283, gamma 2.2-3.3 and R2 0.92-0.985.

The result depends on seed and the arguments only, not on cores: each fire has its own L'Ecuyer-CMRG stream. The caller's random-number state is left as it was.

Value

A list: p50, gamma, R2 (of the gamma regression), and table, a data.frame with one row per p: p, nFires, meanHa, shareRunaway and shareRunawayMonotone (the isotonic fit).

Examples

r <- terra::rast(nrows = 61, ncols = 61, xmin = 0, xmax = 14640, ymin = 0, ymax = 14640, vals = 1)
cal <- calibratePowerLaw(r, pGrid = seq(0.15, 0.4, by = 0.025), nFires = 10)
cal$p50

The years of projected climate that canClimateData prepares

Description

canClimateData's projectedClimateYears is the one place these are set (its default is 2011:2100). Empty, or without canClimateData in the run, means no projected climate: runs that sample past climate (NRV) set it empty.

Usage

canClimateProjectedYears(sim)

Arguments

sim

A simList.

Value

Integer/numeric years; NULL if canClimateData is not in the run.


preparing covariates for fitting modules

Description

preparing covariates for fitting modules

Usage

castCohortData(
  cohortData,
  pixelGroupMap,
  lcc,
  ageMap = NULL,
  missingLCC,
  year = NULL,
  cutoffForYoungAge = fireSenseYoungAgeCutoff
)

Arguments

cohortData

A data.table with columns: pixelGroup, ecoregionGroup, speciesCode, and optionally age, B, mortality, aNPPAct, and sumB.

pixelGroupMap

A RasterLayer with pixel values equal to a pixel group number that corresponds exactly to pixelGroup column in cohortData.

lcc

data.table of dummified landcover

ageMap

a stand age map to assign ages to non-forest LCC used during predict

missingLCC

LCC class to assign forested pixels absent from cohortData must be a character matching a nonForestedLCC group, e.g. '⁠nonForest_highFlam'⁠

year

numeric representing the year represented by cohortData

cutoffForYoungAge

Numeric. Default is 15. This is the age below which the pixel is considered "young" –> youngAge column will be 1 if age <= 15

Value

a trimmed cohortData with wide-layout and rows for every pixel in lcc


Stop if a stored escape definition differs from the current one

Description

A fit's ledger row records the escapeDefinition() it was fitted with. Burning or scoring with another definition would compare fires of one kind with a model of another, so this is an error.

Usage

checkEscapeDefinition(recorded, current = escapeDefinition(), what = "the fit")

Arguments

recorded

Ledger rows (data.frame or list), e.g. one per ELF, with the columns of escapeDefinition(). Rows without them, or with escapeSizeHa NA (fitted before the definition was recorded), are not checked. With a polygonIDTxt column, the message names the ELF of the row that differs.

current

The definition in use, from escapeDefinition() or escapeDefinitionOf(). One with escapeSizeHa NA (a run with an old fit's definition) checks nothing.

what

Where recorded comes from, for the message.

Value

TRUE invisibly if every row checked agrees, NA invisibly if none was checked; otherwise an error.


Check the parameters of the links with a lower asymptote

Description

The one check of lowerAsymptote and richardsNu, used by fireSense_spreadFit for its parameters and by 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.

Usage

checkLinkParams(link, lower = NULL, nu = NULL)

Arguments

link

The spread link.

lower, nu

The lowerAsymptote and richardsNu to check; NULL is not a number.

Value

TRUE, invisibly; an error otherwise.


Data checks and assertions for spreadFitRun

Description

chk_duplicatedStartPixels enforces the invariant that no more than one fire can be ignited in a given pixel within a single time interval. When duplicate cells are detected it issues a warning and keeps only the largest fire (by size) for each duplicated pixel.

Usage

chk_duplicatedStartPixels(cells, size)

.doDataChecks(moduleName, envir, attribs, fml)

Arguments

cells

Integer vector of raster cell indices (pixel IDs) at which fires are scheduled to start.

size

Integer vector the same length as cells, giving the size of each fire (number of pixels). Used to break ties when duplicates exist.

moduleName

Character. Name of the calling SpaDES module, used as a prefix in any error messages thrown.

envir

An environment (typically a SpaDES module's sim object) that is expected to contain the data object named "fireAttributesFireSense_SpreadFit".

attribs

Character. Name of the data object being checked, included in error messages so the caller can identify which input failed.

fml

A model formula passed through to stats::is.empty.model().

Value

A list with two elements: loci (deduplicated cells) and sizes (corresponding size values).

Called for its side effects. Throws an informative error if any check fails; returns invisibly otherwise.


Choose an ELF's dominant and secondary fuel classes

Description

Ranks fuel classes by total treed AGB over a single representative data year (the fit study area), so fireSenseCovariatesCreate(fuelCovariates = "domSecWetland") can be told the same domClass/secClass for every data year of a fit, instead of choosing independently (and possibly differently) each time it is called. Ties are broken alphabetically by fuel-class name for a deterministic result.

Usage

chooseDomSecFuelClasses(
  cohortData,
  pixelGroupMap,
  flammableRTM,
  landcoverDT,
  sppEquiv,
  fuelClassCol,
  sppEquivCol,
  cutoffForYoungAge,
  requiredFuelClasses = NULL
)

Arguments

cohortData

A data.table with columns: pixelGroup, ecoregionGroup, speciesCode, and optionally age, B, mortality, aNPPAct, and sumB.

pixelGroupMap

A RasterLayer with pixel values equal to a pixel group number that corresponds exactly to pixelGroup column in cohortData.

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

landcoverDT

As in fireSenseCovariatesCreate().

sppEquiv

table with species name equivalencies between the kNN and final naming formats. See data("sppEquivalencies_CA", "LandR"). Only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use data("sppEquivalencies_CA", "LandR").

fuelClassCol

As in fireSenseCovariatesCreate().

sppEquivCol

the column name to use from sppEquiv.

cutoffForYoungAge

As in fireSenseCovariatesCreate().

requiredFuelClasses

As in fireSenseCovariatesCreate().

Value

list with domClass and secClass (character); secClass is NA when fewer than two fuel classes are present, and both are NA when there are none (e.g. an ELF with no tree species at all).


Ensure fire points are located on flammable pixels inside a fire polygon Intended to be run using Map

Description

Ensure fire points are located on flammable pixels inside a fire polygon Intended to be run using Map

Usage

cleanUpSpreadFirePoints(firePoints, bufferDT, flammableRTM, idCol)

Arguments

firePoints

a sf points object representing annual ignitions

bufferDT

a data.table of burned cells, output from bufferToArea

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

idCol

Character. Name of the column in firePoints that uniquely identifies each fire event (e.g. "FIRE_ID").

Value

a list of harmonized points and polygons


Clear fuel, non-forest land cover and treed wetland where youngAge is 1

Description

What fireSenseCovariatesCreate(youngAge = TRUE) does for one year, for a table made with youngAge = FALSE whose youngAge was then resolved for the year with youngAgeAtYear(): the columns of youngAgeExclusiveCols() are set to 0, fuel biomass (every column that is not ⁠nfLCC_*⁠, treedWetland or youngAge) to logMinB(0), the value a pixel without that fuel has. It works on the covariates as they are built (fuel on the log scale), whatever scale a model later uses.

Usage

clearYoungAge(covs)

Arguments

covs

data.table of pixelID, the covariates and youngAge (0/1). Changed by reference.

Value

covs.


Fixed ranges of the spread covariates

Description

climateCovRanges is the one table of fixed c(min, max) ranges, one per climate variable of the spread model, that fireSense_spreadFit uses by default (its covFixedRange) instead of the range of each ELF's data, so a coefficient means the same thing in every ELF. The variables and their units: CMD, CMDsm and CMDsp are climate moisture deficit in mm (annual, summer-to-date and spring); cumMDC is a cumulative Monthly Drought Code, an index with no unit (it is not mm). Tmaxsm is the summer (June-August) mean of the daily maximum temperature in degrees C, 0-10; PPTsm is summer precipitation in mm, 0-100. Spans are round decimal numbers, so a coefficient is easy to multiply out afterwards; the rescaling is linear, so values outside a span are fine. The values are provisional: the four moisture-deficit variables are 0-100 for now, to be replaced after the cumMDC values have been checked, and Tmaxsm and PPTsm are first guesses. A climate covariate selected for the spread fit that is not in this table stops the fit; add its range here.

Usage

climateCovRanges

Format

A named list of c(min, max).


ClimateNA names of climate variables given with or without underscores

Description

The fire modules name climate layers without underscores ("CMDsm"), ClimateNA with them ("CMD_sm"). Both forms map to the ClimateNA name.

Usage

climateNAnames(x)

Arguments

x

Character vector of variable names.

Value

Character vector of ClimateNA names, same length as x.


Converts stacks of climate rasters to data.table and optionally subsets to index

Description

Converts stacks of climate rasters to data.table and optionally subsets to index

Usage

climateRasterToDataTable(historicalClimateRasters, Index = NULL)

Arguments

historicalClimateRasters

named list of SpatRaster objects

Index

optional. Either a list of data.table objects named by fireYear (the raster layer names, e.g. year1990), each with a column pixelID: the fire buffer indices, so only those year-and-pixel pairs are returned; or a vector of pixelIDs kept in every year. Only the cells of Index are read from the rasters, not every cell, so a large raster is never made into a table. NULL (the default) returns every cell.

With no raster (a spread model with no climate variable, ~ 1) the table has no climate column: its pixelID and year are those of Index (none, if Index is not a list), so the joins that follow still work.

Value

a long-layout data.table of climate values in each pixel and year, at full precision: the x1000 integer storage (toX1000()) is where they are rounded, as fireSense_spreadPredict does, so a value is stored as the same integer in the fit and in the prediction


Classify pixelGroups by flammability

Description

Classify pixelGroups by flammability

Usage

cohortsToFuelClasses(
  cohortData,
  pixelGroupMap,
  flammableRTM,
  landcoverDT = NULL,
  sppEquiv,
  sppEquivCol,
  cutoffForYoungAge,
  fuelClassCol = fireSenseFuelClassCol,
  requiredFuelClasses,
  asTable = FALSE
)

Arguments

cohortData

A data.table with columns: pixelGroup, ecoregionGroup, speciesCode, and optionally age, B, mortality, aNPPAct, and sumB.

pixelGroupMap

A RasterLayer with pixel values equal to a pixel group number that corresponds exactly to pixelGroup column in cohortData.

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

landcoverDT

Optional table of non-forest land cover classes and pixel indices. It will override pixel values in cohortData, if supplied.

sppEquiv

table with species name equivalencies between the kNN and final naming formats. See data("sppEquivalencies_CA", "LandR"). Only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use data("sppEquivalencies_CA", "LandR").

sppEquivCol

the column name to use from sppEquiv.

cutoffForYoungAge

age at and below which pixels are considered 'young'

fuelClassCol

the column in sppEquiv that describes unique fuel classes

requiredFuelClasses

A character vector of all the fuel classes that are expected. This is needed because a fuel class may disappear (e.g., Popu_tre) due to succession, causing a downstream failure because the prediction model requires values for it.

asTable

if TRUE, return a data.table with pixelID and one column per layer, restricted to cells where at least one layer is not NA – exactly ⁠as.data.table(as.data.frame(<the SpatRaster>, cells = TRUE))⁠ with cell renamed to pixelID, without building the raster. Used by fireSenseCovariatesCreate().

Value

a SpatRaster of biomass by fuel class as determined by fuelClassCol and cohortData (or a data.table, see asTable).


Merging and assignment of fuel classes

Description

Merging and assignment of fuel classes

Usage

combine_fuel_classes(df, targetFuelClasses = 5, lowThreshold = 0.05)

Arguments

df

created during assessFuelClasses

targetFuelClasses

the number of classes at which to stop further merging

lowThreshold

species with above10PctRelB below this threshold will be merged with like fuel classes, when available, regardless of coefficient

Value

a data.table with assigned fuel classes for each species


Add the size merges to the fire-count plan

Description

A size merge covers every ELF in its members, so a fire-count merge whose members are all in one is replaced by it. Skips stay. The size merges get the fire counts of their members from status.

Usage

combinePlans(firePlan, sizePlan, status)

Arguments

firePlan

Plan from ELFmergePlan().

sizePlan

Plan from ELFsizePlan().

status

ELFfitStatus() of the original ELFs.

Value

A data.table in ELFmergePlan()'s format.


Convert covariates to/from integers for smaller footprint; make data.frame

Description

Convert covariates to/from integers for smaller footprint; make data.frame

Usage

covsX1000AndSetDF(
  annualList,
  nonAnnualList,
  fireBufferedList,
  fireLociList,
  paramOrder,
  toX1000Integer = TRUE
)

Arguments

annualList

Named list of data.tables of covariates that vary annually. Must have a pixelID column. List name is year.

nonAnnualList

Named list of data.tables of covariates that do not vary each year. Must have a pixelID column. List name is a concatenated set of years separated by underscore.

fireBufferedList

Named list of data.tables of buffered perimeters with pixelID. Must have a pixelID column. List name is yearXXXX where XXXX is the 4 digit year. Column names must be pixelID, buffer with every row a 1 or 0 as to whether that pixel is in or outside the buffer (1 is in the buffer!), and ids with a unique identifier for each fire.

fireLociList

Named list of data.table of pixelID columns where fires occurred. Columns are size which is number of pixels in the fire

paramOrder

Character vector of the order of covariates that will be used.

toX1000Integer

Logical. If TRUE, then it multiples by 1000 and coerces to integer. If FALSE, then it does the inverse.

Value

a data.table with relevant columns made mutually exclusive


Weights of the CRPS spread objective

Description

The multipliers of the terms of tests = "crps" in .objfunSpreadFit(). They were set by the 2026-10-28 profile of the objective on ELFs 6.6.2, 14.3 and 11.3 (the minimum of the combined score against the simulated/observed area ratio, "W3" scheme: each weight is one over the median, over the three ELFs, of its term's range for area ratios 0.5-2, with the total-area and top-10 terms doubled), relative to the per-fire term = 1. Three ELFs and one seed: tune them with the crpsWeights argument.

Usage

crpsWeightsDefault()

Value

A named list: fire (per-fire CRPS on log size, crpsFireSizes()), adTest (adStatistic()), areaDist (areaWeightedCvM()), totalArea (crpsTotalArea()), top10 (crpsTopFires()) and annualArea (crpsAnnualArea()) and topShare (crpsTopShare()); the last two are 0, so their terms are left out unless a weight is given.


The data year a year's vegetation comes from

Description

The one rule for matching a year to a vegetation or land-cover data year: the data year closest to, and not after, the year. fireSense_dataPrepFit assigns each fire year its data year with it and decides a fit's model structure on it; fireSense_dataPrepPredict takes the vegetation of time(sim) with it; so a fit and every prediction, hindcast or forecast, read the same data for the same year.

Usage

dataYearFor(dataYears, years)

dataYearBefore(dataYears, years)

dataYearElement(x, year, before = FALSE)

Arguments

dataYears

integer years with data, in any order.

years

integer years.

x

a list (anything with names) with one element per data year, named ⁠year<dataYear>⁠ (yearTxt) as fireSense_dataPrepFit names cohortDatas, rstLCCs, ...; any name whose digits are the year will do.

year

one integer year.

before

if TRUE, the data year strictly before year (dataYearBefore()) instead of the one not after it.

Details

dataYearBefore() is the rule of a fit: SCANFI vegetation of year Y already shows year Y's burns, so fireSense_dataPrepFit builds a fire year's vegetation table from the data year strictly before it, and the spread objective must read the same table. Prediction and forecast keep dataYearFor() (not after).

Value

dataYearFor(): integer, one data year per element of years. Stops if a year precedes the first data year: it has no vegetation data.

dataYearBefore(): integer, the latest data year strictly before each element of years. Stops if a year is not after the first data year.

dataYearElement(): the name of the element of x that year uses, the one of ⁠dataYearFor(<the years in names(x)>, year)⁠ (dataYearBefore() with before = TRUE).

Examples

dataYearFor(c(1985, 1990, 2000, 2010, 2020), c(1985, 1999, 2015, 2024))
dataYearBefore(c(1985, 1990, 2000, 2010, 2020), c(1986, 1990, 1991, 2020))
dataYearElement(list(year2010 = "a", year2020 = "b"), 2015)
dataYearElement(list(year2010 = "a", year2020 = "b"), 2020, before = TRUE)

Default climate variables for the fire models

Description

ClimateNA names; "cumMDC" is derived by climateData::calcCumMDC(). spread = "auto" picks, per study area, the ignition variable that best tracks annual area burned (fireSense_dataPrepFit's selectSpreadClimateVariable()).

Usage

defaultClimateVariablesForFire

Default vegetation data years for the fireSense modules

Description

The vegetation years that fireSense_dataPrepFit builds by default ("all years that exist"): every SCANFI V2 year (scanfiV2Years) strictly before the last of defaultFireYears(). A data year needs a fire year after it to be fitted against, so with historical climate to 2024 the years are 1985, 1990, ..., 2020.

Usage

defaultDataYears()

Value

An integer vector of years.


Default fire years for the fireSense modules

Description

The years of fire records that fireSense_dataPrepFit fits to, and over which fireSense_ELFs counts fires to merge ELFs with too few of them. Both modules take their fireYears default from here so that the ELFs and the fit always use the same years.

Usage

defaultFireYears()

Details

The years run from 1986, the year after the first SCANFI V2 year (1985), to the latest year with historical climate for every tile (climateData::latestHistoricalYear()); climate is the last of the inputs to reach a year. A fire year is fitted against the latest vegetation year strictly before it (the vegetation of year Y already shows year Y's burns), so 1985 has no vegetation to pair with.

Value

An integer vector of years.


Default DEoptim population size for a fit

Description

The number of workers, and so the DEoptim population NP, runDEoptim() asks for when nCoresNeeded is NULL: 20 + 10 * floor((nParams + 2) / 5), i.e. 30 for 4 to 7 parameters, 40 for 8 to 12 and 50 for 13 to 15. Ten times the number of parameters was tested against other sizes; 40 was a good middle with very little improvement above it, and the current spread ledgers have 10 to 12 parameters, so every current ELF gets 40.

Usage

deoptimPopulationSize(nParams)

Arguments

nParams

Integer. The number of parameters estimated (length(lower)).

Value

An integer.


NFDB fire points with one row per fire

Description

Some NFDB rows repeat another row's date (YEAR, MONTH, DAY) and location exactly, nearly always under a different FIRE_ID: 554 of the 134,007 natural fires of 1986-2025 in release 20260811, 319 of them in BC. Each such group is taken as one fire recorded more than once, and the row with the largest SIZE_HA is kept.

Usage

dropRepeatedFirePoints(pts)

Arguments

pts

SpatVector of NFDB points with YEAR, MONTH, DAY and SIZE_HA.

Value

pts without the repeated rows, in their original order.


Replace NAs in a data.table with zeros

Description

Modifies DT in place: for each column in colsToUse, every NA is overwritten with 0 via data.table::set(). Useful when a covariate table is later passed to a model that does not tolerate NAs.

Usage

dtReplaceNAwith0(DT, colsToUse = NULL)

Arguments

DT

A data.table to be modified by reference.

colsToUse

Character vector of column names in DT to process. NULL (default) means every column.

Value

DT, invisibly modified by reference; columns are unchanged where no NAs were present.


Count fires in each ELF

Description

Counts natural-cause ignitions, escaped natural ignitions and fire polygons falling in each ELF's fitting area (core plus buffer), per year. Here an escaped ignition is one whose reported size escapedFires() keeps, a proxy that needs no polygons: the escape fit and the hindcast use escapedIgnitions(), the ignitions that became a fire polygon of at least escapeSizeHa.

Usage

ELFfireCounts(
  rasWhole,
  firePoints,
  firePolys,
  fireYears,
  pixelAreaHa,
  naturalCauses = c("L", "N"),
  escapeSizeHa = 50,
  overlay = NULL,
  returnPoints = FALSE,
  fireCauses = NULL
)

Arguments

rasWhole

SpatRaster of ELF layers on one common grid, one layer per ELF, as built by makeELFs() (sim$ELFs$rasWhole). Cells are 0 (outside), 1 (buffer) or 2 (core).

firePoints

SpatVector of fire points, as returned by fireregimetools::load_nfdb_points(). Needs columns YEAR, CAUSE and SIZE_HA.

firePolys

SpatVector of fire perimeters, as returned by fireregimetools::load_nbac_polys(). Needs column YEAR. May be NULL when overlay is given.

fireYears

integer vector of the years being fitted.

pixelAreaHa

area of one fitting pixel, in hectares. A polygon counts when its area inside the ELF exceeds this.

naturalCauses

causes treated as natural ignitions.

escapeSizeHa

size (ha) a fire must reach to count as escaped, as in escapedFires() (pixelAreaHa is its pixel area).

overlay

the table from ELFfireOverlay() for rasWhole, firePolys and fireYears, or NULL (default) to compute it. Passing it lets the clipping be done once and cached.

returnPoints

if TRUE, also return the counted points (see Value).

fireCauses

NULL (default) uses naturalCauses. Cause groups (see fireCauseCodes()), e.g. c("natural", "unknown"), set naturalCauses from that table.

Details

Points are counted on the grid of rasWhole with a single terra::cellFromXY() lookup. Polygons are intersected with each ELF's area and their clipped area is compared with pixelAreaHa, mirroring the size filter the spread fit applies (fireSense_dataPrepFit.R:966-982).

Value

A data.table with one row per ELF and year: ELF, year, naturalIgnitions, escapes, firePolygons. With returnPoints = TRUE, a list instead: counts (that table) and points, the SpatVector of the natural points that were counted (in fireYears and inside at least one ELF), in the CRS of rasWhole, with a logical column escaped.


Clip fire polygons to each ELF, once

Description

Intersects the fire polygons with each ELF's fitting area (core plus buffer) and with its core, and returns one row per clipped piece. ELFfireCounts() counts the pieces larger than a pixel in the fitting area, and ELFregionStats() sums the core pieces into a burn rate, so the slow intersection is done once for both. A polygon wholly inside a zone is not clipped; only those crossing its edge are, which is most of the saving.

Usage

ELFfireOverlay(rasWhole, firePolys, fireYears)

Arguments

rasWhole

SpatRaster of ELF layers on one common grid, as in ELFfireCounts().

firePolys

SpatVector of fire perimeters with column YEAR.

fireYears

integer vector of the years to keep.

Value

A data.table: ELF, zone ("fit" for core plus buffer, "core"), YEAR and ha, the geodesic area of the piece. ELFs no polygon reaches have no rows.


Fires per year in each ELF's core

Description

The mean per year, over fireYears, of the natural-cause ignitions (NFDB points of causes L and N, as ELFfireCounts() counts them) and of the area burned (NBAC polygons, clipped by ELFfireOverlay()) inside each ELF's core, after the merges in plan; the ignitions per 100 km^2 of core; and the area burned as a proportion of the core: a merged ELF sums its members. Only cores count, so a fire in a buffer belongs to the ELF whose core it is in. Arctic and Prairie grassland ELFs (ELFsNotFitted()) are not counted, as in fewFireELFs(), whose cached fire records this reads.

Usage

ELFfireRates(
  ELFs,
  plan,
  fireYears,
  pixelAreaHa,
  destinationPath,
  nfdbUrl = nfdbPointUrl(),
  nbacUrl = latestNBACUrl()
)

Arguments

ELFs

List from makeELFs(), before the merges.

plan

The merges and skips, from fewFireELFs() or ELFmergePlan().

fireYears

Integer vector of years to count fires over.

pixelAreaHa

Area of one pixel of the ELF rasters, in ha.

destinationPath

Directory the fire records are downloaded to.

nfdbUrl, nbacUrl

URLs of the NFDB point and NBAC polygon archives.

Value

A data.table with one row per counted ELF (post-merge names): ELF, naturalFiresPerYear, naturalFiresPer100km2PerYear, haBurnedPerYear and proportionBurnedPerYear (area burned per year over the core's area).


Classify each ELF as zero, few or ok on its fire counts

Description

An ELF with no natural ignitions, or no fire polygons, over the whole fitting window cannot be fitted and is "zero". One below any threshold is "few": it can be fitted, but the thin end of the data drives the escape model's 5-fold CV (⁠fireSense_ignitionFit.R:463,889⁠), which needs at least 10 ignited cell-years before some fold is left holding a single row. The escape and spread fits use only escaped fires (see escapedFires()), so an ELF with many small fires and few large ones is "few" through minEscapes.

Usage

ELFfitStatus(
  counts,
  minNaturalIgnitions = 50,
  minFirePolygons = 50,
  minEscapes = 5
)

Arguments

counts

data.table from ELFfireCounts().

minNaturalIgnitions, minFirePolygons, minEscapes

thresholds below which an ELF is "few".

Value

A data.table with one row per ELF: ELF, naturalIgnitions, escapes, firePolygons, yearsWithFire, status ("zero", "few" or "ok").


Measure flammable area in each ELF

Description

Counts the land-cover pixels an ELF has that the fit would treat as flammable, i.e. those not in nonflammableLCC. Unclassified cover (VLCE2 code 0) is nonflammable by default, which is why ELFs outside VLCE2's mapped extent measure at or near zero (8.2, 10.3.2 and 3.2.4 are 0; no-tree-elfs.md §2, elf-8.2-ecoregion.md).

Usage

ELFflammableArea(rasWhole, rstLCC, nonflammableLCC = fireSenseNonflammableLCC)

Arguments

rasWhole

SpatRaster of ELF layers, as in ELFfireCounts().

rstLCC

SpatRaster of land cover, the same source the fit uses.

nonflammableLCC

land-cover codes that cannot burn. The default, fireSenseNonflammableLCC, matches fireSense_dataPrepFit's nonflammableLCC parameter.

Details

This does not gate anything. Per Eliot's 2026-09-11 decision there is no flammable floor – fireSense_spreadFit is allowed to try regardless – so the result is a report, and an input to deciding whether merging an ELF with a neighbour would give it enough to fit.

Value

A data.table with one row per ELF: ELF, flammablePixels, totalPixels, flammableFraction, flammableAreaHa.


Text to print on ELFs

Description

Text to print on ELFs

Usage

elfLabels(ids, labels = c("code", "name", "none"))

Arguments

ids

Character. ELF codes, e.g. c("13.1", "6.2.1").

labels

"code" returns ids; "name" returns the name of the ecozone each ELF lies in, with the code added in brackets where two of ids share a zone name, so that labels stay distinct; "none" returns "".

Value

A character vector the length of ids.

Examples

elfLabels(c("13.1", "5.4", "6.2.1", "6.2.2"), "name")

Name of a merged ELF

Description

Name of a merged ELF

Usage

ELFmergedName(members)

Arguments

members

ids of the ELFs being merged; they must share one base.

Value

The shared base followed by the members' last parts in numeric order, e.g. c("3.2.4", "3.2.1") gives "3.2.1_4" and c("12.2", "12.1") gives "12.1_2".


Decide which ELFs with too few fires to merge, and which not to fit

Description

Every ELF that ELFfitStatus() calls "zero" or "few" is considered once, in ELF order. Its partner is the neighbouring ELF with the same base and the same depth – another piece of the same split ecoprovince, or another whole ecoprovince of the same ecozone – that shares the longest core border (ties: more fires, then ELF order) and is not already part of a merge. If the two together reach all three thresholds they are merged; otherwise neither is fitted. An ELF with no such neighbour is not fitted.

Usage

ELFmergePlan(
  status,
  neighbours,
  minNaturalIgnitions = 50,
  minFirePolygons = 50,
  minEscapes = 5
)

Arguments

status

data.table from ELFfitStatus().

neighbours

data.table from ELFneighbours().

minNaturalIgnitions, minFirePolygons, minEscapes

thresholds a merged ELF must reach, as in ELFfitStatus().

Value

A data.table with one row per decision: action ("merge" or "skip"), ELF (the merged ELF's name, NA for a skip), members (list of the ELF ids involved), naturalIgnitions, escapes and firePolygons (their totals) and reason.


Per-run ELF metrics, for the national map

Description

fireSense_summary writes one file per run, named by ELFmetricsFilename(): a one-row table with runName (the run's .runName), ELF, spreadFitFile and ignitionFitFile (the ledger files whose fits the run used), then the run's metrics. A rerun of a run overwrites its own file, and no file is shared between runs, so runs on different machines never write over each other.

Usage

ELFmetricsFilename(runName)

readELFmetrics(path, files = NULL, current = TRUE)

Arguments

runName

The run's .runName.

path

Folder(s) searched, with their subfolders, for the files.

files

NULL (default), or the ledger file names (spread and ignition) whose runs are current.

current

If TRUE (default), drop the runs made with other fits.

Details

readELFmetrics() reads the files under path. With current = TRUE, it keeps only the runs made with the current fits: a run made with an older fit describes that fit, not the current one. The current fits of an ELF are, as with "latest", the newest: among the ELF's runs, those whose fits were written last, by spreadFitWrittenAt and ignitionFitWrittenAt (when the run's fits were written; a run over several ELFs is as old as its oldest fit), or, for a metrics file without them, by the date in the ledger file names (ledgerFileOrder(); none is oldest). With files, only runs whose ledger files are all among them count, so one experiment's runs can be read. This relies on a refit always being a new ledger row, never replacing one.

Value

ELFmetricsFilename(): the file name, e.g. "ELFmetrics_13.1_NRV_370_1.csv". readELFmetrics(): a data.table with one row per run, or NULL when there is no file. Pass it, with one row per ELF, to plotELFs()'s metrics.

Examples

## Not run: 
m <- readELFmetrics("/mnt/fast/outputs")
## one row per ELF: the mean over its runs
m <- m[, lapply(.SD, mean), by = "ELF", .SDcols = is.numeric]
plotELFs(metrics = m, metric = "areaBurnedHaPerYear")

## End(Not run)

Shared core borders between ELFs

Description

Measures how much core border each pair of ELFs shares on the common grid of rasWhole: the number of horizontally or vertically adjacent cell pairs where one cell is core (2) in one ELF and the other is core in the other.

Usage

ELFneighbours(rasWhole)

Arguments

rasWhole

ELF layers on one common grid, as a multi-layer SpatRaster or a named list of SpatRasters (sim$ELFs$rasWhole). Cells are 0 (outside), 1 (buffer) or 2 (core).

Value

A data.table with one row per pair of ELFs whose cores touch: ELF1, ELF2, sharedEdges (cell edges) and sharedLength (in the grid's map units).


Area, land cover and burn rate of each region

Description

Statistics for ELFsizePlan(). A region is the core (cells equal to 2) of one layer of rasWhole. Land-cover shares come from a regular grid of up to maxSample points in the core, so the result is deterministic. The burn rate is the area of firePolys inside the core, as a percentage of the core per year.

Usage

ELFregionStats(
  rasWhole,
  landCover,
  firePolys = NULL,
  fireYears = NULL,
  classes = c(20, 30, 40, 50, 100, 210, 220, 230),
  maxSample = 20000L,
  overlay = NULL,
  members = NULL
)

Arguments

rasWhole

SpatRaster of region layers on one grid, as in ELFfireCounts(). Cells are 0, 1 or 2 (core). Its map units must be metres.

landCover

SpatRaster of land-cover class codes.

firePolys

SpatVector of fire perimeters with column YEAR, or NULL (burn rate NA, unless overlay is given).

fireYears

years over which firePolys are counted; their number is the divisor of the burn rate.

classes

land-cover codes whose shares are returned. The default is SCANFI's: water, rock, bryoids, shrubs, herbs, coniferous, broadleaf, mixedwood.

maxSample

largest number of sample points per region.

overlay

table from ELFfireOverlay() (its "core" rows are used) instead of firePolys, so the clipping is not done again. It is for the ELFs the regions are made of, see members.

members

named list giving, for each region (name of a layer of rasWhole), the ids of the ELFs in overlay it is made of. Default: each region is its own ELF.

Value

A data.table with one row per region: ELF, areaKm2, burnRate (%/yr) and landCover (list column of named numeric vectors of shares, names classes).


The ELF to run for an ELF id

Description

The ELF to run for an ELF id

Usage

ELFrunName(ELF, plan)

Arguments

ELF

an ELF id.

plan

data.table from ELFmergePlan().

Value

The merged ELF's name if ELF was merged, otherwise ELF.


ELFs that cannot be fitted

Description

ELFs that cannot be fitted

Usage

ELFsExcluded(status)

Arguments

status

data.table from ELFfitStatus().

Value

character vector of ELF names with status "zero".


Identify and rasterize Ecologically-based Low Fractal-dimensional objects within a study area

Description

Intersects a study area with a set of Ecologically-based Low Fractal-dimensional (ELF) polygons, identifies which ELFs overlap the study area, and constructs a single categorical raster combining each ELF's per-cell classification. A cell in an ELF's core (2) is labelled with that ELF. A cell in the buffer (1) of one or more ELFs is labelled with the ELF, among those, whose core is nearest. All other in-domain cells are 0.

Usage

ELFsInStudyArea(studyArea, inputPath, ELFsRaster = NULL, ELFsPolygon = NULL)

Arguments

studyArea

A SpatVector (or object coercible to one) defining the area of interest. Will be reprojected to the CRS of ELFs internally.

inputPath

Character. Directory in which to store any downloads produced by ELFtemplateRaster() when ELFsPolygon is not supplied.

ELFsRaster

Optional named list (one entry per ELF) of SpatRaster objects containing the integer values 0, 1, and 2, accessed via ELFsRaster$rasWhole. If NULL, the per-ELF rasters must be loaded by the caller before invoking this function.

ELFsPolygon

Optional SpatVector of ELF polygons. If NULL (the default), ELFs are generated by calling makeELFs() with a 20 km buffer around rastTemplate.

Details

The function assumes that ELFs (a list-like object with rasWhole rasters and an ID field) and rastTemplate are available in the calling environment, along with inputPath. ELF rasters are expected to contain the integer values 0, 1, and 2, where 2 indicates the core area of the ELF and 1 indicates the buffer for that ELF.

The three layers are combined with terra::cover() so that:

  • cores override everything else,

  • a buffer cell takes the ELF with the nearest core (terra::distance()), and

  • the 0 background fills remaining in-domain cells.

Value

A categorical SpatRaster with a value/ELFind levels table, where ELFind gives the ELF identifier (or "none" for background).

See Also

makeELFs(), terra::distance(), terra::mosaic(), terra::cover()


Merge regions that are too small with a similar neighbour

Description

A region with areaKm2 < minAreaKm2 is small. Its candidate partners are the neighbours of the same group whose land-cover (Bray-Curtis) distance is at most maxLandCoverDist and whose burn-rate ratio (larger over smaller) is at most maxBurnRatio. For each candidate the merge is simulated (areas summed, land cover and burn rate weighted by area, neighbours combined) and the small regions left with no candidate partner, the orphans, are counted. The candidate with the fewest orphans is accepted, ties going to the smaller land-cover distance and then the smaller burn ratio. This repeats until no candidate is left, so a merged region that is still small can merge again and a group can grow beyond two regions.

Usage

ELFsizePlan(
  stats,
  neighbours,
  minAreaKm2 = 35000,
  maxLandCoverDist = 0.35,
  maxBurnRatio = 6,
  group = .ELFparent
)

Arguments

stats

data.table from ELFregionStats(): ELF, areaKm2, burnRate, landCover. An optional list column members names the original ids a region stands for (default: its own id), so a region that is already a merge keeps a name ELFmergedName() can build.

neighbours

data.table from ELFneighbours(), with ELF1 and ELF2.

minAreaKm2

regions with a smaller core area are small. NULL or NA turns the rule off.

maxLandCoverDist, maxBurnRatio

the similarity limits above.

group

function of the region ids giving the group within which regions may merge. The default is the ELF base (ELFmergePlan()'s rule).

Value

A data.table with one row per merged region, as ELFmergePlan() returns for merges: action ("merge"), ELF (the merged name), members (list of the original ids) and reason, plus areaKm2. mergeELFs() applies it. Zero rows if nothing merges.


ELFs permanently left out of fireSense

Description

ELFs of the Arctic (ecozones 1 and 2, ids ⁠1.*⁠ and ⁠2.*⁠) and of the Prairie grassland (ecoprovince 10.2, ids 10.2 and ⁠10.2.*⁠) are never fitted, nor are ⁠10.3.1_2⁠ and ⁠8.1_2⁠, which are mostly farmland that fireSense treats as non-flammable (⁠10.3.1_2⁠: 82% of its core, and 46% of its observed burned area is on burnable pixels; ⁠8.1_2⁠: 55% of its cells, and its spread calibration could not be estimated reliably): runELFs() leaves them out of every list and map, fewFireELFs() neither counts nor merges them, ELFmergePlan() neither merges them nor uses them as partners, and plotELFs() fills them as "not fitted" with the reason.

Usage

ELFsNotFitted(ids)

ELFsArctic(ids)

Arguments

ids

ELF ids.

Value

ELFsNotFitted(): the ids in ids that are left out, named by the reason ("Arctic" or "Prairie grassland" or "Mostly farmland"). ELFsArctic(): only the Arctic ones, unnamed.


ELFs not fitted after merging

Description

ELFs not fitted after merging

Usage

ELFsSkipped(plan)

Arguments

plan

data.table from ELFmergePlan().

Value

character vector of the ELF ids in the plan's skip decisions.


Build a Canada-wide raster template for ELF construction

Description

Downloads the SCANFI Douglas-fir raster (by default the v2 2020 file on the Arbutus object store), aggregates it by a factor of 8, turns it into a 1/NA mask, loads it into memory, and writes it to disk as a reusable template for building Ecologically-based Low Fractal-dimensional (ELF) objects. Both the remote download and the aggregation step are cached via reproducible::Cache(), keyed on url and the remote file's hash, so the template is only rebuilt when the source changes.

Usage

ELFtemplateRaster(
  inputPath,
  url =
    "https://object-arbutus.alliancecan.ca/529feda02d404836b0e91b1d360b4df0:predictiveecology/SCANFI_v2/2020/SCANFI_spsCC_PSEU_MEN_2020_v2_20260119.tif"
)

Arguments

inputPath

Character. Directory in which to store the downloaded source raster and the resulting rastTemplate_Canada.tif.

url

Character. The source raster. It is used only for its footprint and grid, so any SCANFI layer with the national extent will do. The default is the v2 Douglas-fir 2020 file, which has the same extent, 30 m resolution and CRS as the v1.2 file on ftp.maps.canada.ca it replaced, and is smaller (163 MB vs 226 MB).

Details

The Douglas-fir layer is used purely for its spatial footprint and grid, so the returned values are a mask, not cover. At fact = 8, the v1.2 file has 156,026,794 non-NA cells and the v2 file 156,482,565; 460,121 cells are NA only in v1.2 and 4,350 only in v2, so ELF maps and rasterToMatch built from the template differ by about 0.3% of cells between the two. Remote metadata is checked at most once per week (notOlderThan = Sys.time() - 60*60*24*7) to avoid unnecessary network calls.

Value

A SpatRaster pointing to rastTemplate_Canada.tif inside inputPath. The raster covers Canada at roughly 8x the native SCANFI resolution; it is 1 where the aggregated source has data (including zero cover) and NA elsewhere, and is suitable as a template for downstream ELF construction.

See Also

reproducible::prepInputs(), reproducible::Cache(), terra::aggregate(), terra::writeRaster()


Spread covariates that carry no information

Description

A covariate is empty when it is zero everywhere, or, for fuel biomass, when it is on the logMinB() floor everywhere: fuel is stored as log biomass, so a class with no biomass in the buffers is 3.6 everywhere, not 0. The floor is recognised by its value, so the test does not depend on how a column is named. An indicator with any 1, or a fuel class with any biomass, is not empty. NAs are ignored, as colSums(na.rm = TRUE) did.

Usage

emptySpreadCovariates(dt, cols)

Arguments

dt

data.table of covariates.

cols

character vector: the columns of dt to test.

Value

the names among cols that are empty.


The definition of an escaped fire

Description

An escape is a burned-area polygon of one of fireCauses whose whole size is at least escapeSizeHa (and larger than one pixel). The same definition must be used to fit the spread, ignition and escape models and to burn and score with them; a fit stores it in its ledger row, and checkEscapeDefinition() compares a ledger row with the settings of a later run.

Usage

escapeDefinition(
  escapeSizeHa = fireSenseEscapeSizeHa,
  fireCauses = fireSenseFireCauses
)

Arguments

escapeSizeHa

Size (ha) of the whole polygon at and above which a fire escaped. Default fireSenseEscapeSizeHa. NA is the definition of a fit made before one was recorded: it is stored as such and checkEscapeDefinition() does not check it.

fireCauses

Cause groups of fireCauseCodes(). Default fireSenseFireCauses.

Value

A one-row data.table with escapeSizeHa (numeric) and fireCauses (the groups, sorted and joined by ","), the columns a ledger row stores.

See Also

escapeFireSet(), checkEscapeDefinition(), escapeDefinitionOf()


The escape definition of a SpaDES run

Description

escapeDefinition() of the current module's escapeSizeHa and fireCauses parameters, after SpaDES.core::paramCheckOtherMods() has checked that every other module of sim that has them has the same values (an error otherwise). Call it in an event of a module that defines both parameters.

Usage

escapeDefinitionOf(sim)

Arguments

sim

A simList.

Value

As escapeDefinition().


Fires that escaped

Description

Fires that escaped

Usage

escapedFires(fires, escapeSizeHa, pixSizeHa, sizeCol = "SIZE_HA")

Arguments

fires

Fire points or polygons (sf, SpatVector or data.frame) with a size column in ha.

escapeSizeHa

Size (ha) a fire must reach to count as escaped.

pixSizeHa

Pixel area (ha). A fire must also be larger than one pixel.

sizeCol

The size column.

Value

The rows of fires that escaped.


Ignitions that escaped: those that became a burned-area polygon of at least escapeSizeHa

Description

The escape model's response. An ignition point escaped if it matches a fire polygon of its year (see ignitionPolygonPairs(): at least escapeSizeHa, larger than one pixel, the point inside it or within maxDistM). A polygon matching several points is one escape: points inside it come before points only near it, then the largest sizeCol (the first of ties); a point is marked at most once. A natural-cause polygon that matches no point is added as an ignition by polygonIgnitions(), and that point then escapes here.

Usage

escapedIgnitions(
  points,
  polys,
  escapeSizeHa,
  pixSizeHa,
  sizeCol = "SIZE_HA",
  maxDistM = 1000
)

Arguments

points

Ignition points (SpatVector or sf) with columns YEAR and sizeCol.

polys

Fire polygons (SpatVector or sf) with column YEAR, or a list of them (one per year, as firePolys is in fireSense; NULL elements are dropped). Any CRS: they are projected to that of points.

escapeSizeHa

Size (ha) a polygon must reach.

pixSizeHa

Pixel area (ha). A polygon must also be larger than one pixel.

sizeCol

The column of points that picks one point per polygon.

maxDistM

Distance (m) from a polygon's edge within which a point outside it still matches it.

Value

Logical, one per row of points: TRUE for an escape.


Functions whose code affects what escapeFireSet() and escapeIgnitionPoints() return

Description

Pass as reproducible::Cache()'s .cacheExtra (see harmonizeFireDataDeps()).

Usage

escapeFireSetDeps()

Value

A list of functions.


The ignitions the ignition and escape models are fitted to, and the hindcast counts

Description

The NFDB points of definition's causes that start in the core, with the escapes of fireSet: the point escapedIgnitions() matches to an escape polygon (in it or within maxDistM, one per polygon) is replaced by that fire's start, so a fire is one ignition and one escape, at the start the spread fit uses. A core-start escape polygon that no point matches gets an ignition at its start too, as polygonIgnitions() adds. Matched points of escape polygons that start in the buffer are dropped with their fire.

Usage

escapeIgnitionPoints(
  points,
  polys,
  fireSet,
  coreRaster,
  definition = escapeDefinition(),
  pixSizeHa,
  coreIs = "ELF",
  maxDistM = 1000,
  sizeCol = polySizeColTxt,
  pointSizeCol = "SIZE_HA",
  polyCauseCol = polyCauseColTxt
)

Arguments

points

NFDB ignition points (SpatVector or sf) with YEAR, CAUSE and pointSizeCol.

polys

The fire polygons fireSet was made from.

fireSet

The escape polygons' starts, from escapeFireSet() with the same definition, polys and sizeCol.

coreRaster, coreIs

As in escapeFireSet(): the core the points must start in.

definition

The escape definition, from escapeDefinition().

pixSizeHa

Pixel area (ha), as in escapedIgnitions().

maxDistM

As in ignitionPolygonPairs().

sizeCol, polyCauseCol

As in escapeFireSet().

pointSizeCol

The column of points that picks one point per polygon (escapedIgnitions()).

Value

A SpatVector of points in the CRS of points: the core points that are not an escape polygon's (escaped FALSE), then one per core-start escape of fireSet (escaped TRUE, SIZE_HA the polygon's whole size, CAUSE the NFDB code of its cause group).


The chance that one ignition escapes, from the expected escapes of an ignited pixel

Description

The escape model is fitted on ignited pixel-years only, so its mean escapeMean is the expected escapes of a pixel that has at least one ignition. With Poisson ignitions of mean ignitionMean, each ignition escapes with probability q = escapeMean * (1 - exp(-ignitionMean)) / ignitionMean, capped at 1: (1 - exp(-ignitionMean)) / ignitionMean is 1 / E[ignitions | ignitions > 0], so the expected escapes of an ignited pixel are escapeMean and never exceed its ignitions. fireSense_burn draws a pixel's escapes as rbinom(ignitions, q), so the expected escapes of a pixel are ignitionMean * q.

Usage

escapeProbPerIgnition(escapeMean, ignitionMean)

Arguments

escapeMean

Numeric: expected escapes of an ignited pixel; NA is 0.

ignitionMean

Numeric: the mean the pixel's ignitions are drawn from. At 0, q is its limit, min(1, escapeMean).

Value

Numeric, q, recycled to the longer argument.

Examples

escapeProbPerIgnition(0.3, c(0.01, 1, 5))

Pixels a fire must burn to count as escaped

Description

The smallest whole number of pixels whose area is at least escapeSizeHa. Shared by the spread fit (.objfunSpreadFit()) and fireSense's burning, so "escaped" means the same in both.

Usage

escapeSizePixels(escapeSizeHa, landscape)

Arguments

escapeSizeHa

Size (ha) a fire must reach to count as escaped.

landscape

A SpatRaster (or anything with terra::res()) in metres.

Value

An integer, at least 1.

Examples

r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 2400, ymin = 0, ymax = 2400)
escapeSizePixels(50, r) # 240 m pixels are 5.76 ha: 9 pixels

Count fires per ELF and merge ELFs with too few

Description

Merges each ELF with too few fires with a neighbour that shares its base (ELFmergePlan()), then each region still smaller than minRegionAreaKm2 with a similar neighbour (ELFsizePlan()). Arctic and Prairie grassland ELFs (ELFsNotFitted()) are neither counted nor merged.

Usage

fewFireELFs(
  ELFs,
  fireYears,
  pixelAreaHa,
  destinationPath,
  nfdbUrl = nfdbPointUrl(),
  nbacUrl = latestNBACUrl(),
  minNaturalIgnitions = 50,
  minFirePolygons = 50,
  escapeSizeHa = 50,
  minEscapes = 5,
  landCoverFile = NULL,
  minRegionAreaKm2 = 35000,
  maxLandCoverDist = 0.35,
  maxBurnRatio = 6
)

Arguments

ELFs

List from makeELFs().

fireYears

Integer vector of years to count fires over.

pixelAreaHa

Area of one pixel of the ELF rasters, in ha.

destinationPath

Directory the fire records are downloaded to.

nfdbUrl, nbacUrl

URLs of the NFDB point and NBAC polygon archives.

minNaturalIgnitions

Fewer natural-cause ignitions than this is too few.

minFirePolygons

Fewer fire polygons than this is too few.

escapeSizeHa

Size (ha) a fire must reach to count as escaped.

minEscapes

Fewer escaped natural fires than this is too few.

landCoverFile

Path to a land-cover map in class codes (SCANFI's), or NULL. With minRegionAreaKm2 it switches on the size rule.

minRegionAreaKm2

After the fire-count plan, regions with a core smaller than this (km2) are merged with a similar neighbour. NULL or NA turns the rule off.

maxLandCoverDist, maxBurnRatio

How similar a neighbour must be for the size rule: largest land-cover (Bray-Curtis) distance and largest burn-rate ratio.

Details

The fire records are read by the fireregimetools loaders, cached on the release, the years and the study area, and the clipped fire polygons of every ELF (ELFfireOverlay(), the slow step) are cached on the ELF maps, the NBAC release and fireYears, so a change to the plan rules does not repeat either.

Value

List: ELFs (the merged maps), status (ELFfitStatus()), plan (the fire-count and size merges and the skips, in ELFmergePlan()'s format) and excluded (names of ELFs not fitted).


Cause groups and the NFDB / NBAC values in them

Description

The one place that says which CAUSE (NFDB points) and FIRECAUS (NBAC polygons) values are which cause, so that fitting (fireSense_dataPrepFit) and validation (hindcastObserved(), ELFfireCounts()) agree. natural is NFDB N (and L, in older releases) and NBAC Natural. unknown is NFDB U and NBAC Undetermined (NBAC 20260513; Unknown in case a release spells it so), and a blank or missing cause, as neither source says what started the fire. human is NFDB H (and H-PB, prescribed burn) and NBAC Human; other is NFDB RE (re-burn). NFDB 20260811 has only H, N and U; NBAC 20260513 only Human, Natural and Undetermined.

Usage

fireCauseCodes(groups, source = c("nfdb", "nbac"))

Arguments

groups

Cause groups: any of natural, unknown, human, other.

source

"nfdb" (values of CAUSE) or "nbac" (values of FIRECAUS).

Value

The values in groups; NA is among those of unknown.


Climate layers needed by the fire models

Description

Climate layers needed by the fire models

Usage

fireClimateLayers(
  climateVariablesForFire,
  historicalYears,
  projectedYears = NULL
)

Arguments

climateVariablesForFire

List with ignition and spread character vectors.

historicalYears

Years of historical climate: the fire years for a fit, the simulated years with historical climate for prediction. None (NULL or empty) requests no historical climate; with no projected years either, the result is an empty list.

projectedYears

Projected years, from canClimateProjectedYears(). Projected climate is requested for these years only; none (NULL or empty) requests no projected climate.

Value

A list for sim$climateVariables, as built by climateData::climateLayers().


Pixel IDs burned in each year

Description

Turns fire polygons or a fire-year raster into the per-year pixel lists youngAgeAtYear() reads. Polygons are rasterized at cell centres, as makeTSD() does.

Usage

firePixelsByYear(firePolys = NULL, fireRaster = NULL, template = NULL)

Arguments

firePolys

list named by year ("year2001") of SpatVectors, or NULL entries for years without fires.

fireRaster

SpatRaster whose values are fire years; an alternative to firePolys, used when both are given. It holds one fire per pixel, so earlier fires on the same pixel are not seen.

template

SpatRaster giving the pixels; required with firePolys. Given with fireRaster, it must have the same geometry (stops otherwise).

Value

list named by year ("2001") of integer pixelIDs; years with no burned pixel are absent.


Path to the shapefile in a fire-record archive

Description

Downloads the archive if needed. The shapefile's name carries the release, so callers key their Cache on the name.

Usage

fireRecordShapefile(url, destinationPath, ...)

Arguments

url

URL of the archive.

destinationPath

Directory to download and extract into.

...

Passed to reproducible::preProcess().

Value

Character path(s) of the .shp file(s) in the archive.


Get current state of FireSense Fit parameters as a map

Description

Download the FireSense parameter object, strip the list columns and convert to a SpatVector or SpatRaster.

Usage

fireSenseCloudParameters(
  url = paste0("https://drive.google.com/file/d/",
    "1oJX7V5wPSj49C6wt59yD9RBplfZ7Cp-f/view?usp=drive_link"),
  targetFile = "fireSenseParams.rds",
  destinationPath = ".",
  useCache = TRUE
)

Arguments

url

Http url of the fireSense object with parameters on Google Drive: either the file itself (the default) or the folder that contains targetFile.

targetFile

The name of the file to find when url is a folder. The default is correct for fireSense parameters.

destinationPath

A path where a copy of the downloaded file is saved.

useCache

Ignored. Kept so existing calls still work: the file is always downloaded fresh.

Details

The file is downloaded from Google Drive on every call, so the result is always the current state of the shared parameter file, never a copy left on disk by an earlier call.

Value

The object and the rds file saved to destinationPath.

See Also

fireSenseCloudParametersMap()


Get current state of FireSense Fit parameters as a map

Description

Download the FireSense parameter object, strip the list columns and convert to a SpatVector or SpatRaster. If plot = TRUE, this will also download a map that represents the forested lands of canada, to be plotted on the plot device with the fireSense parameter ELFs that currently have estimated parameters.

Usage

fireSenseCloudParametersMap(rasterize = FALSE, plot = TRUE, res = 5000, ...)

Arguments

rasterize

Logical. If TRUE, then the function returns the rasterized map. FALSE, the default, is a SpatVector.

plot

Logical. If TRUE, the default, then the map will be plotted to device.

res

The resolution of the raster if rasterize = TRUE

...

Other parameters passed to fireSenseCloudParameters

Value

The map, either SpatRaster or SpatVector

See Also

fireSenseCloudParameters()


Create FireSense Input Covariates

Description

Constructs pixel-level covariates required by FireSense (e.g., mutually exclusive fuel-class indicators, transformed by logMinB, and a youngAge indicator) by combining cohort-derived fuel classes with land cover, flammability, and (optionally) non-forest time-since-disturbance.

Usage

fireSenseCovariatesCreate(
  cohortData,
  pixelGroupMap,
  flammableRTM,
  sppEquiv,
  landcoverDT,
  fuelClassCol,
  requiredFuelClasses = NULL,
  sppEquivCol,
  missingLCCgroup,
  nonForestedLCCGroups,
  nonForest_timeSinceDisturbance,
  cutoffForYoungAge,
  nonForestCanBeYoungAge,
  studyAreaName,
  useCache = TRUE,
  rstLCC = NULL,
  treedWetlandLCC = 81,
  treedWetland = TRUE,
  fuelCovariates = c("species", "domSecWetland"),
  domClass = NULL,
  secClass = NULL,
  youngAge = TRUE,
  fuelClassTable = NULL
)

Arguments

cohortData

data.table (or similar) of stand/age cohorts used to derive fuel classes.

pixelGroupMap

A raster (SpatRaster) or mapping structure linking cohort groups to pixels.

flammableRTM

A raster (SpatRaster) mask of flammable pixels (non-flammable typically NA/0).

sppEquiv

Species equivalency table used to map species codes to fuel-class groupings.

landcoverDT

data.table with at least pixelID and one or more land-cover indicators (e.g., logical or numeric columns for LCC groups) used in the covariate set.

fuelClassCol

Character name of the fuel-class column produced/expected by sppEquiv.

requiredFuelClasses

A character vector of all the fuel classes that are expected. This is needed because a fuel class may disappear (e.g., Popu_tre) due to succession, causing a downstream failure because the prediction model requires values for it.

sppEquivCol

Character name of the species-equivalency column in sppEquiv.

missingLCCgroup

A single unquoted column name (passed to data.table:::= via eval) that will be set to 1 where all covariates are zero (forested LCC absent from cohortData).

nonForestedLCCGroups

Named vector or list where names correspond to the non-forest land-cover columns in landcoverDT (used to detect non-forest pixels).

nonForest_timeSinceDisturbance

A raster/vector of time-since-disturbance (TSD) for non-forest pixels; indexed by pixelID and used when nonForestCanBeYoungAge = TRUE.

cutoffForYoungAge

Numeric threshold (years). Pixels with TSD ≤\le this value are considered youngAge.

nonForestCanBeYoungAge

Logical. If TRUE, non-forest pixels can be flagged as youngAge based on nonForest_timeSinceDisturbance and cutoffForYoungAge.

studyAreaName

Character tag used for caching/user tags.

useCache

Logical. If TRUE, enable caching in Cache() calls.

rstLCC

Optional land-cover SpatRaster on the same grid as pixelGroupMap. When given and fuelCovariates = "species", a treedWetland column (see treedWetlandTxt) is added: 1 where the land cover is treedWetlandLCC. When fuelCovariates = "domSecWetland", all tree AGB (all fuel classes) on those pixels is moved into treedWetland_agb (see treedWetlandAgbTxt) instead, and removed from ⁠dom_agb_*⁠/⁠sec_agb_*⁠ there.

treedWetlandLCC

Land-cover code(s) of treed wetland. Default 81 (NTEMS; also what makeFireSenseLCC() assigns on SCANFI land cover from the wetland layer).

treedWetland

Logical. TRUE (default): treed wetland is a covariate when rstLCC is given, as described there. FALSE: it is not, and its tree AGB stays in the fuel columns like any other forest. A fit sets this once per ELF (fireSense_dataPrepFit's minCovariateProp: too little treed wetland to estimate its coefficient); a prediction follows the fit.

fuelCovariates

"species" (default; one covariate column per fuel class, as assignedFuelClass in sppEquiv) or "domSecWetland": only the AGB columns ⁠dom_agb_<domClass>⁠ and ⁠sec_agb_<secClass>⁠ (the ELF's two fuel classes with the most total treed AGB) and, when rstLCC is supplied, treedWetland_agb. AGB of any other fuel class is not a covariate.

domClass, secClass

Only used when fuelCovariates = "domSecWetland". The fuel classes to use for ⁠dom_agb_*⁠/⁠sec_agb_*⁠. NULL (the default) chooses them from this call's own data (highest total AGB first); a prediction should instead pass the classes the fit chose (e.g. from chooseDomSecFuelClasses()), so the columns it builds match the fitted model's terms even when a different class dominates the prediction area. secClass = NA_character_ means no secondary class (fewer than two fuel classes present).

youngAge

logical. TRUE (default): build youngAge from cohort ages and (with nonForestCanBeYoungAge) non-forest time since disturbance, and zero fuel, non-forest land cover and treed wetland where it is 1. FALSE: no youngAge column and nothing zeroed, so the caller can resolve youngAge per year (see youngAgeAtYear()) and apply makeMutuallyExclusive() itself; cutoffForYoungAge and nonForestCanBeYoungAge are then unused.

fuelClassTable

Optional, the result of cohortsToFuelClasses(..., asTable = TRUE) for this call's cohortData, pixelGroupMap, flammableRTM, landcoverDT, sppEquiv, sppEquivCol, fuelClassCol, requiredFuelClasses and cutoffForYoungAge. It is used instead of building it again, so a caller making several covariate sets (e.g. "species" and "domSecWetland") from the same cohorts builds the fuel classes once. It is copied, not modified. With youngAge = FALSE it must have been made with cutoffForYoungAge = -1.

Details

The function:

  1. Calls cohortsToFuelClasses() to derive fuel-class rasters from cohorts.

  2. Converts these to a long data table keyed by pixelID and joins to landcoverDT.

  3. Verifies there are no NA values across covariate columns and raises an error otherwise.

  4. Marks pixels with all-zero covariates as the provided missingLCCgroup.

  5. Enforces mutual exclusivity among the specified fuel/landcover columns.

  6. Applies logMinB to all fuel-class columns (excluding youngAge).

  7. If nonForestCanBeYoungAge = TRUE, augments youngAge for non-forest pixels using nonForest_timeSinceDisturbance and the cutoffForYoungAge.

  • All covariate columns must be non-NA; the function stops with an error if any NA are detected after joining fuelClasses and landcoverDT.

  • Pixels where all covariates sum to zero are flagged by setting missingLCCgroup := 1.

  • When nonForestCanBeYoungAge = TRUE, youngAge for non-forest is derived using nonForest_timeSinceDisturbance and cutoffForYoungAge. Any existing youngAge from fuel classes is combined with this non-forest contribution.

  • Once youngAge is final, mutual exclusivity is enforced via makeMutuallyExclusive() using all fuel-class columns, the land-cover columns (excluding pixelID) and treedWetland (if rstLCC is supplied); youngAge is made exclusive to them.

  • Fuel-class columns (excluding youngAge) are transformed with logMinB.

  • When fuelCovariates = "domSecWetland", the per-species fuel-class columns are collapsed to dom_agb_*, sec_agb_* (other classes are dropped; and treedWetland_agb, if rstLCC is supplied) before mutual exclusivity and logMinB are applied to them, exactly as for the per-species columns.

Value

A data.table named spreadCovariates containing one row per pixelID, with:

  • Mutually exclusive fuel-class covariate columns (log-transformed by logMinB).

  • Land-cover indicator columns from landcoverDT.

  • A youngAge indicator (possibly augmented by non-forest TSD logic).

Expectations/Assumptions

  • fuelClasses returned by cohortsToFuelClasses() includes one column per fuel class, plus optionally youngAge, and a cell (renamed to pixelID here).

  • landcoverDT must contain a pixelID column aligned to rasters by cell index.

  • nonForestedLCCGroups names correspond to column names in landcoverDT.

  • nonForest_timeSinceDisturbance is indexable by pixelID (e.g., vector aligned to raster cells).

See Also

cohortsToFuelClasses, makeMutuallyExclusive, logMinB, putBackIntoRaster, calcNonForestYoungAge

Examples

## Not run: 
covs <- fireSenseCovariatesCreate(
  cohortData = cohortsDT,
  pixelGroupMap = pgRas,
  flammableRTM = flammRas,
  sppEquiv = sppEquivDT,
  landcoverDT = landcoverDT,
  fuelClassCol = "fuelClass",
  sppEquivCol = "sppEquivCol",
  missingLCCgroup = "LCC_missing",
  nonForestedLCCGroups = c(NonForest = 1),
  nonForest_timeSinceDisturbance = NF_TSD,
  cutoffForYoungAge = 20,
  nonForestCanBeYoungAge = TRUE,
  studyAreaName = "MyArea",
  useCache = TRUE
)

## End(Not run)

Non-flammable land-cover codes for the FireSense land cover

Description

The single source of truth for which codes in the land cover built by makeFireSenseLCC() are non-flammable. fireSense_dataPrepFit and fireSense_dataPrepPredict take their nonflammableLCC parameter default from this constant, and makeFireSenseLCC() and ELFflammableArea() take theirs from it too, so the land cover a fit/prediction is built from and the land cover it is run on cannot silently disagree on what counts as flammable.

Usage

fireSenseNonflammableLCC

Format

numeric vector, c(0, 20, 30, 31, 32, 33).

Details

Every code below comes from makeFireSenseLCC()'s two land-cover sources, LandR::prepInputs_NTEMS_LCC_FAO() and LandR::prepInputs_SCANFI_LCC_FAO() (documented in the "Data codes" comment in LandR/R/prepInputs_NTEMS.R and LandR/R/maps.R), plus SCANFI's raw-class recode in LandR::convert_SCANFI_LCC_codes():

  • 0: no data / unclassified – non-flammable.

  • 20: water – non-flammable.

  • 30: rock/exposed land, SCANFI's combined rock+exposed class (LandR::convert_SCANFI_LCC_codes()) – non-flammable. This was missing from the modules' old default, so SCANFI-derived rock entered fits as flammable non-forest.

  • 31: snow/ice (NTEMS) – non-flammable.

  • 32: rock/rubble (NTEMS) – non-flammable.

  • 33: exposed/barren land (NTEMS) – non-flammable.

  • 40: bryoids – flammable ground cover, not included.

  • 50: shrubs – flammable, not included.

  • 80, 81: wetland, wetland-treed – flammable, not included.

  • 100: herbs – flammable, not included.

  • 210, 220, 230: coniferous, broadleaf, mixedwood forest – flammable, not included.

  • 240: FAO-forest disturbed code (disturbedCode in LandR::prepInputs_SCANFI_LCC_FAO()/LandR::prepInputs_NTEMS_LCC_FAO()) – flammable forest, not included.


The phases a fireSense job can be split into

Description

"all" fits if the ELF has no fit, then predicts. "inputs" builds every input and cache and stops before the spread fit (the run event). "fit" fits if the ELF has no fit, then stops. See phaseEvents() and runJob().

Usage

fireSensePhases

Defaults shared by the fireSense modules and functions

Description

The fireSense_dataPrepFit and fireSense_dataPrepPredict modules each have parameters with these names, and a fit and the predictions made from it are only consistent if both use the same values; fireSense_spreadFit takes its ⁠runawayEdge*⁠ defaults from here too. The modules take their parameter defaults from these constants, as they do nonflammableLCC from fireSenseNonflammableLCC, and the functions here that take the same arguments default to them too.

Usage

fireSenseForestedLCC

fireSenseYoungAgeCutoff

fireSenseNonForestCanBeYoungAge

fireSenseFlammabilityThreshold

fireSenseFuelClassCol

fireSenseIgAggFactor

fireSenseSCANFIVersion

fireSenseRunawayEdgeFrac

fireSenseRunawayEdgeMin

fireSenseFireCauses

fireSenseEscapeSizeHa

fireSenseELFCoreValue

Format

Vectors of length 1, except fireSenseForestedLCC (numeric, length 5) and fireSenseFireCauses (character, length 2).

Details

  • fireSenseForestedLCC: land-cover codes treated as forest, in the land cover built by makeFireSenseLCC(): treed wetland (81), coniferous (210), broadleaf (220), mixedwood (230) and disturbed forest land (240).

  • fireSenseYoungAgeCutoff: age (years) at and below which a pixel is youngAge.

  • fireSenseNonForestCanBeYoungAge: whether burned non-forest is youngAge until it passes fireSenseYoungAgeCutoff.

  • fireSenseFlammabilityThreshold: minimum proportion of flammable fine-resolution land cover for a coarser pixel to be flammable.

  • fireSenseFuelClassCol: the column of sppEquiv that defines fuel classes.

  • fireSenseIgAggFactor: aggregation factor (cells per side) for the ignition and escape covariates.

  • fireSenseSCANFIVersion: the SCANFI land-cover version makeFireSenseLCC() reads for non-forest land cover (passed to LandR::prepInputs_SCANFI_LCC_FAO()'s dataVersion).

  • fireSenseRunawayEdgeFrac, fireSenseRunawayEdgeMin: the defaults of runawayEdgeFrac and runawayEdgeMin of .objfunSpreadFit() and runDEoptim(): a simulated fire is a runaway when it burns at least max(runawayEdgeMin, ceiling(runawayEdgeFrac * n)) of the n pixels of its buffer's edge ring.

  • fireSenseFireCauses: the cause groups of the fires the ignition, escape and spread models are fitted to, and the observed fire is counted from (c("natural", "unknown"); groups of fireCauseCodes()). It is the default of fireCauses in fireSense_dataPrepFit and fireSense_summary, which check that they agree (SpaDES.core::paramCheckOtherMods()), and of the readers in fireSimulator_validation. hindcastObserved() and ELFfireCounts() keep fireCauses = NULL (the naturalCauses they are given), so they stay usable for other models.

  • fireSenseELFCoreValue: the value of the core cells of a one-ELF raster (2; the buffer is 1), e.g. rasterToMatchLargeELF, the default coreValues of fireStarts().

  • fireSenseEscapeSizeHa: the whole-polygon size (ha) at and above which a fire escaped (50), the default of escapeDefinition().


Hard-coded name/text constants

Description

Character (or character-vector) constants used across the package and downstream modules to keep column names, identifiers, and other free-text tokens consistent. All such constants end in Txt.

Usage

yearSpreadSDTxt

fireSpreadSDTxt

spreadRandomEffectTxt

Format

  • polygonIDTxt: character(1). Name of the polygon-ID column (currently "polygonID").

  • nonNFColNamesTxt: character vector of bookkeeping column names that are not non-forest landcover classes (currently "pixelID" and polygonIDTxt); used with base::setdiff() to select the non-forest landcover columns when summing/aggregating across rows (see makeTSD()).

  • yearTxt: character(1). Token used as a year-column name or as a prefix on year-suffixed layer/column names (currently "year").

  • youngAgeTxt: character(1). Name of the "young-age" cohort class (currently "youngAge").

  • burnableHaTxt: character(1). Name of the column of spreadFirePoints holding each fire's burned area (ha) on the pixels the spread fit can burn, the fit's target size (currently "BURNABLE_HA").

  • ignitionsTxt: character(1). Name of the ignitions column (currently "ignitions").

  • escapesTxt: character(1). Name of the escapes column (currently "escapes").

  • coreFractionTxt: character(1). Name of the column of the ignition covariates with the share of a coarse pixel in the ELF's core (currently "coreFraction"). An exposure, not a covariate: rescaleCovariates() does not scale it.

  • polyCauseColTxt: character(1). The cause column of NBAC fire polygons (currently "FIRECAUS").

  • polySizeColTxt: character(1). The column of NBAC fire polygons with the whole fire's size in ha (currently "POLY_HA").

  • spreadRandomEffectTxt: character(2). Names of the spread fit's random-effect sds, in the order they end par (.objfunSpreadFit()): "fireSpreadSD" (per fire), then "yearSpreadSD" (per year). They are not covariate coefficients, so a predictor drops them from the fitted parameters.

  • fireSpreadSDTxt, yearSpreadSDTxt: character(1). The two names of spreadRandomEffectTxt, to test for one of them (spreadRandomEffectArgs()).

  • ignitionObjectiveTxt: character(1). The xgboost objective the ignition and escape models are fitted with (currently "count:poisson"); read it back from a fitted model with xgbObjective().

  • spreadFitAdditionalColNamesTxt: character vector of extra simList-slot/column names attached to spread-fit outputs ("numIterations", "objFunVal", "params", "sppEquiv", "nonForestedLCCGroups", "missingLCCgroup", "covMinMax_spread"). covMinMax_spread is what prediction needs to rescale covariates exactly as the fit did.

  • ignitionFitAdditionalColNamesTxt: character vector of the list-column names attached to ignition-fit ledger rows ("fireSense_IgnitionFitted", "fireSense_EscapeFitted").

  • spreadInterceptTxt: character(1). Name of the spread model's intercept, in a formula's design (spreadDesignCols()), in lower/upper and in a ledger row's params (currently "(Intercept)", what stats::lm() calls it).

  • spreadFitCovCentreTxt: character(1). Name of the ledger column that holds the covariate centres of a fit made with an intercept (currently "covCentre_spread"). It is not in spreadFitAdditionalColNamesTxt: a fit without an intercept writes no such column.

  • spreadLinkTxt, spreadFitClimateRefTxt, spreadFitPowerLawGammaTxt, spreadFitPowerLawShapeTxt: character(1) each. Names of the ledger columns a fit made with a non-default spreadLink writes: "spreadLink" (holding "climateOutside" or "powerLaw"), "climateRef_spread" (the fit's climate reference from spreadClimateRef(), with "climateOutside") and "powerLawGamma_spread" (the fit's gamma, with "powerLaw") and "powerLawShape_spread" (its shape, written when not 1; a row without it has shape 1), so prediction applies the same link (spreadProbFromCovs()). A fit with the default "ceiling" link writes none of them; a row without them, every row written before, predicts as it always did.

  • spreadFitLowerAsymptoteTxt, spreadFitRichardsNuTxt: character(1) each. Names of the ledger columns of a fit with "powerLawSmooth" or "richards": "lowerAsymptote_spread" (the link's lower asymptote, both links) and "richardsNu_spread" (nu of "richards"). A "powerLawSmooth" row also has gamma and shape, as "powerLaw".

  • spreadRichardsNu: numeric(1). The default nu of the "richards" link, 0.5 (fireSense_spreadFit's richardsNu).

  • spreadLinearLinks: character. The links that map the linear predictor x itself to p (the year effect is added to x): "powerLaw", "powerLawSmooth" and "richards".

  • spreadPowerLawLinks, spreadAsymptoteLinks: character. The links of spreadLinearLinks that use the power law's gamma and shape (and so its calibration, calibratePowerLaw()): "powerLaw" and "powerLawSmooth"; and those that have a lower asymptote lowerAsymptote: "powerLawSmooth" and "richards".

  • spreadLinkParNames: named list, one element per link of spreadLinearLinks: the names of its parameters, in the order of SpaDES.tools::spreadCpp(linkPars =) (linearLinkPars()).

  • spreadLinkOptions: character vector of the values fireSense_spreadFit's spreadLink can take: "ceiling" (the default: climate inside the logistic, under maxAsymptote), "climateOutside", "powerLaw" (powerLawLink()), "powerLawSmooth" (powerLawSmoothLink()) and "richards" (richardsLink()).

  • spreadPowerLawGamma: numeric(1). The default gamma of the "powerLaw" link, 1.9, from a percolation calibration on a uniform landscape. fireSense_spreadFit calibrates gamma on each ELF's own flammable map instead (calibratePowerLaw()), unless a number is given.

  • spreadLowerAsymptoteMin: numeric(1). The smallest lowerAsymptote (checkLinkParams()), 0.001: with 0 the spread probability of a cell can be about 1e-9, and a fire under its minSize retries for about 1 / p generations.

  • spreadRichardsB: numeric(1). The fixed slope B of the "richards" link, 1 / spreadPowerLawGamma.

  • spreadPowerLawShape: numeric(1). The default shape of the "powerLaw" link, 1 (the exponential approach to pc); fireSense_spreadFit's powerLawShape. Fixed, not fitted.

  • spreadFitPowerLawPc50Txt, spreadFitPowerLawR2Txt: character(1) each. Names of the ledger columns that hold, with "powerLaw" and a calibrated gamma, the calibration's p50 (the spread probability at which half the fires run away, to compare with the fitted p_c) and the R2 of its gamma regression ("powerLawPc50_spread", "powerLawR2_spread").

  • spreadFitPowerLawPcMarginTxt: character(1). Name of the ledger column that holds the margin added to p50 for the upper bound of p_c (powerLawPcBounds(); "powerLawPcMargin_spread"), so the bounds a fit used can be recovered.

  • spreadFitInSampleSizesTxt: character(1). Name of the ledger column that holds a fit's in-sample fire-size validation ("inSampleSizes_spread"): a list of sizes, the one-row scoreFireSizes(), and byYear, 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.

  • treedWetlandAgbTxt: character(1). Name of the pooled treed-wetland biomass column built by fireSenseCovariatesCreate(fuelCovariates = "domSecWetland") (currently "treedWetland_agb").


One start per fire polygon, and whether it is in the core

Description

fireStarts() gives every polygon of polys its start: the start in starts with the same YEAR and idCol (the starts the spread fit was given, e.g. spreadFirePoints from harmonizeFireData()), or, with starts = NULL, the polygon's centroid moved to the nearest burnable pixel of the fire by the functions harmonizeFireData() uses (harmonizeBufferAndPoints(), then cleanUpSpreadFirePoints()), year by year. A polygon with no burnable pixel has no start and is left out. escapeFireSet() does the same for the escape polygons of definition only.

Usage

fireStarts(
  polys,
  flammableRTM,
  coreRaster = NULL,
  starts = NULL,
  idCol = NULL,
  sizeCol = polySizeColTxt,
  polyCauseCol = polyCauseColTxt,
  coreIs = "ELF"
)

escapeFireSet(
  polys,
  flammableRTM,
  coreRaster = NULL,
  definition = escapeDefinition(),
  starts = NULL,
  idCol = NULL,
  sizeCol = polySizeColTxt,
  polyCauseCol = polyCauseColTxt,
  coreIs = "ELF"
)

Arguments

polys

Fire polygons (SpatVector or sf, or a list of them, one per year) with column YEAR.

flammableRTM

SpatRaster of the burnable pixels (1; 0 or NA cannot burn) of the whole landscape, core and buffer. Its grid gives pixelID and the burnable area.

coreRaster

SpatRaster of the core, read by inELFCore() (with coreIs), e.g. rasterToMatchLargeELF (2 core, 1 buffer). NULL makes every start a core start.

starts

NULL, or start points (SpatVector or sf, or a list of them) sharing YEAR and idCol with polys.

idCol

The fire ID column of polys and starts; needed with starts, and copied to the result if given.

sizeCol

Column of polys with the whole fire's size (ha); default polySizeColTxt. A polys without it is measured (terra::expanse()).

polyCauseCol

Column of polys holding the cause; default polyCauseColTxt.

coreIs

What coreRaster is, as in inELFCore(): "ELF" (default; core fireSenseELFCoreValue, buffer 1) or "mask".

definition

The escape definition, from escapeDefinition().

Value

A SpatVector of points in the CRS of flammableRTM, one per polygon with a start: YEAR, .poly (the polygon's row in polys), idCol (if given), polyHa (the whole polygon), burnableHa (its burnable pixels, core and buffer: the area the simulation can burn), cause (if polys has polyCauseCol), pixelID (the start's cell of flammableRTM) and core (logical: the start is in the core).


Will this job read the data prepared for a fit?

Description

The one rule fireSense_dataPrepFit and fireSense_spreadFit share for skipUnusedFitPrep: a job that only predicts from the ledger's fit does not need the spread covariates. A job needs them when it holds out a fold (heldOutFold), validates or profiles (mode), always fits (doFit TRUE), or fits when the ledger has no fit (doFit NA and no ledger fit, or not known). doFit FALSE never fits, so it does not.

Usage

fitDataNeeded(doFit, heldOutFold = NA, mode = NULL, hasLedgerFit = NA)

Arguments

doFit

NA, TRUE or FALSE, as returned by resolveDoFit().

heldOutFold

NA (default), 1L or 2L.

mode

character, fireSense_spreadFit's mode; NULL if that module is not in the project.

hasLedgerFit

logical: does the ledger hold a fit for this polygon? NA (default): not known, so doFit = NA may fit.

Value

logical, length one.


Diagnostics of a fitted spread model

Description

The checks made by hand on the FireSense phase-2 fits (September 2026), as functions, so that fireSense_spreadFit can make them after every fit.

Usage

spreadProbSummary(p, ceiling, tol = 0.002, binWidth = 0.001)

combineSpreadProbSummaries(x)

simulateFireSizes(
  pop,
  fn = .objfunSpreadFit,
  fnArgs = list(),
  cl = NULL,
  seed = 1L
)

scoreFireSizes(
  sims,
  probs = c(0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99),
  largeFire = 174
)

scoreFireSizesByYear(sims)

linkSaturation(sims, probsP = c(0.01, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99))

coefIdentifiability(pop, lower, upper, zMin = 1)

profileCoefficients(
  best,
  pop,
  fn = .objfunSpreadFit,
  reps = 10L,
  cl = NULL,
  seed = 1L,
  fnArgs = list(),
  coefs = covariateCoefs(names(best)),
  probsPop = c(0.05, 0.25, 0.5, 0.75, 0.95),
  at = NULL
)

identifiedInIsolation(ident, profile, seMult = 2)

fitConvergence(DE)

Arguments

p

Numeric. Spread probabilities.

ceiling

The link's upper asymptote, maxAsymptote.

tol

A probability within tol of ceiling counts as at the ceiling.

binWidth

Width of the bins in which p is counted, so summaries of different years can be added up and still give quantiles.

x

A list of spreadProbSummary() results with the same binWidth.

pop

A matrix or data.table of parameter sets, one per row, with column names.

fn

The objective; .objfunSpreadFit().

fnArgs

Named list of further arguments to fn, as for rescorePopulation(). The fit data (landscape, annualDTx1000, ...) are taken from the workers' global environment if absent, so a held-out prediction passes its own years here.

cl

A cluster, or NULL to run in this session.

seed

Every parameter set is evaluated with the same seeds (seed, or seed + i for replicate i of the profile), so differences between them are not luck.

sims

The output of simulateFireSizes().

probs

Quantiles of fire size to compare.

largeFire

Size in pixels above which a fire counts as large (174 pixels = 1000 ha at 5.76 ha per pixel).

probsP

Quantiles of spread probability to report.

lower, upper

The bounds the fit used, named as the columns of pop.

zMin

The zPop at or above which the population is taken to pin a coefficient's sign.

best

Named numeric: the parameter set to profile around, normally the best member by replicated mean (bestByReplicatedMean()).

reps

Evaluations of each profile point.

coefs

The coefficients to profile; all covariate coefficients by default.

probsPop

Population quantiles to evaluate each coefficient at, besides 0.

at

NULL, or a named list of the values to evaluate coefficients at, e.g. list(agb_pine = -20:20). A coefficient named in it is evaluated at exactly those values, instead of at 0 and the population quantiles, so a profile can go past the bounds the population was drawn in. pop is not used for those coefficients, and may be NULL when every coefficient in coefs is in at.

ident

The output of coefIdentifiability().

profile

The output of profileCoefficients().

seMult

Dropping a coefficient must worsen the objective by more than seMult standard errors.

DE

The output of runDEoptim(): a list of DEoptim results, one per chunk of generations.

Details

  • simulateFireSizes() simulates the observed fires from each of several parameter sets, with the "too burny" gate lifted, and returns the simulated sizes.

  • scoreFireSizes() compares those with the observed sizes: per fire, per year, and by quantile. It never uses the objective's value.

  • linkSaturation() reports how many pixel-years sit at the spread-probability ceiling. When most do, fire size is decided by the ceiling alone ("too many medium, too few large fires").

  • coefIdentifiability() measures, for each covariate coefficient, how tightly the final population pins it down.

  • profileCoefficients() sets each coefficient in turn to 0 and to values across the population's range, other coefficients held at the best member, and re-scores.

  • identifiedInIsolation() combines the two: a coefficient is identified in isolation when the population pins its sign (zPop >= zMin) and dropping it (setting it to 0) makes the objective clearly worse.

  • fitConvergence() summarises the objective across the fit's generations.

Value

spreadProbSummary(): a list with n, atCeiling (a count), counts (per bin) and binWidth.

combineSpreadProbSummaries(): their sum, as one summary.

simulateFireSizes(): a data.table, one row per parameter set x fire x replicate: member (row of pop), yr, rep, initialLocus, ids, simulated sim and observed size, in pixels. A year the objective will not simulate even with its gate lifted keeps its fires with sim NA. attr(, "spreadProb") is a list of spreadProbSummary()s, one per member.

scoreFireSizes(): a one-row data.table. fireBias and fireRMSE are the mean and root mean square of log10(simulated / observed) per fire (0.3 is a factor of 2); ⁠year*⁠ the same for annual area burned; yearIn90pct the share of years whose observed area lies within the 5-95% range of simulated years; simsOver10xObs and simsUnderTenthObs the share of simulated fires more than 10 times too large or too small; AD the Anderson-Darling statistic between simulated and observed sizes; ⁠qObs_*⁠/⁠qSim_*⁠ the quantiles in probs.

The remaining columns score single runs, a run being one member x rep: one simulated history over the years it has. ⁠areaRun_*⁠ is each run's total simulated area burned over its observed total and ⁠top10Run_*⁠ the same for the 10 largest fires (all fires if fewer than 10): ⁠_median⁠, ⁠_lo⁠ and ⁠_hi⁠ (the 2.5% and 97.5% quantiles) across runs, and ⁠_obsRank⁠ the share of runs below the observed value (0.5: the observed value is typical; near 0 or 1: it is out of reach of single runs). nRuns is the number of runs.

scoreFireSizesByYear(): a data.table, one row per year with a simulation: yr, obs (the observed area burned, in pixels), simMedian and the 2.5% and 97.5% quantiles simLo and simHi of the simulated area over runs (a run being one member x rep), to report annual-area bias and skill.

linkSaturation(): a data.table, one row per member: pixelYears, propAtCeiling and the spread-probability quantiles ⁠p_*⁠ (bin midpoints).

coefIdentifiability(): a data.table, one row per covariate coefficient: the population median popMedian; spread90, the 5-95% range across members as a share of the bound width; atBound, the share of members within 5% of the width from a bound; ⁠zPop = |popMedian| / ((q95 - q5) / 3.29)⁠, the median in units of the population's spread (a normal's 5-95% range is 3.29 sd); rSlope, the correlation across members with hillSlope1 (the link uses ⁠hillSlope1 * X b⁠, so the two trade off by construction; NA when the population has no hillSlope1 column, as now that it is fixed at 1); and signPinned = zPop >= zMin. With three runs each of four ELFs, zPop >= 1 found the coefficients whose sign every run agreed on with 94% precision and 44% recall.

profileCoefficients(): a data.table, one row per coefficient x profile point: coef, at (its value there; isZero marks the drop test), mean of the objective over reps, and delta and deltaSE: the mean paired difference from best (same seeds) and its standard error. A positive delta means the point fits worse than best. A reference row (coef = "") holds best itself.

identifiedInIsolation(): ident with dropDelta, dropDeltaSE, dropMatters and identified (signPinned & dropMatters) added.

fitConvergence(): a data.table, one row per chunk: generation (its last), bestval (the best value so far) and the median and standard error of the median of the population's values (fail values of 1e6 and above left out).


The Google Drive folder of the shared fit ledgers

Description

The folder that holds the spread-fit and ignition-fit ledger files (see spreadFitFilenameFor() and ignitionFitFilenameFor()). The modules that write and read the ledgers (fireSense_spreadFit, fireSense_ignitionFit, fireSense_dataPrepFit, fireSense_ELFs) use these as the defaults of their spreadFitGoogleDriveFolder and ignitionFitGoogleDriveFolder parameters, and latestSpreadFits() and latestIgnitionFits() use them as the default cloudFolderID.

Usage

spreadFitLedgerFolder(
  folder = if (isTRUE(testing)) getOption("fireSenseUtils.spreadFitLedgerFolderTesting",
    "https://drive.google.com/drive/folders/1nqSVuGRYxIvcgZMn7TIbn5HfRiUHR2xq") else
    getOption("fireSenseUtils.spreadFitLedgerFolder",
    "https://drive.google.com/drive/folders/1X9-mRjyLMNpgkP_cfqhbr_AQEPOsVCHf"),
  testing = FALSE
)

ignitionFitLedgerFolder(
  folder = if (isTRUE(testing))
    getOption("fireSenseUtils.ignitionFitLedgerFolderTesting",
    spreadFitLedgerFolder(testing = TRUE)) else
    getOption("fireSenseUtils.ignitionFitLedgerFolder", spreadFitLedgerFolder()),
  testing = FALSE
)

Arguments

folder

The folder (url or id). An explicit value wins over the option.

testing

Logical. TRUE: the folder's "testing" subfolder, for experiment fits.

Value

A character string, the folder's url or id.

Options

To use another folder, set an option; every module and function then follows it.

fireSenseUtils.spreadFitLedgerFolder

the spread-fit ledger folder (url or id). Default: the shared folder of the fireSense project.

fireSenseUtils.ignitionFitLedgerFolder

the ignition-fit ledger folder (url or id). Default: the value of the spread-fit ledger folder, so one option moves both.

Experiments

Fits made to try something (a new objective, weights, a data change) go in the folder's subfolder "testing": testing = TRUE gives it (options fireSenseUtils.spreadFitLedgerFolderTesting, fireSenseUtils.ignitionFitLedgerFolderTesting). An experiment sets it as the modules' spreadFitGoogleDriveFolder and ignitionFitGoogleDriveFolder. latestSpreadFits() and latestIgnitionFits() list a folder's own files only (googledrive::drive_ls() is not recursive), so the default "latest" over the main folder never reads an experiment's fits. The spread and ignition ledgers share one folder, so they share one "testing" subfolder.


The logistic parameters fixed at 1, not fitted

Description

hillSlope1 and inflectionPoint1, in the position they take in the link, right after maxAsymptote. DEoptim's par, lower and upper do not contain them; the objective, the validation and the gates insert them (fixLogisticPars()), and fireSense_spreadFit restores them in the ledger's parameter sets from this vector.

Usage

fixedLogisticPars

Format

A named numeric vector.


The fold models of an ignition or escape fit, and their mean prediction

Description

fireSense_ignitionFit fits one xgboost model per cross-validation fold and stores them in fit$modelList$model, named Fold1, Fold2, ... (beside non-model elements such as rocs and yearTotals). fireSense_ignitionPredict predicts with their mean, and fireSense_ignitionFit uses the same mean for the fitted year effects, so the two agree.

Usage

foldModels(fit, mustExist = TRUE)

foldMeanPrediction(fit, newdata)

Arguments

fit

A fireSense_IgnitionFitted or fireSense_EscapeFitted: a list with modelList$model.

mustExist

If TRUE (default), stop when fit has no fold model; if FALSE, return an empty list.

newdata

The covariates to predict, prepared as for the fit (standardised with its scaleData when it was fitted with rescaleVars).

Value

foldModels(): the list of fold models (the elements of fit$modelList$model whose name contains "Fold").

foldMeanPrediction(): numeric, one per row of newdata: the mean over the fold models of predict(model, newdata), each floored at 0 (an expected count).


Calculate proportional burn of landcover and tree species

Description

Calculate proportional burn of landcover and tree species

Usage

fuelClassPrep(
  pixelGroupMap,
  cohortData,
  rstLCC,
  nonflammableLCC,
  fires,
  nonforestLCC,
  yearRange
)

Arguments

pixelGroupMap

A RasterLayer with pixel values equal to a pixel group number that corresponds exactly to pixelGroup column in cohortData.

cohortData

A data.table with columns: pixelGroup, ecoregionGroup, speciesCode, and optionally age, B, mortality, aNPPAct, and sumB.

rstLCC

a landcover map

nonflammableLCC

nonflammable landcover in rstLCC

fires

a single sf or SpatVector object of fire polygons containing a YEAR column

nonforestLCC

vector or list of vectors of flammable non-forest LCC

yearRange

the range of years represented by this landscape

Value

data.table with cell, biomass, tree species or LCC for non-forest, and year of fire

Examples

# fuelClassPrep(
#   sim$pixelGroupMap2011, sim$cohortData2011, sim$rstLCC2011,
#   rstLCC = sim$rstLCC2011, nonForestLCC = sim$nonForestLCCGroups,
#   nonflammableLCC = P(sim)$nonflammableLCC,
#   fires = do.call(rbind, sim$spreadFirePolys),
#   yearRange = c(2012, 2020)
# )

The part of fuelCovsToCoarse() that does not depend on the covariate values

Description

The part of fuelCovsToCoarse() that does not depend on the covariate values

Usage

fuelCovsStatic(pixelID, rasTemplate, fact, cells = templateCells(rasTemplate))

Arguments

pixelID

the cells that have covariates (covs$pixelID).

rasTemplate

A raster-like object (typically terra::SpatRaster) used as a spatial template (extent, resolution, projection) when converting the fuel covariate data frame to a raster.

fact

numeric(1) aggregation factor passed to terra::aggregate(fact = ...), controlling the spatial coarsening scale.

cells

the cells of rasTemplate that are not NA; found if not given.

Value

a list with the inputs it was made for (pixelID, cells, fact, geometry) and hasCovs, the values of the coarse mask (1 where a coarse cell has a pixel with covariates, otherwise NA), and noCovs, the non-NA template cells without covariates. It holds no SpatRaster, so it survives being saved with a simList.


Was a static made for these inputs?

Description

The guard fuelCovsToCoarse() runs on the static it is given: TRUE only if static was made (fuelCovsStatic()) for the same pixelIDs, the same non-NA cells of the template, the same template dimensions, extent and CRS, and the same fact. fuelCovsToCoarse() and prepare_FuelCovsCoarse() already run it and return the static they used, so a caller that keeps that one does not need this; it is for a caller that wants to know before the call.

Usage

fuelCovsStaticIsFor(
  static,
  pixelID,
  rasTemplate,
  fact,
  cells = templateCells(rasTemplate)
)

Arguments

static

NULL or the result of fuelCovsStatic().

pixelID

the cells that have covariates (covs$pixelID).

rasTemplate

A raster-like object (typically terra::SpatRaster) used as a spatial template (extent, resolution, projection) when converting the fuel covariate data frame to a raster.

fact

numeric(1) aggregation factor passed to terra::aggregate(fact = ...), controlling the spatial coarsening scale.

cells

the non-NA cells of rasTemplate; found if not given.

Value

TRUE or FALSE.

Examples

tmpl <- terra::rast(nrows = 4, ncols = 4, extent = c(0, 4000, 0, 4000), vals = 1)
st <- fuelCovsStatic(1:12, tmpl, fact = 2)
fuelCovsStaticIsFor(st, 1:12, tmpl, fact = 2)  # TRUE
fuelCovsStaticIsFor(st, 1:8, tmpl, fact = 2)   # FALSE: other pixels have covariates

Range that puts linear fuel biomass on the scale the spread fit uses

Description

Fuel covariates of the spread model are biomass on the LINEAR scale, divided by a fixed 1e4. The division is not done to the data: it is the covMinMax given to rescaleKnown2(), which is affine and does not clamp, so c(0, 1e4) is exactly biomass / 1e4. The constant is fixed, not max(biomass), so that fireSense_spreadPredict reproduces the fit's scaling in every year from the stored covMinMax_spread alone. It is also how a fit is recognised as linear: see isLinearFuelRange().

Usage

fuelLinearRange

Fuel biomass from the log scale back to the linear scale

Description

fireSenseCovariatesCreate() returns fuel-class biomass as logMinB(): logged, with everything below exp(log(100) - 1) (36.8) raised to that floor. On that scale the spread model cannot use the fuel gradient: on ELF 5.3.2, 45% of pixels sit on the floor and the treed ones fall in 16% of the covariate range (rescaled sd 0.05), so the coefficient estimates little more than treed against treeless. On the linear scale the treed pixels span twice the range and an absent fuel is exactly 0, so it contributes exactly nothing.

Usage

fuelLogToLinear(x)

Arguments

x

Numeric vector of fuel biomass as returned by logMinB().

Details

This undoes the log where the spread model needs it, instead of removing it at the source, because fireSenseCovariatesCreate() also builds the ignition covariates and its output is cached for every fitted polygon. Both fireSense_spreadFit and fireSense_spreadPredict call this function, so the fit and the prediction cannot drift apart.

Value

Biomass on the linear scale; values on the logMinB() floor become 0.


Get Fire SpatialPoints from Canadian Fire Database

Description

Get Fire SpatialPoints from Canadian Fire Database

Usage

getFirePoints_NFDB(
  url = NULL,
  studyArea = NULL,
  rasterToMatch = NULL,
  redownloadIn = 1,
  years = 1991:2017,
  fireSizeColName = "SIZE_HA",
  NFDB_pointPath
)

Arguments

url

Passed to prepInputs

studyArea

A SpatialPolygons* object used as the principle study region, passed to prepInputs.

rasterToMatch

A RasterLayer objects to use as the template for all subsequent raster operations (i.e., the one used throughout the simulation).

redownloadIn

Numeric Time in YEARS that we tolerate the data to be "old" i.e. 0.5 would mean "redownload data older than 6 months"

years

Numeric vector of consecutive years to fetch.

fireSizeColName

Character describing the name of the column containing fire size information.

NFDB_pointPath

Passed to destinationPath in prepInputs

Value

A sf spatial points object, retaining all columns of the source data (notably CAUSE, YEAR and SIZE_HA). When rasterToMatch is supplied, an additional size column gives fire size in pixels.


Get Fire SpatialPoints from Canadian Fire Database

Description

Get Fire SpatialPoints from Canadian Fire Database

Usage

getFirePoints_NFDB_V2(
  url = NULL,
  studyArea = NULL,
  redownloadIn = 1,
  years = 1991:2017,
  fireSizeColName = "SIZE_HA",
  NFDB_pointPath = NULL,
  fun = "sf::st_read",
  plot = FALSE
)

Arguments

url

Passed to prepInputs

studyArea

A SpatialPolygons* object used as the principle study region, passed to prepInputs.

redownloadIn

Numeric Time in YEARS that we tolerate the data to be "old" i.e. 0.5 would mean "re-download data older than 6 months"

years

Numeric vector of consecutive years to fetch.

fireSizeColName

Character describing the name of the column containing fire size information.

NFDB_pointPath

Passed to destinationPath in prepInputs

fun

Character. The function (as a string, e.g., "sf::st_read") used to load the downloaded data. Forwarded to prepInputs(fun = ...), and used to load already-downloaded data, so the class returned does not depend on whether a download was needed.

plot

logical indicating whether to produce plot of fire points. Default FALSE.

Value

A sf spatial points object (or whatever class fun returns), retaining all columns of the source data (notably CAUSE, YEAR and SIZE_HA).


Download and prepare fire data from National Fire Database

Description

Download and prepare fire data from National Fire Database

Usage

getFirePolygons(url, years, useInnerCache = FALSE, ...)

Arguments

url

Character (or missing). URL to the fire polygons archive (typically an NBAC ⁠*_shp.zip⁠ on the CFS server). When missing, latestNBACUrl() is queried so the newest NBAC release available on the CFS download index is used; this means re-running the same code later may pick up a newer dataset. Pass an explicit URL to pin to a specific release when reproducibility matters.

years

years to filter fire polygons by

useInnerCache

logical indicating whether to cache the prepInputs call

...

additional arguments passed to reproducible::prepInputs()

Value

list of fire polygons by year, each with its area in ha as POLY_HA and as SIZE_HA

See Also

latestNBACUrl() for the discovery helper used when url is missing.


Cleaning up the polygon points

Description

Mostly this is about 2 things:

  1. remove fires that were so small that they take less than 1 pixel so they are not in the buff object but are in the cent object.

  2. the centroid cell is in a buffer or otherwise nonburnable cell (e.g., water). For 1) remove these from the centroid data. For 2) this function will search in the neighbourhood for the next closest pixel that has at least 7 available neighbours that can burn. If not, remove these.

Usage

harmonizeBufferAndPoints(cent, buff, ras, idCol = "FIRE_ID")

Arguments

cent

List of points as SpatialPointsDataFrame

buff

List of data.table objects with 3 columns, "buffer" which is 1 (in the fire) or 0 (in a buffer), ids which are the fire ids which MUST match the ids in the cent.

ras

The raster that created the pixelIDs in the buff.

idCol

The column name as a character string with the fire ids. Defaults to "FIRE_ID".


Harmonize fire data

Description

Outer wrapper on spread fire polygon data munging that does several things:

  1. ensure buffered fires are entirely in studyArea;

  2. ensure every fire has a corresponding ignition point, and vice versa;

  3. ensure these points are flammable.

Usage

harmonizeFireData(
  firePolys,
  flammableRTM,
  spreadFirePoints,
  areaMultiplier,
  minSize,
  pointsIDcolumn = "FIRE_ID",
  cores = 1
)

Arguments

firePolys

the semi-processed fire polys, with field matching pointsIDcolumn

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

spreadFirePoints

the ignition points corresponding to firePolys

areaMultiplier

Either a scalar that will buffer areaMultiplier * fireSize or a function of fireSize. See ?fireSenseUtils::bufferToArea.

minSize

an alternative to areaMultiplier, typically used when fires are small

pointsIDcolumn

the name of the column denoting fire ids in both spreadFirePoints and firePolys

cores

Positive integer.Number of CPU cores (threads) to use for parallel operations.


Functions whose code affects what harmonizeFireData() returns

Description

reproducible::Cache() digests only the called function's own code, so a cached harmonizeFireData() call keeps returning its old result when a function it calls changes. Pass this list as that call's .cacheExtra and those functions become part of the key. It includes multiplier(), which harmonizeFireData() does not call itself but which fireSense_dataPrepFit's default areaMultiplier does: a change of its defaults changes the buffers.

Usage

harmonizeFireDataDeps()

Value

A list of functions, to pass as reproducible::Cache()'s .cacheExtra.

See Also

harmonizeFireData(), makeFireSenseLCCDeps()


Observed fire in an ELF core in one year

Description

What the hindcast simulation is compared with: natural-cause ignitions, escapes, area burned and the fire sizes of year, all inside the ELF core (the buffer is excluded). Ignitions and escapes are counted on the core with the fit's definitions: NFDB points with CAUSE in naturalCauses of any size are ignitions (ELFfireCounts()), and those that escapedIgnitions() marks (one per fire polygon of the year of at least escapeSizeHa and larger than a pixel) are escapes. Area burned and fire sizes are the area of the fire polygons on the burnable pixels of the core (flammableRTM; ELFfireOverlay()), because the simulation burns only those; the polygon area in the core is kept in the ⁠*Polygon⁠ columns and sizesPolygon. Both are given for the natural-cause polygons and for polygons of every cause, because the simulation ignites natural fires only but the spread model was fitted to polygons of every cause.

Usage

hindcastObserved(
  coreRaster,
  firePoints,
  firePolys,
  year,
  escapeSizeHa = 50,
  pixelAreaHa = prod(terra::res(coreRaster))/10000,
  naturalCauses = c("L", "N"),
  polyCauseCol = polyCauseColTxt,
  naturalPolyCauses = "Natural",
  flammableRTM = NULL,
  fireCauses = NULL,
  coreStart = FALSE,
  sizeCol = polySizeColTxt,
  coreIs = "mask"
)

Arguments

coreRaster

SpatRaster of the ELF core on the simulation grid: cells outside the core are NA or 0 (rasterToMatchELF in the fireSense simulation), or another raster inELFCore() reads (coreIs).

firePoints

SpatVector of fire points with columns YEAR, CAUSE and SIZE_HA (ignitionFirePoints).

firePolys

SpatVector of fire perimeters with column YEAR, or a list of them as firePolys is in the simulation (NULL elements are dropped).

year

The year to describe.

escapeSizeHa

Size (ha) a fire must reach to count as escaped.

pixelAreaHa

Area of one pixel (ha). Default: the area of a coreRaster pixel.

naturalCauses

Values of CAUSE in firePoints that are natural ignitions.

polyCauseCol

Column of firePolys holding the cause. If it is missing, the natural-cause values of the result are NA, with a warning.

naturalPolyCauses

Values of polyCauseCol that are natural.

flammableRTM

SpatRaster of the pixels the simulation can burn (1; 0 or NA cannot burn), e.g. flammableRTM of the fireSense simulation. Projected to coreRaster (nearest) if on another grid. NULL counts every core pixel as burnable, with a warning.

fireCauses

NULL (default) uses naturalCauses and naturalPolyCauses as given. Cause groups (see fireCauseCodes()), e.g. c("natural", "unknown"), set both from the one table, as fireSense_dataPrepFit's fireCauses does, so the observed fire has the fit's causes.

coreStart

FALSE (default): as above, every fire is clipped to the core. TRUE: the fires of the ELF are those whose start (fireStarts(): the centroid moved to the nearest burnable pixel of the fire) is in the core, each at its whole extent, core and buffer, on the burnable pixels of flammableRTM (which must then cover the buffer too; it is not projected to coreRaster); a fire starting in the buffer is not counted at all. Escapes are the core-start polygons of escapeDefinition()⁠(escapeSizeHa, fireCauses)⁠, one per polygon, and ignitions the points escapeIgnitionPoints() gives, the data the escape model is fitted to. Needs fireCauses and flammableRTM, and firePolys with polyCauseCol.

sizeCol

With coreStart = TRUE: the column of firePolys with the whole fire's size (ha), as in escapeFireSet().

coreIs

What coreRaster is, as in inELFCore(): "mask" (default, as above) or "ELF" (a one-ELF raster, core 2 and buffer 1). A categorical (multi-ELF) raster is core wherever it has a label.

Value

A list. counts is a one-row data.table: year, ignitions, escapes, areaBurnedHa (natural-cause polygons on burnable core pixels), areaBurnedHaAllCause, nFires50 and nFires50AllCause (fires with at least escapeSizeHa on burnable core pixels), and the same four measured on the polygons in the core: areaBurnedHaPolygon, areaBurnedHaAllCausePolygon, nFires50Polygon, nFires50AllCausePolygon. sizes is a data.table of each fire's area on burnable core pixels, with cause ("natural" or "allCause") and ha; sizesPolygon is the same for the polygons clipped to the core. polys is the SpatVector of the year's natural-cause polygons (not clipped; NULL without polygons or a cause column), to draw on a map. points is the SpatVector of the natural ignition points that counts$ignitions counts (in the core's CRS, with escaped), the ignition locations the simulation is compared with.


What a fireSense hindcast job changes in a setupProject() call

Description

A hindcast holds the vegetation of SCANFI year year static and draws that year's climate. It runs 10 replicates as decimal years year to year + 9 * step (20, with allSets, one per spread parameter set). It runs the climate and fireSense modules only: no vegetation or summary modules, so modules replaces the project's own. The modules name their interval parameter differently (fireTimeStep, .runInterval, hindcastInterval); this sets each of them to step. .plots = NA keeps the modules that run every replicate from plotting. The data modules keep the fit's .plots, which is in their cache keys, so a hindcast reuses the fit's data preparation.

Usage

hindcastSetup(year, step = 0.001, allSets = FALSE, ignitions = NA_character_)

Arguments

year

The SCANFI year whose vegetation is held static.

step

Years between replicates.

allSets

If TRUE, one job runs every fitted spread parameter set (20 replicates, 5 sets of 4).

ignitions

NA for the fireSense_burn default ("predicted"); "observedEscapes" spreads each year's observed escapes (spread alone).

Value

A list of times, modules and params. Use times and modules instead of the project's, and merge params into the project's with Require::modifyList2().


One simulated year in an ELF core

Description

The simulated counterpart of hindcastObserved(), for one simulated year: the year's ignitions and escapes (ignitionsAndEscapes from fireSense_ignitionPredict) and each fire of the year's burn-ID raster (rstAnnualBurnID from fireSense_burn, one integer per fire), counted or clipped to the ELF core. A fire that burned only outside the core is not listed. The simulation burns the buffer too, so these sizes are smaller than burnSummary$areaBurnedHa for fires crossing the core edge.

Usage

hindcastSimulated(
  burnID,
  coreRaster,
  ignitions = NULL,
  escapeSizeHa = 50,
  coreStart = FALSE,
  coreIs = "mask"
)

Arguments

burnID

SpatRaster of fire IDs (NA where nothing burned).

coreRaster

SpatRaster of the ELF core; cells outside it are NA or 0. It need not share the grid of burnID: pixels are placed by their centres. Read by inELFCore() (coreIs).

ignitions

data.table with the ignition cell numbers of burnID in pixelID and, in escaped, whether each ignition escaped. NULL gives NA ignitions and escapes.

escapeSizeHa

Size (ha) at which a fire counts in nFires50.

coreStart

FALSE (default): every fire is clipped to the core, as above. TRUE: the fires are those that burned the pixel of an ignition in the core, each at its whole extent (every pixel of its ID, core or buffer), as hindcastObserved()(coreStart = TRUE) counts the observed fire; a fire from a buffer ignition is not counted. Needs ignitions.

coreIs

As in hindcastObserved(): "mask" (default, as above) or "ELF".

Value

A list. counts is a one-row data.table: ignitions, escapes, areaBurnedHa and nFires50, the columns of hindcastObserved()'s counts of the same names. sizes has one row per fire in the core (with coreStart = TRUE, per core-start fire): fire_id and ha.


The shared IgnitionFit ledger files

Description

fireSense_IgnitionFit writes each fit (ignition and escape together) as a row of an rds file in a Google Drive folder (its ignitionFitGoogleDriveFolder); fireSense_ELFs reads them for a multi-ELF study area. With ignitionFitFilename = "latest" those modules use these functions instead of one named file. Parallel to the spread-fit ledger helpers (spreadFitFilenameFor(), latestSpreadFits()).

latestIgnitionFits() returns, for every polygon, its newest usable row in the ledger files (any file of the folder; rows fitted with another objective or escape definition are skipped): the one with the latest writtenAt (stamped by reproducible::CacheGeoWrite()). A row written before that stamp existed has its file's date instead: the date in the file's suffix (ledgerFileOrder()), else older than any dated file; ties go by the file's modified time. No row is newer than its file was last modified, so files are read newest-modified first; with polygonIDs, reading stops once each has a row newer than the next file. Files are read, also with no internet, as latestSpreadFits() reads them.

Usage

ignitionFitFilenameFor(fireYears, suffix = "")

ignitionFitFileTag

latestIgnitionFits(
  cloudFolderID = ignitionFitLedgerFolder(),
  destinationPath,
  polygonIDs = NULL,
  escapeDefinition = NULL
)

Arguments

fireYears

The fire years the fit used; only the first and last matter.

suffix

Text put after the model tag in the file name, to name an experiment's ledger file, e.g. "_bufIndep20261024" (ending with the date of the fits orders the file among others for "latest", for rows written before writtenAt). A run reads or writes such a file by naming it (spreadFitFilename, ignitionFitFilename); "latest" reads every ledger file of the folder. Experiment files go in the folder's "testing" subfolder (spreadFitLedgerFolder(testing = TRUE)), which "latest" over the main folder never reads.

cloudFolderID

The Google Drive folder (url or id) holding the ledger files; default ignitionFitLedgerFolder().

destinationPath

Local folder for the downloaded files.

polygonIDs

Optional. The polygons (ELF ids) wanted; NULL reads every file.

escapeDefinition

This run's escapeDefinition(): rows fitted under another (recorded since fireSense_ignitionFit records it) are skipped. NULL (default): not checked.

Details

ignitionFitFileTag is in the names of the files written since xgboost Poisson ignition and escape fits (fireSense_IgnitionFit's modelAlgorithm = "xgboost" with objective count:poisson) began, and dates them. It no longer decides which files "latest" reads: latestIgnitionFits() reads every file and skips each row whose models were fitted with another objective (e.g. the Tweedie fits of "_xgboost" files) or under another escape definition, so a change of model is seen in the fits themselves, not in a tag kept by hand. The tag names the objective (ignitionObjectiveTxt); a test fails if the objective changes and the tag does not.

Value

ignitionFitFilenameFor(): the file name a fit over fireYears is written to, e.g. "fireSenseIgnitionParams_1985-2024_xgboostPoisson_20261013.rds" (then suffix).

latestIgnitionFits(): the ledger rows, in the form fireSense_IgnitionFit writes them (a data.frame with a geometry column), or NULL when no file matches. Attribute "ignitionFitFiles" names the file each polygon came from.


Ignition points and the fire polygons they match

Description

The matching escapedIgnitions() and polygonIgnitions() share. A polygon counts if its area is at least escapeSizeHa and larger than one pixel (the polygons escapedFires() keeps, the fires the spread model is fitted to; area as given, by terra::expanse(), so a polygon clipped to a study area is judged on the part inside it). A point matches a polygon of its year that it lies in, or is within maxDistM of: NFDB locations are often rounded to 0.01 degree (about 1 km), and on ELF 6.6.1 20 of the 31 natural points of 50 ha or more outside every polygon of their year were within 1 km of one.

Usage

ignitionPolygonPairs(
  points,
  polys,
  escapeSizeHa,
  pixSizeHa,
  maxDistM = 1000,
  sizeCol = NULL,
  causes = NULL,
  polyCauseCol = polyCauseColTxt
)

Arguments

points

Ignition points (SpatVector or sf) with column YEAR.

polys

Fire polygons (SpatVector or sf) with column YEAR, or a list of them (one per year, as firePolys is in fireSense; NULL elements are dropped). Any CRS: they are projected to that of points.

escapeSizeHa

Size (ha) a polygon must reach.

pixSizeHa

Pixel area (ha). A polygon must also be larger than one pixel.

maxDistM

Distance (m) from a polygon's edge within which a point outside it still matches it.

sizeCol

NULL (default): a polygon is judged on its area as given (terra::expanse()). A column of polys (e.g. "POLY_HA"): judged on that, the whole fire's size, as escapeFireSet() does.

causes

NULL (default): polygons of every cause. NBAC cause values (e.g. fireCauseCodes(fireCauses, "nbac")): only polygons whose polyCauseCol is one of them.

polyCauseCol

Column of polys holding the cause, used with causes.

Value

A list: points and polys (the polygons that count, with their area in .ha), both SpatVector, and pairs, a matrix with columns point and poly (rows of those) and logical inside.


Construct standardized FireSense object names

Description

Creates a standardized name by combining a pre prefix, a normalized igOrEsc token (case-transformed), and a post suffix.

Usage

igOrEscNames(
  igOrEsc,
  pre = "fireSense_",
  post,
  case = c("lower", "camel", "sentence", "title")
)

Arguments

igOrEsc

character. A token such as "ignition" or "escape".

pre

character scalar. Prefix string (default "fireSense_").

post

character scalar. Suffix string to append.

case

One of c("lower", "camel", "sentence", "title"). Controls how igOrEsc is transformed before concatenation. Partial matching on the first letters is used: e.g., "cam", "sen", "tit".

Value

character(1) constructed as paste0(pre, transformed(igOrEsc), post).

Examples

igOrEscNames("ignition", post = "Covariates")
igOrEscNames("escape", pre = "fs_", post = "_Formula", case = "camel")

Which points or cells are in an ELF's core

Description

The one rule for the core of an ELF, for every part of fireSense: the fit's fires, the escape and ignition data, the burn and the hindcast. Three kinds of raster are in use. The values of the first two cannot tell them apart (a 1 is buffer in one and core in the other), so coreIs says which a numeric coreRaster is:

  • "ELF": a one-ELF raster, rasterToMatchLargeELF: the core is fireSenseELFCoreValue (2), the buffer 1.

  • "mask": the core alone, as rasterToMatchELF and the coreRaster of hindcastObserved() and hindcastSimulated(): the core is every value above 0; NA or 0 elsewhere.

  • A categorical raster (terra::is.factor()), as fireSense_ELFs makes rasterToMatchLargeELF of a study area over several ELFs: each cell is labelled with its ELF (the codes start at 0) and the study area has no buffer, so every labelled cell is core. coreIs is not used.

Usage

inELFCore(x, coreRaster, coreIs = c("ELF", "mask"), grid = coreRaster)

Arguments

x

Points (SpatVector or sf), or cell numbers of grid.

coreRaster

SpatRaster of the core, as above. NULL: everything is core.

coreIs

"ELF" (default) or "mask": what a numeric coreRaster is.

grid

SpatRaster whose cells x numbers; default coreRaster. On another grid each cell is placed by its centre.

Value

A logical vector, one per point or cell: TRUE in the core.


Was this covariate rescaled as linear fuel biomass?

Description

Was this covariate rescaled as linear fuel biomass?

Usage

isLinearFuelRange(range)

Arguments

range

Length-2 numeric: a covariate's entry in covMinMax.

Value

TRUE when range is fuelLinearRange, i.e. the fit used linear fuel biomass, so a prediction must apply fuelLogToLinear() to that covariate before rescaling it. FALSE for a fit made on the log scale, whose covariates must be left as they are.


Is an age young?

Description

The single rule for youngAge: an age is young when it is at or below cutoffForYoungAge (age <= cutoffForYoungAge). NA is never young. Every place in fireSenseUtils that decides young or not young calls this function, so fitting and prediction cannot disagree at the cutoff.

Usage

isYoungAge(age, cutoffForYoungAge = fireSenseYoungAgeCutoff)

Arguments

age

numeric vector of ages (stand age or time since disturbance), in years.

cutoffForYoungAge

age at and below which a pixel is young.

Value

logical vector the length of age; FALSE where age is NA.


Discover the URL of the most recent NBAC shapefile archive

Description

Parses the Apache directory listing at base and returns the URL of the newest file matching ⁠NBAC_<startYear>to<endYear>_<YYYYMMDD>_shp.zip⁠, selected by the YYYYMMDD stamp embedded in the filename. If the listing cannot be read or no matching file is found, fallback is returned, so callers can rely on getting some URL back.

Usage

latestNBACUrl(
  base = "https://cwfis.cfs.nrcan.gc.ca/downloads/nbac/",
  fallback = paste0(base, "NBAC_1972to2025_20260513_shp.zip")
)

Arguments

base

Character. Directory listing URL (must be the parent folder that serves the autoindex page).

fallback

Character. URL to return when discovery fails.

Value

A single character URL.


Each land-cover class's share of an ELF's flammable pixels

Description

How common each class is over the whole study area, not only where fires burned: a covariate for a class that covers a few percent of the ELF has too few pixels for its coefficient to be estimated. fireSense_dataPrepFit compares these shares with its minCovariateProp to decide which non-forest classes are clustered on their own (see assessFuelClasses()) and whether treed wetland is a covariate (see fireSenseCovariatesCreate()).

Usage

lccFlammableShare(rstLCC, flammableRTM = NULL)

Arguments

rstLCC

Land-cover SpatRaster (class codes as values).

flammableRTM

Optional SpatRaster on the same grid; only its cells equal to 1 count. Without it, every cell of rstLCC that is not NA or 0 counts.

Value

Named numeric, one element per class code (as character), summing to 1.


The order to read ledger files in: newest first, by the date in the suffix

Description

A ledger file is named ⁠<prefix>*<fileTag><suffix>.rds⁠. Its date is the last 8-digit yyyymmdd in the suffix ("_gpscCause_20261029" is 20261029, "_bufIndep20261024" 20261024): when its fits were made, which the file's modified time is not (a file is modified whenever a fit is added). A file without a date in its suffix (e.g. no suffix) is older than any dated one; files of the same date, or both undated, are ordered by modified time.

Usage

ledgerFileOrder(names, modifiedTime, fileTag)

Arguments

names

File names.

modifiedTime

Their modified times (ISO 8601 strings, as Google Drive gives them).

fileTag

The model tag (spreadFitFileTag, ignitionFitFileTag).

Value

Integer: the order of names, newest first.


The parameters of a linear-predictor link, in the order of spreadCpp(linkPars =)

Description

The parameter vector of one of spreadLinearLinks, named as spreadLinkParNames says. It is what SpaDES.tools::spreadCpp(link = link, linkPars = ) takes, and linearLinkProb() turns the same vector into p, so the R and the C++ link are given the same numbers. "richards" uses lowerAsymptote, richardsNu and its fixed ⁠B = ⁠ spreadRichardsB, and not gamma, floor or shape.

Usage

linearLinkPars(
  link,
  pc,
  gamma = spreadPowerLawGamma,
  floor = spreadProbFloor,
  shape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu
)

Arguments

link

One of spreadLinearLinks.

pc

The percolation threshold (maxAsymptote).

gamma, floor, shape

As in powerLawLink().

lowerAsymptote, richardsNu

As in logisticAll().

Value

A named numeric vector.


Spread probability from the linear predictor, for a link of spreadLinearLinks

Description

The one place the link is chosen: powerLawLink(), powerLawSmoothLink() or richardsLink().

Usage

linearLinkProb(x, link, pars)

Arguments

x

The linear predictor.

link

One of spreadLinearLinks.

pars

The link's parameters: a named numeric vector (linearLinkPars()), or a matrix with those names as columns and one row per element of x.

Value

A numeric vector, one value per x.


Multiple-parameter versions of logistic functions

Description

Logistic functions using 2, 3, 4, or 5 parameters; logisticAll dispatches to one of them based on length(logisticPars).

Usage

logistic4p(x, par)

logistic5p(x, par)

logistic3p(x, par, par1 = 0.1)

logistic3pUpper(x, par, par1 = 0.1)

logistic2p(x, par, par1 = 0.1, par4 = 0.5)

logisticAll(
  logisticPars,
  mat,
  covPars,
  lowerSpreadProb,
  link = NULL,
  gamma = spreadPowerLawGamma,
  shape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu
)

Arguments

x

Numeric vector. Linear predictor (e.g. mat %*% covPars) at which to evaluate the logistic.

par

Numeric vector of logistic parameters whose length matches the variant: 2 for logistic2p, 3 for logistic3p, etc. See logisticParamNames for the meaning of each position.

par1

Numeric scalar. Lower asymptote (replaces par[1] of the 4-parameter form).

par4

Numeric scalar. Asymmetry factor (replaces par[4] of the 4-parameter form).

logisticPars

Numeric vector of logistic parameters. Unless link names the form, its length selects the variant logisticAll dispatches to – except that a vector with an element named upperTail1 is always logistic3pUpper, whatever its length.

mat

Numeric matrix of covariate values, one row per observation.

covPars

Numeric vector of covariate coefficients (same length as ncol(mat)); mat %*% covPars forms the linear predictor.

lowerSpreadProb

Numeric scalar in ⁠[0, 1]⁠. The lower asymptote (par1) used for the 2- and 3-parameter forms.

link

NULL (the default) to choose the form from logisticPars as above, "logistic3pUpper" to use the 3-parameter form with Stukel's upper tail, or "powerLaw", "powerLawSmooth" or "richards" for powerLawLink(), powerLawSmoothLink() or richardsLink() (logisticPars[1] is then p_c). Pass it explicitly wherever logisticPars may arrive without names, as inside the objective function.

gamma

The "powerLaw" and "powerLawSmooth" links' scale gamma (powerLawLink()); not used by the other links ("richards" has its own fixed scale, richardsLink()).

shape

The "powerLaw" and "powerLawSmooth" links' curvature exponent shape (powerLawLink()); default 1; not used by the other links.

lowerAsymptote

The lower asymptote L of the "powerLawSmooth" and "richards" links (powerLawSmoothLink(), richardsLink()), spreadLowerAsymptoteMin ⁠<= L <= spreadProbFloor⁠ (checkLinkParams()); default spreadProbFloor; not used by the other links.

richardsNu

The "richards" link's nu (richardsLink()); default spreadRichardsNu; not used by the other links.

Details

The general form is the 5-parameter sigmoid (Richards' curve): par1 + (par2 - par1) / (1 + (exp(x) / par3)^(-par4))^par5. The 4-, 3-, and 2-parameter variants successively fix the lower asymptote (par1), the inflection-point scale (par3 = 1), and the asymmetry factor (par5 = 0.5) to reduce the parameter count.

logistic3pUpper is logistic3p with Stukel's (1988) generalized-logistic upper tail applied to the linear predictor: par1 + (par[1] - par1) / (1 + exp(-H(par[2] * x)))^par[3], where H leaves negative values alone and, for u = par[2] * x >= 0 and a = par[4], is (exp(a * u) - 1) / a for a > 0, u for a = 0 and -log(1 - a * u) / a for a < 0 (Stukel, T. A. (1988), Generalized logistic models, JASA 83:426-431; as sirt::pgenlogis()). par[4] changes only how the curve approaches its upper asymptote: negative values slow the approach, so pixels with a high linear predictor are no longer all pressed against the ceiling; par[4] = 0 is logistic3p exactly. In logistic3p the approach to the ceiling is set by the slope par[2] alone – par[3] shapes only the lower end – so this is the one parameter that changes the upper end independently.

Value

Numeric vector of logistic values; same length as x (or nrow(mat) for logisticAll).


Logistic parameter names

Description

Logistic parameter names

Usage

logisticParamNames

Value

A named list of length 4, with "2p", "3p", "4p", "5p" as names representing the 2-parameter etc. logistic curve.


Log with a minimum

Description

Used for transforming Biomass to the log scale

Usage

logMinB(x)

Arguments

x

Any value to be adjusted with log and a minimum B

Value

The original vector, logged with a minimum.


Make Ecologically-based Low Fractal-Dimensional polygons

Description

Fires have key features that are different than "normal" ecological zonations. These include: 1) the property that they spread horizontally across a landscape, regardless of human-mapped ecological areas. 2) Furthermore, even when homogeneous fire regions are mapped, the homogeneousness may be because of fuel changes that occupy the average condition for an ecological area, not necessarily the boundary conditions. 3) Small areas that encompass an area that is only "several times larger than the largest fires" will be too small to capture the potential for multiple very large fires. 4) Furthermore, very large ecological regions may encompass too much variation in fire-fuel-climate relationships that any estimates of fire behaviour will not be accurate across the whole region. 5) No matter what area is chosen to Thus, to estimate fire behaviour across a large region like Canada, we need polygons that are not too small (>> largest fires), not too big (<<), are not constrained by ecological zones defined by vegetation, have buffers.

Usage

makeELFs(
  x,
  desiredBuffer = 20000,
  maxArea = 2.4e+11,
  destinationPath = ".",
  singleSpatVector = FALSE,
  useCache = TRUE
)

plotELFs(
  destinationPath = ".",
  which = NULL,
  fill = "green",
  plan = NULL,
  fewFires = NULL,
  fewFiresFill = "grey60",
  arcticFill = "grey85",
  ELFs = NULL,
  labels = c("code", "name", "none"),
  labelWhich = c("all", "highlighted"),
  buffers = TRUE,
  axes = c("m", "longlat", "none"),
  metrics = NULL,
  metric = NULL,
  metricCol = NULL,
  metricTitle = NULL,
  metricRange = NULL,
  plotFires = NULL,
  ...
)

Arguments

x

A polygon layer (SpatVector or sf) or gridded layer (SpatRaster) that maps the entire area of interest for the ELFs; it only sets which cells are land, the ELFs themselves are (sub-)ecoprovinces. If missing, the national template the fireSense modules use, ELFtemplateRaster()(destinationPath). A polygon layer needs a column called FRU.

desiredBuffer

The distance in m that the buffers should be. Default is 20000.

maxArea

The area in m^2 that will be split if the ecozones are larger than this. Default is 2.4e+11 which is about 500km x 500km plus the buffer. This means that the ELFs will be smaller than this, with lower limit being the individual ecozones plus buffer.

destinationPath

A path where any downloads should be put.

singleSpatVector

Logical. If TRUE, the function returns a single SpatVector of all ELFs (rather than the per-ELF list described in Value). Default FALSE.

useCache

Logical. If TRUE, then some internal steps will be cached. If FALSE, then some (or most) will not be cached.

which

Character. ELF names (e.g., c("13.1", "4.1")) whose cores plotELFs() fills with fill, except those that have a metric value. Default NULL fills none.

fill

The colour used to fill the which ELFs.

plan

The merges and skips to show: sim$ELFmerges of fireSense_ELFs, as returned by ELFmergePlan() or fewFireELFs(). plotELFs() always draws the state after the merges (mergeELFs()), with each merged ELF under its merged name (e.g. ⁠11.1_2⁠). NULL (default) computes the plan with fewFireELFs() at its default settings (Cached).

fewFires

ELF ids to fill as "not enough fires". NULL (default) uses the ELFs the plan skips (ELFsSkipped()); character(0) fills none.

fewFiresFill

The colour used to fill the fewFires ELFs.

arcticFill

The colour used to fill the Arctic and Prairie grassland ELFs (ELFsNotFitted(), which are not fitted). Merged ELFs are not filled; their label is their merged name.

ELFs

The list makeELFs() returns (before any merging), if the caller has it. NULL (default) builds it with makeELFs() (Cached). Without a poly element the outlines are drawn from rasWhole.

labels

What plotELFs() prints on each ELF: "code" (the ELF name, e.g. "13.1"), "name" (the name of the ecozone the ELF lies in, e.g. "Pacific Maritime"; see elfLabels()) or "none".

labelWhich

"all" labels every ELF; "highlighted" labels only those in which.

buffers

If FALSE, plotELFs() draws only the ELF cores, without the buffer rings.

axes

"m" shows the map's own axes (metres); "longlat" keeps the map projection and draws a graticule labelled in degrees; "none" draws no axes and no box.

metrics

A table with one row per ELF: an ELF column (the post-merge names, e.g. "11.1_2") and the values to map, e.g. from readELFmetrics(). NULL (default) maps none.

metric

The column of metrics whose values fill the cores, drawn over the other fills; ELFs without a value keep theirs.

metricCol, metricTitle, metricRange

The colours (a vector, as col of terra::plot()), the legend title and the value range (two numbers, e.g. c(0, 100), fixing the colour scale) of metric. NULL (default) takes terra's colours, metric as the title and the range of the values. With plotFires, the colours and title left NULL are the green-to-red ramp and the name of the rate.

plotFires

NULL (default), "number", "density", "area" or "proportion": fill the cores with the mean natural ignitions per year, the mean natural ignitions per 100 km^2 of core per year, the mean area burned per year (ha), or the mean proportion of the core burned per year, over fireYears, from ELFfireRates(), on a green (less) to red (more) ramp. Arctic and Prairie grassland ELFs, which are not counted, keep their fill. Not with metrics.

...

Passed to fewFireELFs() when plan is NULL, e.g. pixelAreaHa (default 5.76) or fireYears (default defaultFireYears()).

Details

With these five points in mind, we define *Ecologically-based Low Fractal-dimensional polygons, "ELFs", that are constrained by large ecological zones (Canadian Ecozones), are "larg-ish", more "blobby" (low fractal dimension) than other ecological zonation in mountains (which tend to follow elevation contours), and are each buffered (default 20km).

Value

A list of length 2, with rasWhole and rasCentered. Each of these will have the complete list of ELFs. rasWhole is the whole map of Canada with the individual ELF highlighted, and rasCentered is just the individual ELF centred and reprojected so its projected parameters are: long0 is the x mid, and lat0 = ymin and lat1 = ymax of the individual ELF. This will create ELFs with the least amount of pixel deformation.

See Also

fireSenseCloudParameters()


Identify each year's individual fires and buffer them accordingly

Description

Identify each year's individual fires and buffer them accordingly

Usage

makeFireIDs(
  year,
  fireRaster,
  flammableRTM,
  bufferForFireRaster,
  areaMultiplier,
  minSize = 5000,
  verb = 1
)

Arguments

year

numeric fire year

fireRaster

a SpatRaster with values representing fire years

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

bufferForFireRaster

buffer size used to group discrete patches of burned pixels as belonging to the same fire

areaMultiplier

A scalar that will buffer areaMultiplier * fireSize

minSize

The absolute minimum size of the buffer & non-buffer together. This will be imposed after areaMultiplier.

verb

Logical or numeric related to how much verbosity is printed. FALSE or 0 is none. TRUE or 1 is some. 2 is much more.

Value

a data.table with fire ID, buffer status, and pixelID


Prepare NTEMS Land Cover Data for Fire Simulation Models

Description

Processes NTEMS Land Cover Classification (LCC) data for a specific year, adjusting non-flammable classes based on a flammability threshold during reprojection to a target raster's resolution and extent.

Usage

makeFireSenseLCC(
  neededYear,
  to,
  maskTo = NULL,
  nonflammableLCC = fireSenseNonflammableLCC,
  flammabilityThreshold = fireSenseFlammabilityThreshold,
  writeTo = NULL,
  overwrite = TRUE,
  destinationPath,
  lccSource = getOption("fireSense.lccSource", "SCANFI"),
  scanfiVersion = fireSenseSCANFIVersion
)

Arguments

neededYear

Numeric. The specific year required for the NTEMS Land Cover Classification (LCC) data.

to

A SpatRaster (or raster-like) template defining the resolution, extent, and CRS that the output LCC raster will be aligned to. Forwarded to reproducible::postProcessTo(to = ...).

maskTo

Optional. A SpatVector / SpatRaster / polygon used to mask the output. Forwarded to reproducible::postProcessTo(maskTo = ...). Default NULL (no extra mask beyond to).

nonflammableLCC

Numeric vector. LCC codes representing non-flammable land cover types (e.g., water, rock, urban). Defaults to fireSenseNonflammableLCC. Pixels with these values are initially masked or converted for thresholding.

flammabilityThreshold

Numeric. A value between 0 and 1. Target pixels where the proportion of underlying flammable source pixels is below this threshold will be reclassified to 0 (non-flammable) in the output raster. Defaults to 0.1.

writeTo

Character string or NULL. Optional filename for the output LCC raster, relative to destinationPath. If NULL (default), the raster is not written to disk by this function.

overwrite

Logical. Overwrite NTEMS FAO and flammable pixels rasters.

destinationPath

Character string. Directory path where source NTEMS data will be downloaded/loaded (via prepInputs_NTEMS_LCC_FAO) and where the output raster will be written if writeTo is specified.

lccSource

"SCANFI" (default) or "NTEMS"; the default can be set with options(fireSense.lccSource = ). SCANFI land cover (LandR::prepInputs_SCANFI_LCC_FAO()) has no wetland classes, so they are added from the Canadian Wetland Inventory Map (LandR::prepInputs_CWIM()) with LandR::wetlandToLCC(): wet treed pixels become 81, other wet flammable pixels 80, as in NTEMS. This matches Biomass_borealDataPrep's default land cover. "NTEMS" uses LandR::prepInputs_NTEMS_LCC_FAO(), which has 80 and 81 already, exactly as before.

scanfiVersion

Character. Only used when lccSource = "SCANFI"; forwarded to LandR::prepInputs_SCANFI_LCC_FAO()'s dataVersion. Default "V3" (annual, 1985-2025). The installed LandR is checked for dataVersion = "V3" support before it is called; an older LandR stops with a message asking for one that has it, rather than silently building V2 land cover under a "V3" request.

Details

This function performs several steps:

  1. Downloads and prepares NTEMS LCC data for the specified neededYear using LandR::prepInputs_NTEMS_LCC_FAO, cropping and masking to the target extent. This step is cached on its own with reproducible::Cache() (keyed on its arguments and the code of the functions it calls), so a change to the later steps or their inputs (nonflammableLCC, flammabilityThreshold, writeTo) does not redo it.

  2. Identifies the dominant flammable land cover class within each pixel of to. This is done by temporarily masking non-flammable classes (defined in nonflammableLCC) to NA in the source raster and then reprojecting using the 'mode' method.

  3. Calculates the proportion of flammable cover within each pixel of to by reprojecting a binary (1=flammable, 0=non-flammable) version of the source raster using the 'average' method.

  4. Creates the final raster: Pixels where the proportion of flammable cover (calculated in step 3) is below the flammabilityThreshold are assigned a value of 0 (representing non-flammable). Otherwise, pixels retain the dominant flammable LCC code identified in step 2.

Value

A list of two SpatRaster objects:

  1. the processed land cover classification at the resolution, extent, and CRS of to with values representing either the modal flammable LCC code or 0 if the pixel is below the flammabilityThreshold, and

  2. the proportion of each pixel that is flammable in the native resolution

Examples

## Not run: 
  # Requires terra and potentially LandR installed
  # Need example to and maskTo objects
  library(terra)

  # Create dummy to and maskTo
  ras <- rast(xmin = 0, xmax = 10, ymin = 0, ymax = 10, res = 1)
  values(ras) <- 1
  crs(ras) <- "EPSG:4326" # Example CRS
  sa <- ext(ras) |> as.polygons() |> vect()
  crs(sa) <- crs(ras)

  # Define a destination path (replace with a real path)
  destPath <- tempdir()

  # Run the function (will likely try to download data)
  # Note: prepInputs_NTEMS_LCC_FAO might require specific setup or data sources
  # This example might fail if data download/access isn't configured
  # fireLCC <- makeFireSenseLCC(neededYear = 2011, # Example year
  #                            to = ras,
  #                            maskTo = sa,
  #                            destinationPath = destPath)
  # plot(fireLCC)

## End(Not run)

Functions whose code affects what makeFireSenseLCC() returns

Description

reproducible::Cache() digests only the called function's own code, so a cached makeFireSenseLCC() call keeps returning its old result when a function it calls changes. Pass this list as that call's .cacheExtra and those functions become part of the key.

Usage

makeFireSenseLCCDeps(lccSource = getOption("fireSense.lccSource", "SCANFI"))

Arguments

lccSource

"SCANFI" (default) or "NTEMS"; the default can be set with options(fireSense.lccSource = ). SCANFI land cover (LandR::prepInputs_SCANFI_LCC_FAO()) has no wetland classes, so they are added from the Canadian Wetland Inventory Map (LandR::prepInputs_CWIM()) with LandR::wetlandToLCC(): wet treed pixels become 81, other wet flammable pixels 80, as in NTEMS. This matches Biomass_borealDataPrep's default land cover. "NTEMS" uses LandR::prepInputs_NTEMS_LCC_FAO(), which has 80 and 81 already, exactly as before.

Details

Ask for the list rather than writing one out: which functions are in the path depends on lccSource, which is a run-time option, so a hard-coded list is wrong for the other source and goes stale when the default moves. It already did – fireSense_dataPrepFit pinned LandR::prepInputs_NTEMS_LCC_FAO() and kept it after the default became SCANFI, leaving every SCANFI and CWIM change invisible to the cache.

The base land-cover step inside makeFireSenseLCC() has its own Cache() call, keyed on the first part of this list (the land-cover functions only), so it is not redone when only the later steps change.

Value

A list of functions, to pass as reproducible::Cache()'s .cacheExtra.

See Also

makeFireSenseLCC()

Examples

## Not run: 
  Cache(makeFireSenseLCC(neededYear = 2020, to = rtm, destinationPath = dPath),
        .cacheExtra = makeFireSenseLCCDeps())

## End(Not run)

Wrapper on glm that creates separate GLMs for each item in fuel

Description

Wrapper on glm that creates separate GLMs for each item in fuel

Usage

makeGLM(fuel, landscape, form)

Arguments

fuel

vector of tree species or LCC in landscape by which to subset

landscape

created by fuelClassPrep

form

the formula to use - as a character


Create landcoverDT object to classify and track non-forest land cover classes

Description

Create landcoverDT object to classify and track non-forest land cover classes

Usage

makeLandcoverDT(rstLCC, flammableRTM, forestedLCC, nonForestedLCCGroups)

Arguments

rstLCC

landcover raster

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

forestedLCC

vector of values representing forested landcover classes in rstLCC

nonForestedLCCGroups

a named list of non-forested flammable landcover groups

Value

a data.table with columns for pixelID and binary presence of landcover


Convert a list of SpatialPointsDataFrame object to a list of data.table objects

Description

Must supply a raster so that points can be converted to the cells on a raster. It is assumed that the sizeCol is accurate. If not, it should be recalculated before this function call.

Usage

makeLociList(
  ras,
  pts,
  idsCol = "FIRE_ID",
  dateCol = "YEAR",
  sizeCol = "POLY_HA",
  sizeColUnits = "ha",
  yearPrefix = "year"
)

Arguments

ras

A raster that will be the template for cells (pixel ids)

pts

A list of sf point objects

idsCol

Character string identifying column name in pts that has unique id per event (i.e., fire)

dateCol

Character string identifying column name in pts that has year

sizeCol

Character string identifying column name in pts that has size of individual event. Can be in hectares or metres squared. Should set sizeColUnits

sizeColUnits

Character string. Either "ha" or "m2".

yearPrefix

Character string prefixed to each year when naming the output list elements (e.g. "year" produces "year2001", "year2002", ...). Default "year".

Value

A list of data.table objects, each with 4 columns, "size" (in pixels), "date", "ids" from idsCol, and "cells", which are the pixel indices of the pts points.


guarantees mutually exclusive values in a data table

Description

guarantees mutually exclusive values in a data table

Usage

makeMutuallyExclusive(dt, mutuallyExclusiveCols = list(youngAge = c("vegPC")))

Arguments

dt

a data.table with columns that should be mutually exclusive

mutuallyExclusiveCols

A named list, where the name of the list element must be a single covariate column name in dt. The list content should be a "grep" pattern with which to match column names, e.g., "vegPC". The values of all column names that match the grep value will be set to 0, whenever the name of that list element is non-zero. Default is list("youngAge" = list("vegPC")), meaning that all columns with vegPC in their name will be set to zero wherever youngAge is non-zero. Patterns are matched anchored to the start of the column name, and the key column itself (cov1) is never zeroed, even if it matches its own pattern.

Value

a data.table with relevant columns made mutually exclusive


Put cohortData back into a SpatRaster with some extra details

Description

Put cohortData back into a SpatRaster with some extra details

Usage

makeRastersFromCD(class, cohortData, flammableRTM, pixelGroupMap)

Arguments

class

fuelClass from sppEquiv

cohortData

A data.table with columns: pixelGroup, ecoregionGroup, speciesCode, and optionally age, B, mortality, aNPPAct, and sumB.

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

pixelGroupMap

A RasterLayer with pixel values equal to a pixel group number that corresponds exactly to pixelGroup column in cohortData.

Value

a SpatRaster with values equal to class biomass (B)


Prepare a time since disturbance map from stand age and fire data

Description

Combines an initial stand age map with disturbance (fire) history to produce a time-since-disturbance (TSD) raster. Stand age is trusted for most pixels, but for pixels whose stand age is unreliable (e.g. non-forest land cover) the fire history is used instead: a recorded recent burn sets the TSD, while the absence of one marks the pixel as old (cutoffForYoungAge + 1).

Usage

makeTSD(
  year,
  firePolys = NULL,
  fireRaster = NULL,
  standAgeMap,
  lcc = NULL,
  cutoffForYoungAge = fireSenseYoungAgeCutoff,
  pixToUpdate = NULL,
  flammablePixels = NULL
)

Arguments

year

the year represented by standAge.

firePolys

list of spatialPolygon objects comprising annual fires. fireRaster will supersede firePolys if provided.

fireRaster

a RasterLayer with values representing fire years.

standAgeMap

initial stand age map

lcc

Optional data.table with landcover values, i.e., landcoverDT (see makeLandcoverDT()). When supplied, pixToUpdate and flammablePixels are derived from it unless they are passed explicitly. Specific to fireSense_dataPrepFit; for general use prefer pixToUpdate / flammablePixels.

cutoffForYoungAge

Numeric. Default is 15. This is the age below which the pixel is considered "young" –> youngAge column will be 1 if age <= 15

pixToUpdate

Optional integer vector of pixelIDs whose age should be taken from fire history rather than standAgeMap (e.g. pixels with no reliable stand age). If NULL and lcc is supplied, these are the non-forest pixels in lcc (those with a positive sum across the non-forest landcover columns).

flammablePixels

Optional integer vector of flammable pixelIDs. Pixels not in this set are set to NA in the output (non-flammable). If NULL and lcc is supplied, this is lcc$pixelID. If NULL and lcc is not supplied, no pixels are masked to NA.

Details

Which pixels to update from fire history, and which pixels are flammable, can be supplied in one of two ways:

  • directly, via pixToUpdate and flammablePixels (general purpose); or

  • via lcc, the landcoverDT produced by fireSense_dataPrepFit, from which both are derived (non-forest pixels are updated, and lcc$pixelID defines the flammable mask). This is retained for backwards compatibility.

Value

a SpatRaster with values representing time since disturbance


Merge ELF maps as planned

Description

Replaces the members of each merge in ELFmergePlan() by one ELF. Its rasWhole layer is the cell-by-cell maximum of the members' layers, so a cell that is core in any member is core. A buffer drawn around the union of cores equals the union of the members' buffers, so the buffer does not need redrawing. Its rasCentered layer is that map projected onto a Lambert conformal conic centred on the merged core, as makeELFs() centres each ELF. Its poly rows are rebuilt from the merged layer the way makeELFs() builds them.

Usage

mergeELFs(ELFs, plan)

Arguments

ELFs

list with rasWhole and rasCentered (named lists of SpatRaster) and optionally poly, as returned by makeELFs().

plan

data.table from ELFmergePlan().

Value

ELFs, with each merge's members replaced by the merged ELF.


Build ignition covariates table by stacking/extracting rasters and joining lightning

Description

For each year (or year period) provided, stacks and extracts covariates from coarse fuel rasters (split into forested vs. non-forested LCC groups) and climate, at ignition point locations, then merges results across years, filters unusable pixels, appends lightning summaries, and orders columns. Results are optionally cached.

Usage

mergePreparedCovs(
  years,
  fuelCovsCoarse,
  ignitionFirePoints,
  nonForestedLCCGroups,
  ignitionClimateCoarse,
  lightningMap,
  digest,
  useCache = TRUE
)

Arguments

years

A vector or list of year identifiers passed to stackAndExtract(). Can be a list matching the structure of fuelCovsCoarse/ignitionClimateCoarse.

fuelCovsCoarse

A list (possibly nested by year) of named raster-layer collections (e.g., terra::SpatRaster or lists of SpatRaster) representing fuel-related covariates. Names must overlap with LCC group names used to split forested vs. non-forested classes.

ignitionFirePoints

Ignition point locations (e.g., sf/sp points or a data.frame convertible by stackAndExtract) used for extraction.

nonForestedLCCGroups

A named vector or list whose names identify the LCC (land-cover) classes considered non-forested. These names are used to split fuelCovsCoarse into LCC (non-forested) and fuel (forested/other) inputs.

ignitionClimateCoarse

A list (possibly by year) of coarse climate rasters (e.g., terra::SpatRaster) to include in the stack-and-extract process. The names of this list are used as userTags in caching and are later treated as climate column names when computing row-wise cover sums.

lightningMap

A named terra::SpatRaster (or a named list coercible to one) containing one or more lightning-derived layers (e.g., "lightningDays"). These values are looked up by pixelID and appended as columns.

digest

A cache key supplement (character or list) forwarded to reproducible::Cache() via .cacheExtra to ensure cache correctness for large inputs omitted from the hash.

useCache

logical (default TRUE). If TRUE, wrap the Map call in reproducible::Cache() with omitArgs = c("fuel", "LCC"), .cacheExtra = digest, and userTags = names(ignitionClimateCoarse).

Details

Processing steps:

  1. Calls stackAndExtract() via Map() for each entry in years, splitting fuelCovsCoarse per year into:

    • fuel: all layers not in names(nonForestedLCCGroups)

    • LCC: layers whose names are in names(nonForestedLCCGroups)

    Additional MoreArgs include climate = ignitionClimateCoarse and fires = ignitionFirePoints.

  2. Optionally caches the list of per-year extractions with reproducible::Cache() (function name tagged as "stackAndExtract").

  3. Combines the list to a single data.table via data.table::rbindlist().

  4. Removes rows for which the sum across all cover-type columns is zero (computed as rowSums(.SD) over all columns except ignitions, yearTxt (from fireSenseUtils), cell, and the climate variable names).

  5. Renames the cell column to pixelID, coerces year to numeric, and appends lightning columns by indexing terra::values(terra::rast(lightningMap)) with pixelID.

  6. Optionally reorders columns to place pixelID, ignitions, climate columns (i.e., names(ignitionClimateCoarse)), and youngAgeTxt (if it exists) first.

Assumptions / Requirements:

  • fireSenseUtils::stackAndExtract() must accept arguments years, fuel, LCC, climate, and fires, and return a data.table-like object with at least cell, ignitions, and year (or yearTxt) columns.

  • fireSenseUtils::yearTxt is used as a column name to exclude from cover sums; ensure it exists/aligns with the data produced by stackAndExtract().

  • youngAgeTxt is referenced when establishing column order but is not defined in this scope; if unavailable, it is silently omitted.

  • pixelID is assumed to be a valid row index into lightningMap raster values.

Lightning layer choice: The code appends all layers provided in lightningMap. If a single best-performing layer is known (e.g., "lightningDays"), subset lightningMap before calling this function.

Caching: Large raster inputs are excluded from the cache key via omitArgs = c("fuel", "LCC"); the caller-supplied digest should capture the salient identity of those omitted objects to avoid cache collisions.

Value

A data.table of ignition covariates with:

  • pixelID (formerly cell)

  • ignitions

  • Climate covariate columns (names derived from ignitionClimateCoarse)

  • Cover/class covariates retained from stackAndExtract() (filtered to rows with non-zero cover sum)

  • Lightning-derived columns appended from lightningMap

  • year coerced to numeric

Potential pitfalls

  • If pixelID indexes are not aligned with lightningMap cell indices, appended lightning values will be incorrect; ensure consistent indexing/resolution.

  • If fireSenseUtils::yearTxt is absent in the returned data, the exclusion in .SDcols is harmless, but confirm that the intended year column exists for analysis.

  • If youngAgeTxt is not defined, it will be ignored when reordering columns.

See Also

fireSenseUtils::stackAndExtract, reproducible::Cache, data.table::rbindlist, terra::rast, terra::values

Examples

## Not run: 
# Pseudocode, assuming you have compatible inputs prepared:
yrs <- list(`2001` = 2001L, `2002` = 2002L)
# fuelCovsCoarse[[year]] is a named list or SpatRaster with LCC class names
# ignitionClimateCoarse[[year]] is a SpatRaster of climate layers
# ignitionFirePoints are point locations (sf/sp/data.frame accepted by stackAndExtract)
# lightningMap is a named SpatRaster (e.g., "lightningDays")

out <- mergePreparedCovs(
  years = yrs,
  fuelCovsCoarse = fuelCovsCoarse,
  ignitionFirePoints = ignitionFirePoints,
  nonForestedLCCGroups = c("Shrub", "Grass", "Bare"),
  ignitionClimateCoarse = ignitionClimateCoarse,
  lightningMap = lightningMap["lightningDays"],
  digest = list(seed = 1L, cfg = "v1"),
  useCache = TRUE
)
data.table::str(out)

## End(Not run)

Buffer-size multiplier for fire footprints

Description

Returns a per-fire buffer target (in pixels) by scaling size so that small fires get proportionally larger buffers and large fires plateau at baseMultiplier * size: max(minSize, max(baseMultiplier, logIntercept - logSlope * log(size)) * size). Used when generating non-burned "control" pixels around historical fire perimeters; fireSense_dataPrepFit uses 10 times this (areaMultiplier).

Usage

multiplier(
  size,
  minSize = 500,
  baseMultiplier = 7.5,
  logIntercept = 21,
  logSlope = 2
)

Arguments

size

Numeric vector. Fire sizes in pixels.

minSize

Numeric scalar. Absolute floor on the returned size; the buffer (plus burned pixels) is never smaller than this. Default 500.

baseMultiplier

Numeric scalar. Asymptotic multiplier for large fires (as size grows, the effective multiplier tends to baseMultiplier). Default 7.5.

logIntercept, logSlope

Numeric scalars. The multiplier of smaller fires, logIntercept - logSlope * log(size), until it falls to baseMultiplier. Defaults 21 and 2.

Details

The defaults (with that factor 10) make a simulated fire that is cut at the buffers' open edge (bufferOpen()) while still smaller than its observed fire rare, so the spread objective (the per-fire "crps" term) is the same as with no buffers. They are the smallest buffers (over the observed fires of three ELFs) that keep that rate at or below 1e-4 per fire and replicate in every size class of known-truth simulations (2026-10-23): a buffer of about 135 times the size at 9 pixels, 70 times from 100 to 10,000 pixels, 55 times at 18,000 pixels. They cost about what the previous defaults (minSize = 1000, baseMultiplier = 5, logIntercept = 14, logSlope = 1) did, with 1.13 times the buffer pixels; with them the fitted parameters on buffers matched those on the whole ELF.

Value

Integer vector the same length as size, giving the target buffered area in pixels for each fire.


Must this run fit, given doFit and the ledger?

Description

Must this run fit, given doFit and the ledger?

Usage

mustFit(doFit, hasLedgerFit, polygon = "")

Arguments

doFit

NA, TRUE or FALSE, as returned by resolveDoFit().

hasLedgerFit

logical: does the ledger hold a usable fit for this polygon? Evaluated lazily, only when doFit is not TRUE, so a forced fit never consults the ledger.

polygon

the polygon identifier, for the error message.

Value

TRUE to fit, FALSE to use the ledger's fit. Stops when doFit is FALSE and the ledger has no usable fit.


Rows where an interaction is cleared by mutual exclusivity

Description

The rows of dt where makeMutuallyExclusive() zeroes a covariate of an interaction a:b of colsToUse (the same patterns, matched anchored to the start of the column name, and the same rows: where the key column is non-zero). The interaction is 0 there, whatever centring did to its covariates.

Usage

mutuallyExclusiveRows(dt, mutuallyExclusiveCols, colsToUse)

Arguments

dt

a data.table with the key columns (e.g. youngAge), before centring.

mutuallyExclusiveCols

as for makeMutuallyExclusive(); NULL clears nothing.

colsToUse

the design columns, from spreadDesignCols().

Value

a named list, by interaction, of row indices (integer(0) when none).


NFDB fire points in a study area, of every size and cause

Description

NFDB fire points in a study area, of every size and cause

Usage

nfdbFirePoints(shp, years, studyArea)

Arguments

shp

path of the NFDB point shapefile.

years

integer years to keep.

studyArea

polygon to crop to; the result is in its CRS.

Value

spatial points, with YEAR and SIZE_HA harmonized by fireregimetools.


The study area's NFDB fire points of the given causes, one row per fire

Description

The fires of years in studyArea (nfdbFirePoints()), of causes (pointsOfCauses()), one row per fire (dropRepeatedFirePoints()): fireSense_dataPrepFit's ignitionFirePoints, and the fires whose sizes fireSense_burn draws for the ignitions that do not escape.

Usage

nfdbFirePointsOfCauses(shp, studyArea, years, causes)

Arguments

shp

path of the NFDB point shapefile, e.g. fireRecordShapefile(nfdbPointUrl(), destinationPath); its name carries the release, so a caller can key a Cache() on it.

studyArea

polygon (SpatVector or sf) to crop to; the result is in its CRS.

years

integer years to keep.

causes

cause groups, see fireCauseCodes().

Value

SpatVector of points with YEAR, SIZE_HA and CAUSE.


URL of the National Fire Database point archive

Description

The archive of all fire points, as a shapefile, on the CFS server. The file was NFDB_point.zip; CFS renamed it NFDB_point_shp.zip (with ⁠_txt⁠ and large_fires variants beside it), and the old name returns HTTP 404. The re-download check in getFirePoints_NFDB() and getFirePoints_NFDB_V2() then could not fetch a newer release, so the last copy on disk (fires to 2024) kept being used.

Usage

nfdbPointUrl()

Value

The URL, a character string.


Sizes of the fires that did not escape

Description

Sizes of the fires that did not escape

Usage

nonEscapedFireSizes(fires, escapeSizeHa, sizeCol = "SIZE_HA")

Arguments

fires

Fire points or polygons (sf, SpatVector or data.frame) with a size column in ha.

escapeSizeHa

Size (ha) a fire must reach to count as escaped.

sizeCol

The size column.

Value

Numeric vector (ha) of the positive fire sizes below escapeSizeHa.


Threads for training multi-threaded libraries

Description

The thread budget for work that should be multi-threaded, i.e. training xgboost models. (xgboost otherwise uses every core: restoring one set of saved boosters took 110 s of CPU in 2.3 s on an 80-core host, with many R workers at once. See setXgbThreads() for the default.)

Usage

nThreads(cores = parallel::detectCores())

Arguments

cores

Number of cores on the host.

Details

The count is, in order:

  1. getOption("fireSense.nThreads") if set (e.g. options(fireSense.nThreads = 4));

  2. otherwise min(8, max(2, floor(cores - load))), where load is the host's 1-minute load average (⁠/proc/loadavg⁠). Training therefore gets 2 to 8 threads, based on the free cores. Where the load cannot be read (not Linux), it is taken as 0, i.e. min(8, cores).

Value

Integer, at least 1.


Names of the arguments that are NULL, to give to Cache(omitArgs =)

Description

An argument added to a cached call changes its key even when it is NULL. Omitting it while it is NULL keeps the key of a call made before the argument existed, so the cached result is still found.

Usage

omitNullArgs(...)

Arguments

...

Named arguments.

Value

A character vector: the names of those that are NULL.


Split the character vector of parameters into covPars and logisticPars

Description

DEoptim::DEoptim does not differentiate between the logistic parameters and the covariates. This splits the vector into the correct components. The split is based on the number of covariates. Therefore the number of logistic parameters is deduced from length(pars) - parsModel.

Usage

paramsSeparate(par, parsModel)

Arguments

par

Numeric vector of all parameters. The covariate parameters must be the second group.

parsModel

Integer. The number of covariates.

Value

list of 2 numeric vectors covPars and logisticPars, representing the parameters for the covariates and the logistic equation, respectively.


The SpaDES.core event barriers of a phase

Description

The SpaDES.core event barriers of a phase

Usage

phaseEvents(
  phase = fireSensePhases,
  validates = FALSE,
  profiles = FALSE,
  terms = FALSE
)

Arguments

phase

One of fireSensePhases.

validates

Whether the spread fit validates (its mode contains "validate", or a heldOutFold is set): the "fit" phase then stops after crossValidate, not after run.

profiles

Whether the spread fit only profiles its ledger fit (its mode contains "profile"): the "fit" phase then stops after profileFromLedger, as no run event is scheduled.

terms

Likewise for a spread fit that only scores a pool of parameter vectors (its mode contains "terms"): the "fit" phase stops after termsFromPool.

Value

NULL for "all"; otherwise the events list (.stopBefore, .stopAfter) that SpaDES.core::simInit() takes.


Plot burn summary

Description

Create plot with subplots showing: a) area burned; b) number of fires; c) median fire size.

Usage

plotBurnSummary(
  climateScenario,
  studyAreaName,
  outputDir,
  Nreps,
  years,
  pixelSize,
  simFiles
)

Arguments

climateScenario

character string specifying the name of a CIMP6 climate scenario, including SSP, formatted as in ClimateNA, using underscores as separator (e.g., 'CanESM5_SSP370').

studyAreaName

character string giving the study area name

outputDir

Path specifying the directory to which outputs figures/objects should be saved.

Nreps

the number of simulation replicates/run used to produce summary figures. NOTE: mclapply is used internally, so you should set options(mc.cores = nReps) to take advantage of parallel processing.

years

integer (length 2). start and end years for comparison.

pixelSize

raster pixel (Cell) size

simFiles

Optional character vector of simulation output file paths (e.g. the file column of SpaDES.core::outputs(sim)), used to locate the per-replicate files instead of reconstructing them from outputDir. Needed when the replicate outputs do not live in ⁠<outputDir>/repNN/⁠, e.g. when summarizing runs restored from another machine, or when the replicate directories are unpadded (rep1 rather than rep01). When supplied, the replicates present in simFiles are used, and Nreps is ignored.

Value

list of file names corresponding to the figures and/or objects written to disk


Plot cumulative burn maps

Description

Plot cumulative burn maps

Usage

plotCumulativeBurns(
  climateScenario,
  studyAreaName,
  outputDir,
  Nreps,
  years,
  rasterToMatch,
  simFiles
)

Arguments

climateScenario

character string specifying the name of a CIMP6 climate scenario, including SSP, formatted as in ClimateNA, using underscores as separator (e.g., 'CanESM5_SSP370').

studyAreaName

character string giving the study area name

outputDir

Path specifying the directory to which outputs figures/objects should be saved.

Nreps

the number of simulation replicates/run used to produce summary figures. NOTE: mclapply is used internally, so you should set options(mc.cores = nReps) to take advantage of parallel processing.

years

integer (length 2). start and end years for comparison.

rasterToMatch

A RasterLayer objects to use as the template for all subsequent raster operations (i.e., the one used throughout the simulation).

simFiles

Optional character vector of simulation output file paths (e.g. the file column of SpaDES.core::outputs(sim)), used to locate the per-replicate files instead of reconstructing them from outputDir. Needed when the replicate outputs do not live in ⁠<outputDir>/repNN/⁠, e.g. when summarizing runs restored from another machine, or when the replicate directories are unpadded (rep1 rather than rep01). When supplied, the replicates present in simFiles are used, and Nreps is ignored.

Value

list of file names corresponding to the figures and/or objects written to disk

a file path corresponding to the images and/or objects written to disk


Simulated rep-years beside the observed year

Description

One panel each for the number of ignitions, escapes, area burned in the core and fires of at least the escape size: the histogram of the simulated rep-years with the observed value as a vertical line. Area burned and fire count have two lines, the natural-cause and the all-cause observed value.

Usage

plotHindcastDistributions(reps, observed, title = NULL)

Arguments

reps

data.table with one row per simulated rep-year and columns ignitions, escapes, areaBurnedHa and nFires50 (the rows fireSense_summary writes to hindcast_reps.csv, pooled over parameter sets).

observed

The result of hindcastObserved().

title

Plot title, e.g. the ELF and year.

Value

A ggplot.


Burn-frequency map with the observed fires on top

Description

The cumulative burn map of the simulated rep-years divided by their number (the fraction of rep-years each pixel burned), with the outlines of the observed fire polygons drawn over it.

Usage

plotHindcastMap(
  burnMap,
  nReps,
  firePolys = NULL,
  coreRaster = NULL,
  title = NULL
)

Arguments

burnMap

SpatRaster count of rep-years in which each pixel burned.

nReps

Number of rep-years the count is over.

firePolys

SpatVector of the observed polygons to draw, or NULL.

coreRaster

Optional SpatRaster of the ELF core: the map is masked to it.

title

Plot title.

Value

A ggplot.


Fire-size distribution, simulated and observed

Description

The empirical cumulative distribution of core-clipped fire sizes (at least minHa), pooled over the simulated rep-years, with the observed natural-cause and all-cause fire sizes as step lines.

Usage

plotHindcastSizes(simSizes, observed, minHa = 50, title = NULL)

Arguments

simSizes

Numeric vector of simulated fire sizes (ha) pooled over rep-years (the ha column of hindcast_sizes.csv).

observed

The result of hindcastObserved().

minHa

Sizes below this are left out of both sides (default: 50 ha, the escape size).

title

Plot title.

Value

A ggplot.


Plot historic ignitions, escapes, and area burned

Description

Plot historic ignitions, escapes, and area burned

Usage

plotHistoricFires(
  climateScenario,
  studyAreaName,
  outputDir,
  pixelSize,
  firePolys,
  ignitionPoints,
  simFiles,
  sizeCol = "SIZE_HA"
)

Arguments

climateScenario

character string specifying the name of a CIMP6 climate scenario, including SSP, formatted as in ClimateNA, using underscores as separator (e.g., 'CanESM5_SSP370').

studyAreaName

character string giving the study area name

outputDir

Path specifying the directory to which outputs figures/objects should be saved.

pixelSize

raster pixel (cell) side length (m); a fire larger than one pixel (pixelSize^2 / 1e4 ha) is an escape

firePolys

A sf spatial polygons of historic fire burn areas, from the Canadian National Fire Database.

ignitionPoints

A sf spatial points of historic fire ignitions, from the Canadian National Fire Database.

simFiles

Optional character vector of simulation output file paths (e.g. the file column of SpaDES.core::outputs(sim)), used to locate the per-replicate files instead of reconstructing them from outputDir. Needed when the replicate outputs do not live in ⁠<outputDir>/repNN/⁠, e.g. when summarizing runs restored from another machine, or when the replicate directories are unpadded (rep1 rather than rep01). When supplied, the replicates present in simFiles are used, and Nreps is ignored.

sizeCol

The column of firePolys with the fire size (ha), used both to count escaped fires (larger than one pixel) and to sum the area burned of all fires.

Value

list of file names corresponding to the figures and/or objects written to disk


NFDB fire points of the given cause groups

Description

NFDB fire points of the given cause groups

Usage

pointsOfCauses(points, groups)

Arguments

points

NFDB fire points (SpatVector) with column CAUSE.

groups

Cause groups, see fireCauseCodes().

Value

The rows of points whose CAUSE is in groups.


Ignitions for natural-cause fire polygons that no ignition point matches

Description

Eliot, 2026-10-25: a natural-cause burned-area polygon of at least escapeSizeHa that no natural ignition point matches (see ignitionPolygonPairs()) was still an ignition, and it escaped. It is added at the fire's start point, the one the spread fit uses: starts, the polygon centroids that harmonizeFireData() moved to the nearest burnable pixel of the fire (harmonizeBufferAndPoints(), cleanUpSpreadFirePoints()). Bind the result to the ignition points: each adds one ignition, and escapedIgnitions() then counts it as the polygon's escape.

Usage

polygonIgnitions(
  points,
  polys,
  starts,
  idCol,
  escapeSizeHa,
  pixSizeHa,
  maxDistM = 1000,
  polyCauseCol = polyCauseColTxt,
  naturalPolyCauses = "Natural"
)

Arguments

points

Natural-cause ignition points (SpatVector or sf) with column YEAR.

polys

Fire polygons (SpatVector or sf) with column YEAR, or a list of them (one per year, as firePolys is in fireSense; NULL elements are dropped). Any CRS: they are projected to that of points.

starts

One start point per fire polygon (SpatVector or sf, or a list of them), sharing idCol with polys, e.g. spreadFirePoints after fireSense_dataPrepFit's prepSpreadFitData.

idCol

The fire ID column of polys and starts.

escapeSizeHa

Size (ha) a polygon must reach.

pixSizeHa

Pixel area (ha). A polygon must also be larger than one pixel.

maxDistM

Distance (m) from a polygon's edge within which a point outside it still matches it.

polyCauseCol, naturalPolyCauses

Column of polys holding the cause, and its natural values.

Value

SpatVector of points in the CRS of points, one per unmatched natural-cause polygon that has a start point, with YEAR, CAUSE ("N") and SIZE_HA (the polygon's area), the columns of points that the ignition and escape counts read.


Which arguments a link's cache key leaves out

Description

powerLawGamma and powerLawShape matter only with link = "powerLaw" or "powerLawSmooth"; lowerAsymptote only with "powerLawSmooth" or "richards"; richardsNu only with "richards". An argument that does not matter for the link is left out of the key, so a fit made without it is found as before.

Usage

powerLawOmitArgs(link, shape = spreadPowerLawShape)

Arguments

link

The spread link: NULL, "logistic3pUpper", "powerLaw", "powerLawSmooth" or "richards".

shape

The powerLawShape of the call; default spreadPowerLawShape.

Details

With link = "powerLaw" or "powerLawSmooth", powerLawShape is also left out when it is the default, 1 (the original link), so a fit made before powerLawShape existed is found.

Value

A character vector of argument names, for omitArgs of Cache().


Per-ELF bounds of p_c for the "powerLaw" link

Description

A fit that tries p_c far above the ELF's own threshold (calibratePowerLaw()⁠$p50⁠) only simulates runaway fires that are then rejected. So the upper bound is p50 + margin; the lower bound is that of spreadPowerLawPcBounds. p50 must lie inside those outer limits.

Usage

powerLawPcBounds(p50, margin = 0.005, climateCeiling = FALSE)

Arguments

p50

The calibrated threshold.

margin

Added to p50 for the upper bound.

climateCeiling

TRUE when climate moves pc toward p50 (spreadLinkInputs()): the upper bound is then p50 itself, else a wet year (climate below its reference) would raise pc past p50. Default FALSE.

Value

c(lower, upper) for the maxAsymptote slot.


Predictions from ignition model

Description

Predictions from ignition model

Usage

predictIgnition(model, data, rescaleFactor, lambdaRescaleFactor)

Arguments

model

the model used to fit ignition data (must have a predict method)

data

data for prediction

rescaleFactor

spatial rescaling factor when predicted and fitted data are at different scales. Calculated as: (predResolution/fitResolution)^2

lambdaRescaleFactor

If the data for fitting has been sampled for pseudo-absences, this imposes a new baseline probability of fire occurrences, hence predictions need to be adjusted. If the original fire prob. is (total no. fires)/(total no. fires + total no. absences), and the fire probability imposed by sampling is (total no. fires)/(total no. fires + no. sampled pseudo-absences), to adjust predicted values, one needs to multiply them by (total no. fires + no. sampled pseudo-absences/(total no. fires + total no. absences).

Value

vector of predicted values.


Create and aggregate fuel covariate rasters to a coarse resolution

Description

Creates fuel covariate layers from tabular inputs using fireSenseUtils:::fireSenseCovariatesCreate(), converts the resulting data frame into a raster using SpaDES.tools::rastFromDF(), and aggregates the raster to a coarser spatial resolution with terra::aggregate() using the mean.

Usage

prepare_FuelCovsCoarse(..., rasTemplate, fact, static = NULL)

Arguments

...

Arguments forwarded directly to fireSenseUtils:::fireSenseCovariatesCreate(), defining the inputs and options required to construct fuel covariates.

rasTemplate

A raster-like object (typically terra::SpatRaster) used as a spatial template (extent, resolution, projection) when converting the fuel covariate data frame to a raster.

fact

numeric(1) aggregation factor passed to terra::aggregate(fact = ...), controlling the spatial coarsening scale.

static

NULL (default) or the result of fuelCovsStatic(), made once and passed in every year to skip rebuilding the parts that do not change; ignored if it was made for other pixelIDs, template or fact (see fuelCovsToCoarse()).

Details

The function performs the following steps:

  1. Generates a fuel covariate data frame using fireSenseUtils:::fireSenseCovariatesCreate(...).

  2. Converts the data frame to a raster aligned with rasTemplate via SpaDES.tools::rastFromDF().

  3. Aggregates the raster to a coarser resolution using terra::aggregate(fact = fact, fun = mean). Pixels of rasTemplate without covariates (not flammable) count as no cover, so a coarse cell that is partly non-flammable is not NA (see fuelCovsToCoarse()).

The aggregation is applied across all raster layers (if present), computing the mean of contributing cells.

Value

A terra::SpatRaster containing aggregated fuel covariate layers at the coarser spatial resolution defined by fact. Its attribute "static" is the fuelCovsStatic() the call used: static itself if it fitted, otherwise the one made for this call. Keep it and pass it to the next call (see fuelCovsToCoarse()).

Assumptions and required environment

The function assumes that the following are available:

  • fireSenseUtils:::fireSenseCovariatesCreate() (non-exported API),

  • SpaDES.tools::rastFromDF(),

  • the terra package.

No input validation is performed on the structure of the data returned by fireSenseCovariatesCreate().

Note

This function uses a non-exported function from fireSenseUtils via :::, which may change without notice across package versions.

References

  • terra package reference manual: raster aggregation with aggregate().

  • SpaDES.tools package reference manual: rastFromDF().

  • fireSenseUtils package source code: fireSenseCovariatesCreate() (internal API).

See Also

terra::aggregate(), SpaDES.tools::rastFromDF()

Examples

## Not run: 
fuelCovsCoarse <- prepare_FuelCovsCoarse(
  fuels = fuelTable,
  rasTemplate = templateRaster,
  fact = 4
)

## End(Not run)

Fuel covariate rasters at a coarse resolution, with youngAge resolved for each fire year

Description

As prepare_FuelCovsCoarse(), but the covariates are built once with fireSenseCovariatesCreate(youngAge = FALSE) and then, for each of years, youngAge is set from youngAgeAtYear() over every pixel (time since disturbance of the data year aged to that year, reset by all fires since) and fuel, non-forest land cover and treed wetland are cleared where it is 1, as fireSenseCovariatesCreate(youngAge = TRUE) does for a single year. Fuel is cleared to logMinB(0), the value fireSenseCovariatesCreate() gives a pixel without that fuel. Each year is then aggregated with mean, so youngAge becomes the proportion of young pixels in a coarse cell; non-flammable pixels count as no cover, as in prepare_FuelCovsCoarse().

Usage

prepare_FuelCovsCoarseByYear(
  ...,
  years,
  dataYear,
  nonForest_timeSinceDisturbance,
  firePixelsByYear,
  cutoffForYoungAge,
  rasTemplate,
  fact
)

Arguments

...

Arguments for fireSenseCovariatesCreate().

years

character, fire years ("year2001") to build, all described by the same data year.

dataYear

the year nonForest_timeSinceDisturbance describes.

nonForest_timeSinceDisturbance

SpatRaster of time since disturbance at dataYear (for every pixel, not only non-forest; see makeTSD()).

firePixelsByYear

all fires as pixelIDs by year, see firePixelsByYear().

cutoffForYoungAge

as in fireSenseCovariatesCreate().

rasTemplate

A raster-like object (typically terra::SpatRaster) used as a spatial template (extent, resolution, projection) when converting the fuel covariate data frame to a raster.

fact

numeric(1) aggregation factor passed to terra::aggregate(fact = ...), controlling the spatial coarsening scale.

Value

a list named by years of SpatRasters, each as prepare_FuelCovsCoarse() returns, with a youngAge layer.


Aggregate and cache ignition-related climate rasters

Description

Aggregates a list of ignition-relevant climate rasters to a coarser spatial resolution using terra::aggregate() (mean across source cells) and caches the resulting list with reproducible::Cache(). The cache key is augmented with a robust digest of the input rasters and a caller-provided upstream digest.

Usage

prepare_ignitionClimate(
  ignitionClimateList,
  fact,
  digest = NULL,
  useCache = TRUE
)

Arguments

ignitionClimateList

A named or unnamed list of raster-like objects (typically terra::SpatRaster) representing historical climate variables used in ignition modeling.

fact

numeric(1) aggregation factor passed to terra::aggregate(fact = ...).

digest

A digest object (e.g., list, atomic vector) representing upstream processing context, which will be appended to the input-derived digest when constructing the cache key.

useCache

logical (default TRUE). If TRUE, wrap the per-element aggregation in reproducible::Cache() so that re-running with the same inputs returns the cached result. If FALSE, force recomputation.

Details

The function:

  1. Computes a robust digest of ignitionClimateList using .robustDigest() to capture changes in input rasters.

  2. Appends that digest to the user-supplied digest to form a composite cache key (dig3).

  3. Aggregates each raster via terra::aggregate(fact = fact, fun = mean).

  4. Wraps the aggregated list in reproducible::Cache() with omitArgs = "x" (to exclude the ephemeral list element passed to lapply) and .cacheExtra = dig3 to drive cache invalidation from the composite digest.

All rasters are processed independently via lapply(), preserving list order and names.

Value

A list of aggregated climate rasters (typically terra::SpatRaster), in one-to-one correspondence with ignitionClimateList.

Caching and reproducibility

Cache invalidation is controlled by .cacheExtra = dig3, which combines:

  • a robust digest of the input rasters (.robustDigest(ignitionClimateList)), and

  • the caller-provided digest (e.g., pipeline/module context).

Assumptions and required environment

The symbols .robustDigest() and reproducible::Cache() must be available. No validation is performed on input types. Aggregation is controlled by the fact parameter.

References

  • terra package reference manual: aggregate() (spatial raster aggregation).

  • reproducible package reference manual and vignettes: Cache() and .cacheExtra.

See Also

terra::aggregate(), reproducible::Cache()

Examples

## Not run: 
# Example (requires `terra` rasters and `reproducible` cache setup):
upstreamDigest <- .robustDigest(list(module = "Fire", version = "1.0.0"))
ignitionClimateCoarse <- prepare_ignitionClimate(
  ignitionClimateList = sim$historicalClimateRasters[
    sim$climateVariablesForFire$ignition
  ],
  fact = 4,
  digest = upstreamDigest
)

## End(Not run)

Prepare and cache lightning rasters from Google Drive sources

Description

Downloads, reads, aggregates, and caches multiple lightning-related rasters (e.g., daily flashes, flash density, positive CG counts) using reproducible::prepInputs(), terra::aggregate(), and reproducible::Cache(). The function builds a cache key that combines local processing context (rasterToMatch, igAggFactor, and the lightning reader) with the remote hashes of the Google Drive files, so cached results are invalidated whenever either local parameters or upstream files change.

Usage

prepare_LightningData(rtm, igAggFactor, dPath)

Arguments

rtm

terra::SpatRaster or raster-like object used as the target template (i.e., an alignment/extent/projection reference) for reading lightning rasters.

igAggFactor

numeric(1) aggregation factor forwarded to terra::aggregate(fact = ...), typically used to coarsen lightning rasters for ignition modeling.

dPath

Character. Destination path forwarded to reproducible::prepInputs(destinationPath = ...); the directory where downloaded lightning rasters are stored / cached on disk.

Details

Lightning data is given by the authors of https://www.tandfonline.com/doi/full/10.1080/07055900.2020.1845117 It is currently not hosted by the authors. We therefore host it on Google Drive.

The function maintains an internal mapping of Google Drive file IDs for four lightning products:

  • lightningDays

  • lightningDensity

  • positiveCG

  • positiveCGdensity

For each product, it:

  1. Resolves the Drive ID to a human URL, obtains remote metadata (hash),

  2. Calls reproducible::prepInputs() with a reading function that should return a raster aligned to sim$rasterToMatch,

  3. Aggregates the raster with terra::aggregate(fact = P(sim)$igAggFactor),

  4. Caches the result with reproducible::Cache() under a product-specific function label, seeding the cache with both local and remote digests.

A final Cache() call wraps the list of per-product results to further stabilize caching across the set.

Value

A named list of aggregated lightning rasters (class list of terra::SpatRaster), with names matching: c("lightningDays", "lightningDensity", "positiveCG", "positiveCGdensity").

Caching and reproducibility

The cache key includes:

  • The remote hash of each Google Drive resource (so cloud-side updates bust the cache),

  • The local context digest of rasterToMatch, igAggFactor, and the reader, via .robustDigest.

This design minimizes recomputation while remaining sensitive to upstream and local changes.

Note

If prepInputs() expects a function for fun, prefer:

fun = function(...) rld(targetFile, to = sim$rasterToMatch)

instead of calling rld(...) immediately.

References

  • User-provided function source (this documentation derives from the code you supplied).

  • Reproducible workflows with the reproducible package and raster handling with terra as described in their package manuals and vignettes.

See Also

reproducible::prepInputs(), reproducible::Cache(), terra::aggregate()

Examples

## Not run: 
out <- prepare_LightningData(
  rtm = sim$rasterToMatch,
  igAggFactor = P(sim)$igAggFactor,
  rld = readLightningData
)
out$lightningDensity

## End(Not run)

Prepare and (optionally) cache scaled covariates for modeling

Description

Wraps rescaleCovariates() to rescale features according to the modeling algorithm, and optionally caches results based on a robust digest of the unscaled input data. Returns a list containing the (possibly) rescaled covariates, the modeling formula (if any), per-variable rescalers (if any), the x-axis variable name(s), and the digest used for caching.

Usage

prepareCovariatesOuter(unscaledData, algorithm, rescaleVars, useCache = TRUE)

Arguments

unscaledData

A data.frame or data.table of covariates. Must include predictor columns and may include response columns such as ignitions and/or escapes (see Details).

algorithm

character. Name of the model algorithm. If it contains "xgb", covariates are standardized via base::scale() (centering and scaling); otherwise, covariates are rescaled by order of magnitude to roughly the [0, 10] range (see Details).

rescaleVars

logical. If TRUE, perform rescaling/standardization according to algorithm; if FALSE, covariates are returned unchanged.

useCache

logical (default TRUE). If TRUE, results are cached using reproducible::Cache() with an extra key derived from a digest of unscaledData.

Details

This function:

  • Computes a digest of unscaledData (if useCache = TRUE) using an internal .robustDigest() to form a .cacheExtra key for reproducible::Cache().

  • Calls rescaleCovariates() with formula = NULL and family = NULL (non-xgboost code-paths were removed).

  • Caches the result while omitting the large arguments "covariates" and "formula" from cache key construction (via omitArgs), relying on the explicit digest instead.

Expected columns:

  • ignitions: if present, is preserved through standardization (xgboost path).

  • escapes: if present, is preserved through standardization (xgboost path).

  • year or yr: used to infer xvar (see rescaleCovariates()).

Value

A list with elements:

covariates

A data.table with rescaled/standardized covariates.

formula

NULL (the non-xgboost formula path is disabled).

ignitionRescalers

Named numeric vector of per-variable 10-based rescalers (non-xgboost path) or NULL for xgboost / no-rescale.

xvar

Character vector indicating which year-like column(s) were found.

digestOfData

The digest used for caching, or NULL if useCache = FALSE.

See Also

rescaleCovariates(), reproducible::Cache()

Examples

## Not run: 
library(data.table)
dt <- data.table(pixelID = 1:3,
                 year = c(2001L, 2002L, 2003L),
                 ignitions = c(0, 1, 0),
                 x1 = c(0.01, 2.3, 15))

out <- prepareCovariatesOuter(unscaledData = dt,
                              algorithm = "xgb_classifier",
                              rescaleVars = TRUE,
                              useCache = FALSE)
str(out)

## End(Not run)

Rebuild land cover layers back into a SpatRastser

Description

Given a template raster (e.g., a flammability map) and a data.table containing pixel values for one or more land cover classes, this function reconstructs each class as a raster layer and returns a multi-layer SpatRaster whose layer names match the class names supplied in lcc.

Usage

putBackIntoRaster(lcc, landcoverDT, flammableMap)

Arguments

lcc

character vector. Names of the land cover class columns in landcoverDT to rebuild into raster layers (e.g., c("Conifer", "Deciduous", "Shrub")).

landcoverDT

data.table. A data.table that must contain:

  • a column pixelID with integer indices into the template raster's value vector (as returned by terra::values(flammableMap, mat = FALSE)), and

  • one numeric column per class named in lcc.

flammableMap

SpatRaster. A terra::SpatRaster used as the spatial template (geometry, extent, resolution, and NA mask) for the output layers.

Details

This function:

  1. Creates a working copy of the template raster's values (initialized to 0 on all non-NA cells and keeping original NAs).

  2. For each class name in lcc, it pulls the corresponding vector from landcoverDT, assigns those values into the working vector at positions indicated by landcoverDT$pixelID, and then writes these values back into a fresh terra::rast(flammableMap) layer.

  3. Stacks all layers into a single terra::rast() and sets layer names to lcc.

Assumptions / requirements

  • flammableMap is a terra::SpatRaster providing the spatial geometry, extent, resolution, and NA mask.

  • landcoverDT is a data.table with a column named pixelID that indexes cell positions in the template raster's value vector (i.e., values returned by terra::values(flammableMap, mat = FALSE)). Indices must be valid and 1-based (R-style).

  • Each element of lcc is the name of a numeric column in landcoverDT.

  • All layers are created in the same CRS, resolution, and extent as flammableMap.

Notes

  • Non-NA cells in the template are initialized to 0 before assignment, so only positions referenced by pixelID will receive class values; other non-NA positions remain 0 in each layer.

  • If you want to preserve existing values outside pixelID, modify the initialization step accordingly.

Value

A multi-layer terra::SpatRaster where each layer corresponds to one entry in lcc, with layer names set to lcc.

See Also

terra::rast(), terra::values(), terra::setValues()

Examples

## Not run: 
library(terra)
library(data.table)

# Template raster (5x5 example)
r <- rast(nrows = 5, ncols = 5, vals = NA)
# Mark some cells as valid (non-NA)
values(r) <- rep(NA_real_, ncell(r))
valid_idx <- c(3, 5, 7, 13, 17, 20)
tmp_vals <- values(r, mat = FALSE)
tmp_vals[valid_idx] <- 0
r <- setValues(r, tmp_vals)

# Data table with pixel indices and two classes
dt <- data.table(
  pixelID = valid_idx,
  Conifer  = c(0.6, 0.2, 0.8, 0.1, 0.0, 0.4),
  Deciduous = c(0.1, 0.3, 0.0, 0.4, 0.5, 0.2)
)

# Rebuild layers
out <- putBackIntoRaster(
  lcc = c("Conifer", "Deciduous"),
  landcoverDT = dt,
  flammableMap = r
)

out
names(out)        # "Conifer" "Deciduous"
plot(out)

## End(Not run)

this is a wrapper to simplify caching of lapply with bufferForFireRaster. Years are iteratively processed by makeFireID.

Description

this is a wrapper to simplify caching of lapply with bufferForFireRaster. Years are iteratively processed by makeFireID.

Usage

rasterFireBufferDT(
  years,
  fireRaster,
  flammableRTM,
  bufferForFireRaster,
  areaMultiplier,
  minSize = 5000,
  verb = 1,
  cores = 1,
  seed = .bufferSeed(years, fireRaster, flammableRTM, bufferForFireRaster,
    areaMultiplier, minSize)
)

Arguments

years

numeric fire years

fireRaster

a SpatRaster with values representing fire years

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

bufferForFireRaster

buffer size used to group discrete patches of burned pixels as belonging to the same fire

areaMultiplier

A scalar that will buffer areaMultiplier * fireSize

minSize

The absolute minimum size of the buffer & non-buffer together. This will be imposed after areaMultiplier.

verb

Logical or numeric related to how much verbosity is printed. FALSE or 0 is none. TRUE or 1 is some. 2 is much more.

cores

number of processor cores to use

seed

integer. Seeds the per-year draws of buffer pixels. The default is derived from the other inputs, so the same inputs give the same buffers in any session, whatever the state of its random number generator, and the session's random stream is left untouched. Supply a value to get a different set of buffers for the same inputs.

Value

a list of data.tables named by year, with cols ids, buffer, and pixelID


Create a list of annual ignition points based on fire raster

Description

Create a list of annual ignition points based on fire raster

Usage

rasterFireSpreadPoints(fireBufferDT, flammableRTM)

Arguments

fireBufferDT

a data.table with columns buffer (1 = burned), id (unique fire ID), and pixelID

flammableRTM

@template flammableRTM

Value

a list of sf point objects


Generate random beta variates between 2 values and a mean

Description

Generate random beta variates between 2 values and a mean

Usage

rbetaBetween(n, l, u, m, shape1, shape2 = NULL)

Arguments

n

number of observations. If length(n) > 1, the length is taken to be the number required.

l

scalar numeric for the lower bound.

u

scalar numeric for the upper bound.

m

scalar numeric for the mean.

shape1

non-negative parameter of the Beta distribution.

shape2

If provided, passed to stats::rbeta(). If not, m must be.

See Also

stats::rbeta


Read lightning data

Description

Data is not publicly available; it is currently stored in a User Access Controlled location. Data comes from William Burrows. Please contact him to obtain data. This function will get the data (which is in a .txt format) and do all the necessary sequence of calculations to create a SpatRaster.

Usage

readLightningData(filename, ...)

Arguments

filename

The local filename to read with data.table::fread

...

Passed to postProcess, e.g., to, maskTo

Value

This will return a SpatRaster object with resolution the same as that supplied by to or projectTo. If no SpatRaster is supplied, it will default to resolution of 10000 m (10 km x 10 km).

References

Kochtubajda, B., & Burrows, W. R. (2020). Cloud-to-Ground Lightning in Canada: 20 Years of CLDN Data. Atmosphere-Ocean, 58(5), 316–332. https://doi.org/10.1080/07055900.2020.1845117

Examples

## Not run: 
# The example fetches from a Google Drive folder that requires
# `drive_auth()` credentials. R CMD check runs examples
# non-interactively where no Drive token is available, so the body
# is gated under \dontrun{} to keep docs complete without breaking
# checks.
if (require(googledrive, quietly = TRUE)) {
  crsToUse <- paste("+proj=lcc +lat_0=0 +lon_0=-95 +lat_1=49 +lat_2=77",
                    "+x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs")
  ras <- terra::rast(
    terra::ext(-1115000, -376750, 7267000, 7874000),
    resolution = 250,
    vals = 1,
    crs = crsToUse
  )
  ## Google Drive folder:
  ## <https://drive.google.com/drive/folders/1ftpKKUO8BZcJ9ba4LDWcmF5uQkpRGmku>
  data <- list(
    lightningDays = "1jeKJquhVJsesoNk2EPP1QZkttX3Zwp5c",
    lightningDensity = "12fnhfKtER-JXkl06M4_yZ3GvpZWtQlIr",
    positiveCG = "1bn6cQ23tvPicFLHn1tz4Z3AqDzJI4r60",
    positiveCGdensity = "1GNixhXj1Ex1jT0tWXfhmxef-dX3ze1a4"
  )
  lightning <- Map(
    url = data,
    f = function(url) {
      reproducible::prepInputs(
        url = url,
        fun = readLightningData(targetFile, to = ras),
        destinationPath = file.path(tempdir(), "lightning_data")
      )
    }
  )
}

## End(Not run)

Read the SpreadFit ledger rows for a study area

Description

The rows are chosen spatially, by reproducible::CacheGeo(): those whose polygons intersect domain (the study area), never by ELF name. Used by fireSense_dataPrepFit and, in a run without it, fireSense_dataPrepPredict.

Usage

readSpreadFitLedger(
  spreadFitFilename,
  cloudFolderID,
  domain,
  destinationPath,
  escapeDefinition = NULL
)

Arguments

spreadFitFilename

The module's spreadFitFilename: a file in cloudFolderID, or "latest".

cloudFolderID

The Google Drive folder holding the ledger files.

domain

The study area, an sf object.

destinationPath

Where the ledger files are downloaded.

escapeDefinition

With "latest", the run's escapeDefinition(): rows fitted under another are skipped (see latestSpreadFits()). NULL (default): not checked.

Details

With spreadFitFilename = "latest", the rows come from latestSpreadFits(): for each polygon, the most recent ledger file that has it. CacheGeo() then picks this study area's rows, as it does from a named file. The combined rows go to a local file named by their content (prepInputs() would otherwise find its checksum changed and try to download it).

Value

What CacheGeo() returns: the ledger rows within domain, or NULL.


Read the fitted year effects of national ignition ledgers

Description

The ignition fit stores, per ELF and process, the year effects a hindcast may use (modelList$yearEffects, fireSense_ignitionFit's fittedYearEffects()). This reads them into one long table.

Usage

readYearEffects(ledgerFiles)

Arguments

ledgerFiles

Paths of ledgers fireSenseIgnitionParams_*.rds: a data.frame with one row per ELF (polygonID) and the list columns of ignitionFitAdditionalColNamesTxt (ignition, then escape), each element holding ⁠$modelList$yearEffects⁠.

Value

A data.frame, one row per ledger, ELF, process (ignition, escape) and year: ledger (file name without .rds), ELF, process and year, observed, expected, priorSD (the sd of the prior of the year effect), multiplier and shape. Ledger rows whose yearEffects is NULL (older fits) are skipped with a message. Stops when a file is missing or a ledger has two rows for one ELF.

Examples

x <- data.frame(polygonID = "1.1")
ye <- data.frame(year = 2001:2003, observed = 5, expected = 5, priorSD = 0.5, multiplier = 1, shape = 10)
x$fireSense_IgnitionFitted <- list(list(modelList = list(yearEffects = ye)))
x$fireSense_EscapeFitted <- list(list(modelList = list(yearEffects = ye)))
f <- tempfile(fileext = ".rds"); saveRDS(x, f)
readYearEffects(f)

Remove buffered fires in fireBufferedListDT that are outside flammableRTM

Description

Remove buffered fires in fireBufferedListDT that are outside flammableRTM

Usage

removeBufferedFiresOutsideRTM(fireBufferedDT, flammableRTM)

Arguments

fireBufferedDT

data.table containing indices for buffered annual fires

flammableRTM

a rasterToMatch with binary values where 1 represents flammable pixels, 0 nonflammable, and NA no data

Value

fireBufferedDT excluding fires with indices (burned or unburned) outside flammableRTM


Rescale/standardize covariates for modeling

Description

Applies either order-of-magnitude rescaling to approximately confine features to the [0, 10] range (non-xgboost) or standardization via base::scale() (xgboost path). Preserves key response columns when present.

Usage

rescaleCovariates(formula, covariates, rescaleVars, modelAlgorithm)

Arguments

formula

A model formula or NULL. Non-xgboost paths would parse and validate it, but the surrounding code path currently sets formula = NULL and disables non-xgboost modeling in the caller.

covariates

A data.frame or data.table of covariates and possibly responses (e.g., ignitions, escapes).

rescaleVars

logical. If TRUE, features are rescaled/standardized according to modelAlgorithm. If FALSE, returned unchanged (with ignitionRescalers = NULL).

modelAlgorithm

character. If the string contains "xgb", apply base::scale() (centering and scaling) to all columns except yearChar, ignitions, and escapes. Otherwise, log-10 order-of-magnitude rescaling is applied to all non-excluded covariates whose maxima fall outside [0, 10].

Details

Year variable inference: If any of c("year", "yr") match column names (case-insensitive), xvar is set to the intersection. Otherwise, the code references rows (a TODO), which is undefined here. This appears to be a bug or placeholder and will error unless rows exists in scope; consider providing a default (e.g., NULL) or removing.

Non-xgboost path:

  • Excludes pixelID, ignitions, escapes, year, and yearChar from rescaling.

  • Computes per-variable rescalers <- 10^(floor(log10(abs(max)))) for variables whose maxima fall outside [0, 10].

  • Calls rescaleVarsByMagnitude(covariates, ignitionRescalers) (must exist in scope).

xgboost path:

  • Standardizes numeric columns except yearChar, ignitions, and escapes.

  • Preserves original ignitions and (if present) escapes columns.

  • Attaches centering/scaling attributes under attr(covariates, "scaleData").

External references:

  • Uses ignitionsTxt, escapesTxt and coreFractionTxt to refer to the response columns and the exposure, none of which is scaled. If these are not available, ensure compatible strings are provided (see exported constants below).

Value

A list with elements:

covariates

A data.table after rescaling/standardization.

formula

The input formula (often NULL in current usage).

ignitionRescalers

Named numeric vector of per-variable rescalers (non-xgb) or NULL.

xvar

Character vector with detected year-like column(s) or (bug) rows.

See Also

base::scale()

Examples

## Not run: 
library(data.table)
dt <- data.table(ignitions = c(0,1,0),
                 escapes = c(0,0,1),
                 year = 2001:2003,
                 x1 = c(0.05, 12, 100),
                 x2 = c(5, 6, 7))

# XGBoost-like standardization
out_xgb <- rescaleCovariates(NULL, dt, rescaleVars = TRUE, modelAlgorithm = "xgb_tree")
str(out_xgb)

# Non-xgboost magnitude rescaling
out_other <- rescaleCovariates(NULL, dt, rescaleVars = TRUE, modelAlgorithm = "glm")
str(out_other)

## End(Not run)

rescale function no.2

Description

rescale function no.2

Usage

rescaleKnown2(x, minNew, maxNew, minOrig, maxOrig)

Arguments

x

a vector to be rescaled

minNew

the minimum of the new range

maxNew

the max of the new range

minOrig

the minimum of the original data

maxOrig

the maximum of the original data

Value

the rescaled vector


Rescale a data.table according to a named vector of rescalers

Description

Rescale a data.table according to a named vector of rescalers

Usage

rescaleVarsByMagnitude(dt, rescalers)

Arguments

dt

a data.table of covariates

rescalers

a named vector of rescalers

Value

the data.table with rescaled values


Re-score a population with replication, and pick the best members by their mean

Description

DEoptim evaluates each surviving member only once, so on a noisy objective the values it holds are partly luck: a lucky low draw survives and is reported as "best". Re-scoring the final population several times and ranking by the mean sees through that. In eight FireSense fits (2026-09-17), DEoptim's best member ranked 1st to 6th of 60 by its replicated mean, and the ledger's "5 best" were five copies of that one member.

Usage

rescorePopulation(pop, fn, reps = 10L, cl = NULL, seed = 1L, fnArgs = list())

bestByReplicatedMean(pop, scores, n = 5L)

Arguments

pop

A matrix, one parameter set per row, with the parameter names as column names.

fn

The objective function; called as fn(par, ...) with fnArgs.

reps

Evaluations per member.

cl

A cluster from parallel::makeCluster(), or NULL to evaluate here.

seed

Base seed.

fnArgs

Named list of further arguments to fn.

scores

The output of rescorePopulation() for pop.

n

How many members to return.

Details

rescorePopulation() evaluates every row of pop reps times; each evaluation has its own seed (seed + its index), so the result is reproducible. With a cluster the evaluations run on its workers, which must already hold whatever fn reads from their global environment (as for DEoptim).

Value

rescorePopulation(): a data.table with member (row of pop), rep and value.

bestByReplicatedMean(): a list with params (a data.table, one row per member, best first), objFunVal (their replicated means), objFunValSD and member (their rows in pop). Identical rows of pop count once, so the members returned are distinct.


Resolve the doFit parameter of the FireSense fit modules

Description

fireSense_spreadFit and fireSense_ignitionFit decide whether to fit from one three-valued parameter, doFit: FALSE (the modules' default) never fits (use the ledger fit; stop when there is none), NA fits only when the ledger has no usable fit for the polygon, TRUE always fits (replacing a ledger fit). refitExisting and stopIfNoPreRunFit are deprecated aliases: refitExisting = TRUE is doFit = TRUE; stopIfNoPreRunFit = TRUE is doFit = FALSE (stopIfNoPreRunFit = FALSE only allowed a fit, which is what NA does); when both are set refitExisting wins. A doFit of NA or TRUE is never overridden by an alias. A doFit of FALSE is, because it is the modules' default and so cannot be told apart from an unset doFit. A module that does not have an alias leaves it NA.

Usage

resolveDoFit(
  doFit = NA,
  refitExisting = NA,
  stopIfNoPreRunFit = NA,
  module = "the fit module",
  message = TRUE
)

Arguments

doFit

logical, length one: NA, TRUE or FALSE.

refitExisting, stopIfNoPreRunFit

the deprecated aliases; NA means not set.

module

character; module name used in the deprecation message.

message

logical; send the deprecation message when an alias is set (once per call).

Value

NA, TRUE or FALSE.


Run DEoptim

Description

Provides a wrapper around DEoptim::DEoptim, setting up the multiple cluster connections. This will only work if ssh keys are preconfigured on all machines (if using multiple machines).

termsInDEoptim() is deprecated: it counted every parameter not in the formula as a "logit" term, so the per-year random effect yearSpreadSD was reported as a third logistic parameter. runDEoptim() now names the parameters with names(lower).

Usage

runDEoptim(
  landscape,
  annualDTx1000,
  nonAnnualDTx1000,
  fireBufferedListDT,
  historicalFires,
  itermax,
  initialpop = NULL,
  NP = NULL,
  trace,
  strategy,
  cores = NULL,
  paths,
  libPath = .libPaths(),
  logPath = tempfile(sprintf("runDEoptim_%s_", format(Sys.time(),
    "%Y-%m-%d_%H%M%S")), fileext = ".log"),
  doObjFunAssertions = getOption("fireSenseUtils.assertions", TRUE),
  iterStep = 25,
  lower,
  upper,
  mutuallyExclusive,
  formulaToFit,
  objFunCoresInternal,
  covMinMax = covMinMax,
  tests = "crps",
  maxFireSpread,
  Nreps,
  .c = 0.5,
  DEoptimControl = list(),
  .verbose,
  visualizeDEoptim = logPath,
  .plots = "screen",
  plotEvery = 25L,
  .plotSize = list(height = 1600, width = 2000),
  rep = 1L,
  runName = "",
  progressFile = NULL,
  nCoresNeeded = NULL,
  rescoreReps = 10L,
  sizeLik = "kde",
  sizeLikDf = 5,
  weighted = TRUE,
  adWeight = "auto",
  link = NULL,
  escapeSizeHa = NULL,
  jumpTries = 0,
  jumpMeanDist = 0,
  yearAreaWeight = 0,
  areaDistWeight = 0,
  crpsWeights = NULL,
  gateRefusal = "minLik",
  penaliseRunaways = TRUE,
  runawayEdgeFrac = fireSenseRunawayEdgeFrac,
  runawayEdgeMin = fireSenseRunawayEdgeMin,
  runawayBufferMultiple = NULL,
  profileReps = 0L,
  simulateMembers = 0L,
  penaliseCapHits = NULL,
  covCentre = NULL,
  convergence = NULL,
  climateRef = NULL,
  powerLawPc50 = NULL,
  powerLawGamma = spreadPowerLawGamma,
  powerLawShape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu,
  wholeLandscape = FALSE
)

termsInDEoptim(fireSense_spreadFormula, numParams)

Arguments

landscape

A SpatRaster which has the correct metadata associated with the pixelID and cells of other objects in this function call.

annualDTx1000

A list of data.table objects. Each list element will be from 1 year, and it must be the same length as fireBufferedListDT and historicalFires. All covariates must be integers, and must be ⁠1000x⁠ their actual values.

nonAnnualDTx1000

A list of data.table objects. Each list element must be named with a concatenated sequence of names from names(annualDTx1000), e.g., ⁠1991_1992_1993⁠. It should contain all the years in names(annualDTx1000). All covariates must be integers, and must be ⁠1000x⁠ their actual values.

fireBufferedListDT

A list of data.table objects. It must be same length as annualDTx1000, with same names. Each element is a data.table with columns: buff...TODO: INCOMPLETE

historicalFires

A named list of data.frames (one per year, names matching those of annualDTx1000), each with columns cells (pixel indices of fire ignitions) and size (fire size in pixels). Used as the observed reference against which simulated fires are scored.

itermax

Maximum number of iterations for the DEoptim::DEoptim algorithm. Passed to DEoptim::DEoptim.control.

initialpop

Optional. A matrix or vector specifying the initial population for DEoptim::DEoptim. If NULL, DEoptim::DEoptim generates one. Passed to DEoptim::DEoptim.control.

NP

Optional. The number of population members (individuals) in DEoptim::DEoptim. If NULL, DEoptim::DEoptim sets a default. DEoptim::DEoptim.control.

trace

Integer or Logical. Controls the level of tracing information printed by DEoptim::DEoptim during optimization. Passed to DEoptim::DEoptim.control.

strategy

Integer ⁠[1,10]⁠. Defines the DEoptim::DEoptim strategy variant to use. Passed to DEoptim::DEoptim.control.

cores

A numeric (for running on localhost only) or a character vector of machine names (including possibly "localhost"), where the length of the vector indicates how many cores should be used on that machine.

paths

list of paths containing the cachePath to store cache. Should likely be cachePath(sim). See SpaDES.core::paths.

libPath

Character vector of R package library directories, in order (e.g. a dev library, then a stable one); all are passed to clusters::clusterSetup(), which ships them to the workers, leaving out R's own. They must exist on each machine, though the function will make sure they do internally. Not part of the Cache() key.

logPath

A character string indicating what file to write logs to. This dirname(logPath) must exist on each machine, though the function will make sure it does internally.

doObjFunAssertions

logical indicating whether to do assertions.

iterStep

Integer. Must be less than itermax. This will cause DEoptim::DEoptim to run the itermax iterations in ceiling(itermax / iterStep) steps. At the end of each step, this function will plot, optionally, the parameter histograms (if visualizeDEoptim is TRUE)

lower

Numeric vector. Lower bounds for the parameters being optimized. Passed to DEoptim::DEoptim.

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.

upper

Numeric vector. Upper bounds for the parameters being optimized. Passed to DEoptim::DEoptim.

mutuallyExclusive

If there are any covariates, e.g,. youngAge, that should be considered mutually exclusive, then this can be done here (i.e., "if youngAge is non-zero, should vegPC2 be set to zero"). A named list, where the name of the list element must be a single covariate column name in either annualDTx1000 or nonAnnualDTx1000. The list content should be a "grep" pattern with which to match column names, e.g., "vegPC". The values of all column names that match the grep value will be set to 0, whenever the name of that list element is non-zero. Default is list("youngAge" = list("vegPC")), meaning that all columns with vegPC in their name will be set to zero wherever youngAge is non-zero.

formulaToFit

Passed to DEoptim::DEoptim

objFunCoresInternal

Integer. The number of cores to use for potential parallelization within a single call to the objective function (.objfunSpreadFit()). This is distinct from the parallelization managed by DEoptim::DEoptim across population members.

covMinMax, tests, maxFireSpread, Nreps, .verbose

Passed to .objfunSpreadFit().

.c

Numeric in ⁠(0, 1]⁠. DEoptim's c, the speed of crossover adaptation (used by strategy = 6). Passed to DEoptim::DEoptim.control(); a c in DEoptimControl wins.

DEoptimControl

Named list of further DEoptim::DEoptim.control() settings (for example CR, F, p, reltol), passed through clusters::clusterSetup() to DEoptim. NP is the number of workers the cluster gets.

visualizeDEoptim

Logical. If TRUE, then histograms will be made of DEoptim::DEoptim outputs.

.plots

Character string. Specifies the plot destination device (e.g., "screen", "png", "pdf"). Passed to internal plotting functions (likely via SpaDES.core::Plots()). Default "screen".

plotEvery

Integer. Generations between DEoptim progress figures; the final figures are always drawn. Passed to clusters::DEoptimIterative(). It is not part of the fit's cache key, so changing it does not refit. Default 25.

.plotSize

List specifying plot height and width, in pixels.

rep

Integer. An identifier for the replication number of this optimization run. Used in cache tags and plot filenames. Default 1L.

runName

Character string used to label this run. Forwarded to clusters::DEoptimIterative() and used as a suffix for the cache .functionName so that runs with different runName values get distinct cache entries. Default "" (no suffix).

progressFile

Passed to clusters::DEoptimIterative(): NULL (default) lets it choose ⁠DEoptimProgress_<runName>.csv⁠ in visualizeDEoptim; FALSE writes none; or a path. The file has one row per generation and a FINISHED row at the end. It is not part of the cache key.

nCoresNeeded

Integer. How many workers to request for the DEoptim cluster. NULL (the default) takes deoptimPopulationSize() of length(lower): 30 for 4 to 7 parameters, 40 for 8 to 12, 50 for 13 to 15. DEoptim's NP is set to the number of workers the cluster actually gets, so a smaller allocation means a smaller population.

rescoreReps

Integer. After the fit, each member of the final population is evaluated this many more times and the result is attached to the returned object as attr(DE, "finalRescore"), for bestByReplicatedMean(). 0 skips it.

sizeLik, sizeLikDf, weighted, adWeight

Passed to .objfunSpreadFit(), in the fit AND in the final-population re-score, so both evaluate the same objective. The defaults are that function's. Before these existed, every fit used those defaults whatever the caller wanted.

link

Passed to .objfunSpreadFit() in the fit and the re-score: NULL, "logistic3pUpper" or one of spreadLinearLinks. Needed because DEoptim may hand the objective an unnamed par.

escapeSizeHa

Passed to .objfunSpreadFit() in the fit and the re-score: the size (ha) a fire must reach to count as escaped. NULL keeps the historical rules.

jumpTries, jumpMeanDist, yearAreaWeight, areaDistWeight

Passed to .objfunSpreadFit(), in the fit and the final-population re-score. Off by default (0).

crpsWeights, gateRefusal

Passed to .objfunSpreadFit(), in the fit and the final-population re-score: the weights of its tests = "crps" objective (NULL, the default, is crpsWeightsDefault(); its annualArea weight, 0 by default, adds each year's area burned), and whether a year that fails the spread probability gates is scored as refused ("minLik", default) or simulated ("simulate"). With the defaults they add nothing to the fit's cache key.

penaliseRunaways

Passed to .objfunSpreadFit() in the fit and the re-score: TRUE (default) stops a simulated fire at the first open edge pixel of its buffer; it is cut either way. The edge and open pixels of every buffer are found here, once (addBufferEdge()).

runawayEdgeFrac, runawayEdgeMin, runawayBufferMultiple

Passed to .objfunSpreadFit(), which ignores them (see there); a non-NULL runawayBufferMultiple warns once.

profileReps

Integer. If above 0, profileCoefficients() is run around the best member of the re-score, each point evaluated this many times, and attached as attr(DE, "profile"). Needs rescoreReps > 0. Costs about 6 * nCoefficients * profileReps evaluations.

simulateMembers

Integer. If above 0, that many best members of the re-score simulate the observed fires without the size cap (simulateFireSizes()), attached as attr(DE, "fitSims") for scoreFireSizes() and linkSaturation(). Needs rescoreReps > 0.

penaliseCapHits

Deprecated and ignored; use penaliseRunaways.

covCentre

Passed to .objfunSpreadFit() in the fit, the re-score and the profile and simulation diagnostics: values subtracted from the rescaled covariates, from spreadCovCentre() when the formula has an intercept. NULL (default) centres nothing, and then the call, and so its cache key, is what it was before this argument existed.

convergence

NULL (default: clusters' options and defaults decide) or a list with any of window, minGenerations, se, sdChange: when clusters::DEoptimIterative() stops a fit whose population has stopped improving (see clusters::deoptimConvergence()). Unlike plotEvery, it is part of the fit's cache key when not NULL; clusters does not put it in any generation's key, so a fit that stopped early resumes from its cached generations and continues under a stricter rule.

climateRef

Passed to .objfunSpreadFit() in the fit, the re-score and the profile and simulation diagnostics: NULL (default) keeps climate under the maxAsymptote ceiling, and the call and its cache key are what they were; a named numeric (spreadClimateRef()) takes climate outside the ceiling (spreadProbFromCovs()).

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.

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.

powerLawShape

The "powerLaw" link's curvature exponent shape (powerLawLink()), fixed, passed like powerLawGamma. At its default, 1, it is left out of the cache keys and the re-score's arguments, so fits made before it existed are found.

lowerAsymptote, richardsNu

The lower asymptote of the "powerLawSmooth" and "richards" links and the nu of "richards" (powerLawSmoothLink(), richardsLink()), fixed, passed like powerLawGamma. Used only with those links; with any other link they are left out of the cache keys and the re-score's arguments (powerLawOmitArgs()).

wholeLandscape

Passed to .objfunSpreadFit() in the fit and the re-score: TRUE spreads every fire on all pixels of annualDTx1000 (the whole landscape's tables), see there. FALSE (default) adds nothing to the fit's cache key; then a fitted ignition outside every buffer of its year (where spreadProb is 0) is warned about once.

fireSense_spreadFormula

The formula to be submitted to DEoptim::DEoptim(), from e.g., sim$fireSense_spreadFormula.

numParams

The number of parameters (TODO: improve description)

Value

The result of the clusters::DEoptimIterative() call. This is typically a list where each element contains the DEoptim::DEoptim object state after a block of iterStep iterations. The final element represents the state after itermax iterations or upon early stopping.


Run the ELFs module and return the ELF names or maps

Description

Extracting only the "ELF" module, runs it via SpaDES.core::simInitAndSpades2() and returns the vector of polygon IDs from spreadFitPreRun, or the ELF maps. The run is not cached here: the module caches the national ELF list itself, keyed on its ELFversion parameter alone and shared through the cloud cache, so a run only downloads it.

Usage

runELFs(
  preRunSetupProject,
  whatOut = c("fittedNamesOnly", "allNames", "maps"),
  urlELFresults = paste0("https://drive.google.com/file/d/",
    "1tkC944mPzR9-y-qCMDB5o2cAR_1MoDz4/view?usp=drive_link")
)

Arguments

preRunSetupProject

list. A SpaDES project object prepared for SpaDES.core::simInitAndSpades2(), containing $modules and $paths$modulePath.

whatOut

string. One of c("fittedNamesOnly", "allNames", "maps" ). Partial matching is active (i.e., fit will do fittedNamesOnly). Will default to the first one if more than one supplied. If not fittedNamesOnly nor allNames, then will do maps. fittedNamesOnly will return the vector of the .ELFind names that have ⁠SpreadFit`` values in the Cloud Geo Cache. ⁠allNames⁠will return all .ELFind names, even if they have no fits.⁠maps⁠or not one of the first two options, will return a list of length 2, each with length⁠NROW(names(.ELFinds))⁠. These are individual rasters, one per .ELFind, either with the entire map of Canada (⁠rasWhole⁠) or with a projection centered on the centroid of the ELF (⁠rasCentred').

urlELFresults

Unused and deprecated; kept so existing calls still work. runELFs() no longer reads this Google Drive file or uploads to it.

Details

The function:

  1. Restricts preRunSetupProject$modules to entries matching "ELFs".

  2. Initializes and runs the simulation with SpaDES.core::simInitAndSpades2().

  3. Returns sim$spreadFitPreRun[[fireSenseUtils::polygonIDTxt]], or the names or maps chosen by whatOut.

The function expects preRunSetupProject to be a SpaDES project list with at least:

  • $modules: character vector of module names.

  • $paths$modulePath: base directory containing module folders.

Value

A vector corresponding to sim$spreadFitPreRun[[fireSenseUtils::polygonIDTxt]]. Currently, no high arctic ELFs are returned (e.g., Ecoprovinces starting with either 1. or 2.), nor the Prairie grassland ELFs (ecoprovince 10.2, i.e. 10.2 and 10.2.*); see ELFsNotFitted().

Author(s)

Based on the provided code snippet.

See Also

simInitAndSpades2

Examples

## Not run: 
# Assuming 'prj' is a valid SpaDES project list:
# prj <- somePreparationFunction(...)
ids <- runELFs(prj)

## End(Not run)

Run one fireSense job of an ELF

Description

Runs the simulation that SpaDES.project::setupProject() set up, up to the end of phase (phaseEvents()), and returns it. The sim is copied first, so it is not changed.

Usage

runJob(
  sim,
  elf,
  phase = sim$params$fireSense_spreadFit$phase,
  fitQueue = NA,
  afterQueue = NA,
  diagFile = NA,
  rprofPrefix = NA,
  uploadDir = NULL,
  ledger = NULL,
  scenario = list(),
  hindcast = FALSE
)

Arguments

sim

The result of SpaDES.project::setupProject().

elf

The ELF's name, as the queues know it.

phase

One of fireSensePhases; by default the phase parameter of fireSense_spreadFit, or "all" if it has none.

fitQueue

The fit queue's .rds file, or NA.

afterQueue

The inputs queue's .rds file, or NA.

diagFile

A file to source() before the run, or NA.

rprofPrefix

If not NA, the run is profiled with Rprof() to ⁠<rprofPrefix>_<elf>_<pid>.out⁠.

uploadDir

The Google Drive folder that a finished "all" job saves its simList to with SpaDES.project::outSaveTarUpload(), or NULL for no upload. A failed upload only warns.

ledger

A reproducible::CacheGeoLedger() that records each upload, with the ELF itself (studyAreaELF, no buffer) as its polygon, so the run can be found by study area. NULL, the default, records nothing: pass it only for runs others should find, not for experiments.

scenario

A named list of what tells this run apart from others of the same ELF, e.g. list(GCM = "NRV", SSP = 370, rep = 1); one ledger column each.

hindcast

Whether the job is a hindcast, which is not uploaded.

Details

With fitQueue, a "inputs" job is skipped when SpaDES.project::queueSkipForFits() gives a reason (the fits have claimed or will claim this ELF). With afterQueue, a "fit" job first calls SpaDES.project::queueWaitWhile(), so it does not start while that queue is still building the ELF's inputs. Both need SpaDES.project.

Value

The simList, invisibly; NULL if the job was skipped.


SCANFI V2 vegetation years

Description

The years that SCANFI V2 has, every five years from 1985 to 2025. This repeats LandR:::.scanfi_v2_years, which LandR does not export: keep the two in step.

Usage

scanfiV2Years

Every member's objective terms, on common random numbers

Description

Evaluates every row of pop reps times with fn(returnTerms = TRUE): replicate r of EVERY member uses seed seed + r, so members are compared on the same random numbers (rescorePopulation() gives each evaluation its own seed and keeps only the total). The terms can then be re-weighted afterwards without simulating again.

Usage

scorePopulationTerms(
  pop,
  fn = .objfunSpreadFit,
  reps = 1L,
  cl = NULL,
  seed = 1L,
  fnArgs = list()
)

Arguments

pop

A matrix, one parameter set per row, with the parameter names as column names.

fn

The objective function; called as fn(par, ...) with fnArgs.

reps

Evaluations of each member, rep 1 to reps.

cl

A cluster from parallel::makeCluster(), or NULL to evaluate here.

seed

Base seed.

fnArgs

Named list of further arguments to fn.

Value

a data.table, one row per member x rep: member (row of pop), rep, and what fn returns with returnTerms = TRUE. For .objfunSpreadFit(): objective; adTest, pitAD, yearArea and areaDist as the objective added them (WEIGHTED); crpsFire, crpsTotalArea, crpsTop10, crpsAnnualArea and crpsTopShare unweighted; nFires; then, to re-weight, raw_adTest, raw_pitAD, raw_yearArea and raw_areaDist (before their weights) and the weight of every term, ⁠w_<term>⁠. objective is the sum over terms of weight x unweighted value. A term the objective did not use is NA (adTest, pitAD, yearArea and areaDist when their tests are off); with returnTerms, crpsAnnualArea and crpsTopShare are computed even at weight 0, so they can be weighted up afterwards.


Set the number of threads xgboost uses in this session

Description

Sets xgboost's global nthread (xgboost::xgb.set.config()). It covers restoring saved boosters (readRDS(), a cache restore) and predict(), which do not take their own nthread. The default is 1, applied when fireSenseUtils is loaded (a booster is restored before any module code runs when a cached event is read back). To change it, set options(fireSense.nThreads = N) before loading the package, or call setXgbThreads(N). Code that trains boosters passes nthread = nThreads() itself. Other packages that use xgboost should set their own nthread; this does not manage them.

Usage

setXgbThreads(n = getOption("fireSense.nThreads", 1L))

Arguments

n

Number of threads; default getOption("fireSense.nThreads", 1).

Value

n, invisibly.


Path to the land-cover map the size rule uses

Description

SCANFI v2 land cover for 2020 in Canada LCC class codes, the same map and source as LandR::prepInputs_SCANFI_LCC_FAO() starts from. The file's name carries its release, so a copy in destinationPath or getOption("reproducible.inputPaths") is used as it is; otherwise it is downloaded from LandR's SCANFI mirror, which needs no Google login.

Usage

sizeRuleLandCover(destinationPath)

Arguments

destinationPath

Directory to download into.

Value

Character path of the .tif.


The climate covariates of a spread formula

Description

The covariates of the formula that are annual (columns of annualDTx1000) and not 0/1 indicators (youngAge, ⁠nfLCC_*⁠, treedWetland; see spreadIndicatorRanges()): the rule fireSense_spreadFit uses to require a fixed range for a climate covariate.

Usage

spreadClimateCols(formulaToFit, annualDTx1000)

Arguments

formulaToFit

The spread formula, a character string or a formula.

annualDTx1000

The annual covariate tables, as in .objfunSpreadFit(); only the column names of the first are used.

Value

A character vector; empty when the formula has no climate covariate.


The climate reference of a spread fit with climate outside the ceiling

Description

With climate outside the ceiling (climateRef of spreadProbFromCovs(); spreadLink = "climateOutside" in fireSense_spreadFit) the climate term is beta_clim * (climate - climateRef), added on the logit of the spread probability after the fuel ceiling. climateRef is the fit's typical climate: the mean of each climate covariate (spreadClimateCols()) over every pixel-year in annualDTx1000, on the scale of the objective's design matrix (rescaled with covMinMax, and centred with covCentre when the fit has an intercept, so then it is 0 up to rounding). It is found once, from the data the objective uses, stored in the ledger row (spreadFitClimateRefTxt), and fireSense_spreadPredict uses the same value, so the fit and the prediction cannot drift apart.

Usage

spreadClimateRef(
  annualDTx1000,
  nonAnnualDTx1000,
  formulaToFit,
  covMinMax = NULL,
  mutuallyExclusive = list(youngAge = c("class", "nf")),
  covCentre = NULL
)

Arguments

annualDTx1000, nonAnnualDTx1000, covMinMax, mutuallyExclusive

As in .objfunSpreadFit().

formulaToFit

The spread formula; the intercept is not a covariate and has no centre.

covCentre

The fit's covariate centres (spreadCovCentre()); NULL without an intercept.

Value

A named list, one mean per climate covariate, to give as climateRef; NULL when the formula has no climate covariate.


The centre of each covariate of a spread fit: its mean over the data the objective uses

Description

With an intercept in the model the covariates are centred (covCentre of .objfunSpreadFit()), so the coefficients describe variation and the intercept the level. The centre is the mean of each covariate of the formula, over every pixel-year in annualDTx1000, after the rescaling and the mutual exclusivity the objective applies and before it centres: the very values it goes on to centre.

Usage

spreadCovCentre(
  annualDTx1000,
  nonAnnualDTx1000,
  formulaToFit,
  covMinMax = NULL,
  mutuallyExclusive = list(youngAge = c("class", "nf"))
)

Arguments

annualDTx1000, nonAnnualDTx1000, covMinMax, mutuallyExclusive

As in .objfunSpreadFit().

formulaToFit

The spread formula; the intercept is not a covariate and has no centre.

Value

NULL when the formula has no intercept (nothing is centred), else a named list, one mean per covariate, to give as covCentre.


The columns of the spread model's design, in the order of its coefficients

Description

The terms of the formula, preceded by spreadInterceptTxt when the formula has an intercept (~ 1 + a + b; the module formulas are ~ 0 + ... and have none). The intercept is a column of 1s that spreadProbFromIntegerCovs() adds after rescaling and centring, so it is multiplied by its coefficient like every covariate, and paramsSeparate(par, length(spreadDesignCols(f))) finds it as the first covariate coefficient. spreadCovCols() drops it. A term of the form a:b is an interaction of two covariates (spreadInteractionCols()): it has its own coefficient, after the main effects.

Usage

spreadDesignCols(formulaToFit)

spreadCovCols(colsToUse)

spreadInteractionCols(colsToUse)

spreadSourceCols(colsToUse)

spreadAddInteractions(DT, colsToUse, cleared = list())

Arguments

formulaToFit

The spread formula, a character string or a formula; NULL gives no columns.

colsToUse

A character vector from spreadDesignCols().

DT

a data.table that has the columns spreadSourceCols(colsToUse), rescaled to 0-1 and centred. Changed by reference.

cleared

a named list (by interaction), the rows of DT where the interaction is 0: mutuallyExclusiveRows().

Value

A character vector.

spreadCovCols(): colsToUse without the intercept, i.e. the columns that are covariates (rescaled, centred, and in covMinMax).

spreadInteractionCols(): the columns of colsToUse that are interactions, "a:b" (a term the formula has as a:b). spreadProbFromIntegerCovs() makes each as the product of its two covariates after they are rescaled, made mutually exclusive and centred, so each main effect is the slope where the other covariate is at its mean; where youngAge cleared a fuel, that fuel's interactions are 0. The product is not centred again.

spreadSourceCols(): the covariates that are columns of the data: those of colsToUse that are not interactions, and the covariates the interactions multiply (even when the formula has no main effect for them). These are the columns that are rescaled, divided by 1000 and centred (spreadCovCentre()).

spreadAddInteractions(): DT, with a column for each of spreadInteractionCols(colsToUse), the product of the two columns it is named for, 0 on the rows in cleared.


Default values for various things

Description

Default values for various things

Usage

spreadFitAdditionalColNames

The climate variables of stored spread fits

Description

Every climate variable any of the ledger rows' fits uses (each ELF chose its own with spread = "auto"), for preparing the climate of prediction, which blends neighbour ELFs.

Usage

spreadFitClimateVariables(ledgerInputs)

Arguments

ledgerInputs

As returned by spreadFitLedgerInputs().

Value

Character vector of ClimateNA names (e.g. "CMD_sm"), each once.


The shared SpreadFit ledger files

Description

fireSense_spreadFit writes each fit as a row of an rds file in a Google Drive folder (its spreadFitGoogleDriveFolder); fireSense_ELFs and fireSense_dataPrepFit read them. With spreadFitFilename = "latest" those modules use these functions instead of one named file.

spreadFuelScale is the scale of the fuel covariates of the spread model (fuelLogToLinear()); fireSense_spreadFit records it in each ledger row (column spreadFitFuelScaleTxt). With the escape definition the row also records (escapeDefinition()), it is what prediction must apply as the fit did, so latestSpreadFits() skips a row whose fuel scale or escape definition differs from this run's. A row written before the fuel scale was recorded counts as spreadFuelScale when its file carries spreadFitFileTag, and is skipped otherwise. A change of model is then recorded by the fit itself: spreadFitFileTag is no longer changed by hand, and only dates the files written before.

latestSpreadFits() returns, for every polygon, its newest usable row in the ledger files (any file of the folder; rows of another fuel scale or escape definition are skipped, see spreadFuelScale): the one with the latest writtenAt (stamped by reproducible::CacheGeoWrite()). A row written before that stamp existed has its file's date instead: the date in the file's suffix (ledgerFileOrder()), else older than any dated file; ties go by the file's modified time. No row is newer than its file was last modified, so files are read newest-modified first; with polygonIDs, reading stops once each has a row newer than the next file. Each file is read with reproducible::CacheGeoRead() into destinationPath: downloaded only if it changed on Drive, and from the local copy when Drive cannot be reached. The folder's file list is saved there too, and used when Drive cannot be reached (a compute node with no internet).

Usage

spreadFitFilenameFor(fireYears, suffix = "")

spreadFitFileTag

spreadFuelScale

spreadFitFuelScaleTxt

latestSpreadFits(
  cloudFolderID = spreadFitLedgerFolder(),
  destinationPath,
  polygonIDs = NULL,
  escapeDefinition = NULL
)

Arguments

fireYears

The fire years the fit used; only the first and last matter.

suffix

Text put after the model tag in the file name, to name an experiment's ledger file, e.g. "_bufIndep20261024" (ending with the date of the fits orders the file among others for "latest", for rows written before writtenAt). A run reads or writes such a file by naming it (spreadFitFilename, ignitionFitFilename); "latest" reads every ledger file of the folder. Experiment files go in the folder's "testing" subfolder (spreadFitLedgerFolder(testing = TRUE)), which "latest" over the main folder never reads.

cloudFolderID

The Google Drive folder (url or id) holding the ledger files; default spreadFitLedgerFolder().

destinationPath

Local folder for the downloaded files.

polygonIDs

Optional. The polygons (ELF ids) wanted; NULL reads every file.

escapeDefinition

This run's escapeDefinition() (e.g. escapeDefinitionOf()): rows fitted under another are skipped. NULL (default): not checked.

Details

spreadFitFileTag marks the files whose fits use the current model: fuel biomass on the linear scale (fuelLogToLinear()), escaped fires starting at 50 ha (escapeSizeHa), and the objective with the annual-area and area-distribution terms. The date (2026-09-25) is when this model started, i.e. the model version. Files with an older tag ("_linearFuel_esc50": the same model before it was dated; "_linearFuel": 1-pixel escape; none: log fuel) hold fits of an earlier model, which fireSense_spreadPredict would apply wrongly; their rows record no fuel scale, so "latest" skips them (see spreadFuelScale).

Value

spreadFitFilenameFor(): the file name a fit over fireYears is written to, e.g. "fireSenseParams_1985-2024_linearFuel_esc50_20260925.rds" (then suffix).

latestSpreadFits(): the ledger rows, in the form fireSense_spreadFit writes them (a data.frame with a geometry column), or NULL when no file matches. Attribute "spreadFitFiles" names the file each polygon came from.


Per-ELF species, fuel and climate inputs from SpreadFit ledger rows

Description

Each row of the SpreadFit ledger is one ELF's fit, with the species table (sppEquiv), non-forest land-cover groups and missing-land-cover group it was fitted with, and its parameters. fireSense_dataPrepFit builds the per-ELF inputs from the ledger it reads before the fit, and fireSense_spreadFit rebuilds them from the ledger after it writes its own row, so prediction in the same run has the new ELF.

spreadFitLedgerInputLists() regroups them into the per-ELF lists that fireSense_dataPrepPredict reads.

Usage

spreadFitLedgerInputs(
  ledger,
  sppEquivCol,
  fuelClassCol,
  studyArea,
  colNames = spreadFitAdditionalColNamesTxt
)

spreadFitLedgerInputLists(ledgerInputs)

Arguments

ledger

data.frame or sf, SpreadFit ledger rows, with columns polygonID (polygonIDTxt), params and the list-columns in colNames.

sppEquivCol

character, the column of sppEquiv naming the species.

fuelClassCol

character, the column of sppEquiv naming the fuel classes.

studyArea

passed to LandR::sppHarmonize(); used only when a row has no sppEquiv.

colNames

character, the list-columns to read (those holding "param" are left out). Columns the ledger lacks (rows written before they existed) are skipped.

ledgerInputs

the result of spreadFitLedgerInputs().

Details

spreadFitLedgerInputs() harmonizes each row's sppEquiv with LandR::sppHarmonize() (species without a name in sppEquivCol are dropped and a colour vector is made), and finds the climate variables of its parameters: the columns of params that are neither logistic parameters (logisticParamNames), youngAge, fuel classes nor non-forest groups, and are a climate variable of climateData.

Value

spreadFitLedgerInputs(): a list with one element per row, named by polygonID, each a list of missingLCCgroup and nonForestedLCCGroups (when the ledger has them), sppColorVect, sppEquiv and sppNameVector (harmonized), theseClimVars and theseClimVarsNoUnderscore.

spreadFitLedgerInputLists(): a named list of five lists, each with one element per ledger row (named by polygonID): sppEquivs, sppColorVects, sppNameVectors, nonForestedLCCGroupsList and missingLCCgroupList.


Compare a spread fit with the data it was fitted to

Description

A response curve of logit(p) against a covariate cannot show misfit: its points are the model's own predictions, so they sit on the fitted curve by construction. What can show misfit is the share of pixels that actually burned against the share that burned in the fit's own simulations, binned by each covariate.

Usage

spreadFitValidationData(
  par,
  landscape,
  annualDTx1000,
  nonAnnualDTx1000,
  formulaToFit,
  historicalFires,
  fireBufferedListDT,
  covMinMax = NULL,
  mutuallyExclusive = list(youngAge = c("class", "nf")),
  covCentre = NULL,
  Nreps = 10,
  lowerSpreadProb = spreadProbFloor,
  maxFireSpread = spreadProbCeiling,
  link = NULL,
  fitYearSpreadSD = NULL,
  fitFireSpreadSD = NULL,
  wholeLandscape = FALSE,
  climateRef = NULL,
  powerLawGamma = spreadPowerLawGamma,
  powerLawShape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu,
  seed = NULL,
  powerLawPc50 = NULL,
  ...
)

plotSpreadFitValidation(d, nBins = 10L, covariates = NULL, title = NULL)

plotSpreadFitResponse(d, covariates = NULL, bins = 40L, title = NULL)

Arguments

par

The fitted parameters, as given to .objfunSpreadFit() (without hillSlope1 and inflectionPoint1, which are fixed at 1; fireSpreadSD then yearSpreadSD last if fitted).

landscape

A SpatRaster with extent, resolution, and projection (crs) used for SpaDES.tools::spread2.

annualDTx1000

A list of data.table class objects. Each list element is data from a single calendar year, and whose name takes the form "yearxxxx", where xxxx is the four-digit year. The columns in the data.table must integers, that are ⁠1000x⁠ their actual values as this function will divide by 1000.

nonAnnualDTx1000

Like annualDTx1000, but with where each list element will be used for >1 year. The names of the list elements must be of the form "yearxxxx_yearyyyy_yearzzzz" where xxxx, yyyy, and zzzz represent the four-digit calendar years for which that list element should be used. The columns are variables that are used for more than 1 year.

formulaToFit

Formula, put provided as a character string, not class formula. (if it is provided as a class formula, then it invariably will have an enormous amount of data hidden in the formula environment; this is bad for DEoptim::DEoptim)

historicalFires

A named list of data.frames (one per year, names matching those of annualDTx1000), each with columns cells (pixel indices of ignitions) and size (fire size in pixels). The observed fire record against which the simulation is compared.

fireBufferedListDT

A named list of data.tables (one per year, names matching annualDTx1000), each with columns pixelID, buffer (1 if the pixel is inside a buffered fire footprint, 0 otherwise), and ids (a unique identifier per fire). Restricts the set of pixels used when fitting and scoring spread.

covMinMax

This is a 2 row by multiple column data.frame indicating the minimum and maximum values of the original covariate data values. These will be used to rescale the covariates internally so that they are all between 0 and 1. It is important to not simply rescale internally here because only 1 year is run at a time; all years must be rescaled for a given covariate by the same amount.

mutuallyExclusive

Named list of vectors describing groups of model terms that must not be active together (mutually exclusive in the formula). Default list("youngAge" = c("class", "nf")).

covCentre

Optional named list or vector of values subtracted from the rescaled covariates of the same name. NULL (default) does no centring. Must be the same at fit and predict. spreadCovCentre() gives the centres to use with an intercept.

Nreps

Simulations per fire; use the fit's Nreps.

lowerSpreadProb

Numeric. Lower bound for spreadProb; if a candidate spreadProb falls at or below this, the call exits early to avoid wasted simulation work. Default spreadProbFloor.

maxFireSpread

A value for spreadProb that is considered impossible to go above. Default spreadProbCeiling, also the upper bound of maxAsymptote. maxAsymptote is the spread-probability ceiling in a typical year. The year random effect (yearSpreadSD) is added on the logit of the final spread probability, after the link, so in a given year p can exceed maxAsymptote or fall below lowerSpreadProb; that is intended. There is no absolute cap, because spreadCpp does not need one; maxAsymptote is bounded because runaway fires are slow to simulate and wasted if the parameters are wrong.

link

Passed to logisticAll(): NULL for the form implied by the logistic parameters, or "logistic3pUpper" for the 3-parameter logistic with Stukel's upper tail, whose fourth logistic parameter is upperTail1, or "powerLaw", "powerLawSmooth" or "richards" for powerLawLink(), powerLawSmoothLink() or richardsLink(): maxAsymptote is then p_c, fitted, and the year effect (fitYearSpreadSD) is added to the linear predictor x, not to the logit of p, so a year cannot take p past p_c. Pass it explicitly when fitting: par may arrive unnamed.

fitYearSpreadSD

If TRUE, the last element of par is the sd of a per-year random effect on the logit of spread probability, a seasonal departure: in each replicate the year draws one eps ~ N(0, sd^2) and every pixel of that year spreads with plogis(qlogis(p) + eps), so all of the year's fires are bigger or smaller together. Without it the simulated fire sizes were too alike: medians too large and the largest fires too small at once (2026-09-23). sd = 0 is the model without it, exactly (no random numbers are drawn). NULL (default): TRUE when par is named and includes yearSpreadSD. DEoptim passes par unnamed, so runDEoptim() sets it explicitly.

fitFireSpreadSD

If TRUE, par has the sd of a per-fire random effect, before yearSpreadSD if that is fitted too, else last: in each replicate every fire draws its own eps ~ N(0, sd^2), added to the linear predictor of the cells it spreads to (SpaDES.tools::spreadCpp()'s linkOffset, one per fire, on top of the year's draw), so fires of one year can differ in how readily they spread. Only with wholeLandscape = TRUE (an error otherwise, when the sd is above 0). sd = 0 draws no random numbers, so the objective is exactly the one without it. NULL (default): TRUE when par is named and includes fireSpreadSD. DEoptim passes par unnamed, so runDEoptim() sets it explicitly.

wholeLandscape

FALSE (default), or TRUE: every fire spreads on all the pixels of annualDTx1000 (the whole landscape's tables) with no buffer edge, so no fire is cut and every term scores the size it burned unbounded. The linear predictor is computed once per year and the spread probability only for the cells a fire reaches (SpaDES.tools::spreadCpp(link = ), the doubles of powerLawLink(), powerLawSmoothLink() or richardsLink()), with no landscape-length vector per replicate, so a fit costs about what a buffered fit does. Needs link one of spreadLinearLinks; not with penaliseRunaways = TRUE, which stops fires at the buffer edge (both an error). FALSE changes nothing.

climateRef

NULL (default): the climate covariates are inside the logistic, under the maxAsymptote ceiling, as always. A named numeric or list (spreadClimateRef()): climate is taken outside the ceiling, p = plogis(qlogis(p0) + beta_clim * (climate - climateRef)) with p0 the logistic of the other covariates; see spreadProbFromCovs(), which computes both links. The year effect (fitYearSpreadSD) is added on the same logit, after climate. The gates (spreadProbGateTest()) and the saturation summary are then applied to p0, the spread probability at the reference climate, not to p. With a power-law link and powerLawPc50, climate is in the ceiling instead: it moves pc toward powerLawPc50, never past it (spreadLinkInputs()).

powerLawGamma

The "powerLaw" and "powerLawSmooth" links' gamma (powerLawLink()), fixed, not fitted; used only with those links.

powerLawShape

The "powerLaw" and "powerLawSmooth" links' curvature exponent shape (powerLawLink()), fixed, not fitted; used only with those links. Default 1.

lowerAsymptote

The lower asymptote L of the "powerLawSmooth" and "richards" links (powerLawSmoothLink(), richardsLink()), fixed, not fitted, ⁠spreadLowerAsymptoteMin <= L <= spreadProbFloor⁠ (checkLinkParams()); default spreadProbFloor. The spread-probability gates use it as their lower bound with those links (spreadLinkLower()).

richardsNu

The "richards" link's nu, fixed, not fitted; default spreadRichardsNu.

seed

If not NULL, the simulations run with this seed and the session's random number stream is restored afterwards.

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.

...

Further arguments to .objfunSpreadFit(), e.g. escapeSizeHa, jumpTries, jumpMeanDist: give it what the fit was given. The objective's gates on implausible landscapes are lifted (lanscape1stQuantileThresh = Inf) unless given here.

d

The output of spreadFitValidationData().

nBins

Number of quantile bins per covariate.

covariates

The covariates to plot; all of the formula's by default.

title

Plot title; a default is used when NULL.

bins

Number of hexagons (or squares, without hexbin) across each panel.

Details

  • spreadFitValidationData() runs the objective's simulations for the fitted parameters, recording which pixels burned (.objfunSpreadFit(returnBurned = TRUE)), and returns one row per spreadable pixel-year in the buffers of the fitted fires.

  • plotSpreadFitValidation() plots, per covariate, the observed and the simulated burned share by quantile bin of that covariate.

  • plotSpreadFitResponse() plots the fitted response curves (the model, not the data).

Both plot functions take the data as their first argument and return a ggplot, so they can be given to SpaDES.core::Plots() as fn.

Value

spreadFitValidationData(): a data.table, one row per spreadable pixel-year inside the buffers of the fires the objective fits (minFireSize, escapeSizeHa): year (the name of the fire year), pixelID, observed (1 if the pixel is inside an observed fire, else 0), simulated (the share of the Nreps simulations in which it burned), p (its fitted spread 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 annual (climate) ones, and yearsNotSimulated – years the objective declined to simulate, which have no rows.

plotSpreadFitValidation(): a ggplot, one panel per covariate (NULL for a model with none, ~ 1). Pixel-years are binned by quantiles of the covariate: all of them for climate covariates, only those where it is present (above its covMinMax minimum, else above 0) for the others, and one bin per value for covariates with two values or fewer. Each bin shows the observed burned share and the mean simulated burned share, at the bin's mean covariate value, with its number of pixel-years along the bottom.

plotSpreadFitResponse(): a ggplot, one panel per covariate with more than two values (NULL when there is none). The line is logit(p) the fitted parameters give a "pure stand": that covariate alone, every other covariate absent (0 after rescaling: other fuels, youngAge, non-forest), and climate at its median. Behind it, the pixel-years' own predicted logit(p) (only where the covariate is present, except for climate), up to its 99.5th percentile. Those follow the curve by construction: the figure shows the model's response, not how well it fits.


Memory (GB) assumed per DEoptim worker before a fit has a memory record

Description

runDEoptim() sets options(clusters.workerMemoryGB) to this, unless the user has set it, so clusters (>= 0.0.75) caps workers per host by free memory from a fit's first cluster build. At 9 GB a GPSC node of 450 GB holds 40 workers (at 14 GB it held 32). Measured peak resident memory per spread-fit worker: median 4.5 GB, 90th percentile about 6.5 GB. Once a fit has run its first chunk, the fit's own record replaces this number. A regression of worker memory on fire and ELF pixel counts was considered and put aside.

Usage

spreadFitWorkerMemoryGB

Does the spread model have a covariate?

Description

FALSE for the null model, the formula ~ 1: an intercept and nothing else, so every pixel has the same spreadProb.

Usage

spreadHasCovariates(colsToUse)

Arguments

colsToUse

character; the design columns, from spreadDesignCols().

Value

logical(1).


Indicator covariates of the spread model

Description

The covariates that are 0 or 1: youngAge, the non-forest land-cover groups (⁠nfLCC_*⁠) and the species-mode treedWetland indicator (not the biomass treedWetland_agb). Their range is always c(0, 1) (spreadIndicatorRanges()), not the range of the data: in an ELF where one is constant the data's range is zero wide and rescaling divides by zero.

Usage

spreadIndicatorCols(covNames)

spreadFuelCols(covNames)

spreadIndicatorRanges(covNames)

Arguments

covNames

character vector of covariate column names.

Value

spreadIndicatorCols(): the names among covNames that are indicators. spreadIndicatorRanges(): a named list, c(0, 1) for each of them.

spreadFuelCols(): the names among covNames that are not indicators, i.e. fuel biomass.


The linear predictor and the link parameters of a spread link of spreadLinearLinks

Description

What spreadProbFromCovs() turns into p with linearLinkProb(), and what the objective gives SpaDES.tools::spreadCpp() (x as the linear predictor, pars as linkPars). Without climateRef, x = mat %*% covPars and pars is the vector linearLinkPars() with pc = logisticPars[1].

Usage

spreadLinkInputs(
  mat,
  logisticPars,
  covPars,
  lowerSpreadProb,
  link,
  climateRef = NULL,
  powerLawPc50 = NULL,
  powerLawGamma = spreadPowerLawGamma,
  powerLawShape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu,
  climateAtRef = FALSE
)

Arguments

mat

Numeric matrix, one row per pixel, one column per design column (with colnames when climateRef is given), as spreadProbCovsOfYear() gives them: as.matrix(covs[, ..colsToUse]).

logisticPars, covPars, lowerSpreadProb

As for spreadProbFromCovs().

link

One of spreadLinearLinks.

climateRef

NULL, or a named numeric or list: the reference value of each climate column, on the scale of mat (spreadClimateRef()). Every name must be a column of mat.

powerLawPc50

The landscape's runaway threshold p50 (calibratePowerLaw()); needed, finite, with climateRef.

powerLawGamma

The "powerLaw" and "powerLawSmooth" links' gamma; used only with those links.

powerLawShape

The "powerLaw" and "powerLawSmooth" links' curvature exponent shape; used only with those links.

lowerAsymptote, richardsNu

The lower asymptote of "powerLawSmooth" and "richards", and the nu of "richards" (logisticAll()); used only with those links.

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.

Details

With climateRef (climate in the ceiling; spreadClimate = "ceiling" in fireSense_spreadFit) and a power-law link (spreadPowerLawLinks) climate moves the percolation threshold pc toward the landscape's own runaway threshold 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.

Value

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.


The spread-probability ceiling and floor

Description

One value each, used wherever the spread model needs them. spreadProbCeiling is the upper bound fireSense_spreadFit gives maxAsymptote, and the default maxFireSpread of the objective, the gates and the validation: a fitted maxAsymptote above it draws a warning. How a year's random effect can take a pixel past it is described at maxFireSpread in .objfunSpreadFit(). spreadProbFloor is the default lowerSpreadProb in the objective, the gates, the validation and fireSense_spreadPredict. It is the lower asymptote of the logistic links. With "powerLaw" it is p at x = 0 and there is no lower asymptote: p falls below it for x < 0 and is set to 0 (powerLawLink()). With "powerLawSmooth" it is p at x = 0 and the default lowerAsymptote, the lower asymptote, which may be anywhere from spreadLowerAsymptoteMin to it (powerLawSmoothLink()). spreadPowerLawPcBounds are the bounds fireSense_spreadFit gives p_c, the maxAsymptote slot, with the "powerLaw" link (powerLawLink()): p_c must stay above the floor (0.01 above it), and its upper bound is 0.35. These are the outer limits: fireSense_spreadFit bounds p_c above by the ELF's own calibrated threshold (powerLawPcBounds()). Runaway-curve simulations on real ELF landscapes put the threshold at 0.258-0.288 (0.248 on a uniform landscape), higher where less of the landscape can burn, so spreadProbCeiling (0.276) would bind.

Usage

spreadProbCeiling

spreadProbFloor

spreadPowerLawPcBounds

Format

Numeric scalars.


The spread probability of each pixel from its covariates: the one place the spread link is computed

Description

Every spread probability the model gives – in the objective (.objfunSpreadFit()), its gates (spreadProbGates()), the validation (spreadFitValidationData(), plotSpreadFitResponse()) and the prediction (fireSense_spreadPredict) – comes from this function, so the fit and the prediction use one formula.

Usage

spreadProbFromCovs(
  mat,
  logisticPars,
  covPars,
  lowerSpreadProb,
  link = NULL,
  climateRef = NULL,
  climateAtRef = FALSE,
  powerLawGamma = spreadPowerLawGamma,
  powerLawShape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu,
  powerLawPc50 = NULL
)

Arguments

mat

Numeric matrix, one row per pixel, one column per design column (with colnames when climateRef is given), as spreadProbCovsOfYear() gives them: as.matrix(covs[, ..colsToUse]).

logisticPars, covPars, lowerSpreadProb, link

As for logisticAll(); covPars in the order of the columns of mat.

climateRef

NULL, or a named numeric or list: the reference value of each climate column, on the scale of mat (spreadClimateRef()). Every name must be a column of mat.

climateAtRef

Logical. With climateRef, TRUE returns p0, the spread probability with climate 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.

powerLawGamma

The "powerLaw" and "powerLawSmooth" links' gamma; used only with those links.

powerLawShape

The "powerLaw" and "powerLawSmooth" links' curvature exponent shape; used only with those links.

lowerAsymptote, richardsNu

The lower asymptote of "powerLawSmooth" and "richards", and the nu of "richards" (logisticAll()); used only with those links.

powerLawPc50

The landscape's runaway threshold (calibratePowerLaw()); with climateRef and a power-law link it puts climate in the ceiling (spreadLinkInputs()). Needed then, ignored otherwise.

Details

Links, chosen by link and climateRef:

  • climateRef = NULL (the default; spreadLink = "ceiling" in fireSense_spreadFit): the logistic of the whole linear predictor, p = f + (maxAsymptote - f) * plogis(x) with x = mat %*% covPars (logisticAll(); f is lowerSpreadProb). Climate is one of the covariates in x, so it acts under the maxAsymptote ceiling: where fuel alone puts a pixel near the ceiling a dry year adds almost nothing (in the 2026-10 hindcasts of three ELFs, 59-77% of pixels sat within 0.01 of the ceiling every year, and spread barely changed between years).

  • climateRef a named numeric (spreadLink = "climateOutside"): the climate covariates (its names, columns of mat) are taken out of the ceiling. p0 = f + (maxAsymptote - f) * plogis(x_fuel), with x_fuel the linear predictor of every other column (intercept, fuels, youngAge, non-forest, ...), is the spread probability at the reference climate; then p = plogis(qlogis(p0) + sum(beta_clim * (climate - climateRef))), uncapped. The year effect eps_Y (yearSpreadSD in the objective, fireSense_SpreadSD in fireSense_burn) is added on the same logit afterwards, so climate and the year effect act together after the fuel ceiling. At climate = climateRef the two links give the same p for the same p0. The sign constraint on the climate coefficient (⁠>= 0⁠, from fireSense_spreadFit's bounds) is unchanged.

  • link = "powerLaw" (spreadLink = "powerLaw"): p = pc - (pc - f) * exp(-sign(x) * abs(x / powerLawGamma)^powerLawShape), with pc (logisticPars[1]) fitted (powerLawLink()). The year effect eps_Y is added to x, not to the logit of p. With climateRef and powerLawPc50, climate moves pc instead (spreadLinkInputs()); without powerLawPc50 that combination stops.

  • link = "powerLawSmooth" (spreadLink = "powerLawSmooth"): the same for x >= 0; for x < 0, p falls from f to the lower asymptote lowerAsymptote, never below it (powerLawSmoothLink()). With climateRef as for "powerLaw".

  • link = "richards" (spreadLink = "richards"): p = L + (pc - L) / (1 + nu * exp(-B * x))^(1 / nu), with L the lowerAsymptote, nu the richardsNu and B fixed (richardsLink()). It does not use powerLawGamma. Not combined with climateRef.

Value

A one-column numeric matrix, one value per row of mat (as logisticAll()).


Convert covariates from their x1000 integer to usable by spread

Description

Convert covariates from their x1000 integer to usable by spread

Usage

spreadProbFromIntegerCovs(
  shortAnnDTx1000 = NULL,
  annDTx1000,
  nonAnnualDTx1000,
  indexNonAnnual,
  yr,
  covMinMax = NULL,
  mutuallyExclusive,
  colsToUse,
  doAssertions,
  logisticPars,
  covPars,
  maxFireSpread,
  lowerSpreadProb,
  covCentre = NULL
)

Arguments

shortAnnDTx1000

Optional if annDTx1000 and nonAnnualDTx1000 are supplied. Otherwise it must be a data.frame/data.table that has all covariates (>= 1 forests, >=0 non-forests, climate, youngAge), whose values are 1000x their original values so they can be stored as integers.

annDTx1000

TODO: use description of annualDTx1000 parameter in .objfunSpreadFit. If shortAnnDTx1000 is not supplied, this must be supplied. It must be a data.frame/data.table that has all the annual covariates (e.g., ⁠>=1⁠ forest biomass, ⁠>=0⁠ non forest binary), whose values are 1000x their original values so they can be stored as integers.

nonAnnualDTx1000

If shortAnnDTx1000 is not supplied, this must be supplied. A named list of data.frames/data.tables that has all the non-annual covariates (e.g., ⁠>=1⁠ forest biomass, ⁠>=0⁠ non forest binary), whose values are 1000x their original values so they can be stored as integers, named by their data year. The table used for yr is that of the latest data year strictly before yr (dataYearBefore()); the function stops if a pixel of annDTx1000 is not in it.

indexNonAnnual

Unused, kept for callers: the table of yr is chosen from the names of nonAnnualDTx1000, which must be the data years (see dataYearBefore()).

yr

A single character or numeric/integer representing the full year (e.g., 2020) to but used. This year will be extracted from both the annDTx1000 and nonAnnualDTx1000 if they are supplied

covMinMax

A data.table, one column for each column in shortAnnDTx1000 (or the ann and nonAnnual alternatives), where the two rows represent the minimum and maximum values in the original fitting dataset. This MUST be supplied if this is prediction scenario so that the new covariates values are not scaled to themselves. I.e., they must be rescaled compared to the fitted data or else their rescaled values will be incorrect.

mutuallyExclusive

If there are any covariates, e.g,. youngAge, that should be considered mutually exclusive, then this can be done here (i.e., "if youngAge is non-zero, should vegPC2 be set to zero"). A named list, where the name of the list element must be a single covariate column name in either annualDTx1000 or nonAnnualDTx1000. The list content should be a "grep" pattern with which to match column names, e.g., "vegPC". The values of all column names that match the grep value will be set to 0, whenever the name of that list element is non-zero. Default is list("youngAge" = list("vegPC")), meaning that all columns with vegPC in their name will be set to zero wherever youngAge is non-zero.

colsToUse

Optional. If this is supplied, it must be a character vector indicating the column names to use in shortAnnDTx1000, i.e., it must include everything, annual or nonAnnual, that will be used. It may start with spreadInterceptTxt (see spreadDesignCols()): that column is made here, as 1s, after rescaling and centring. An interaction ("a:b") is made here too, as the product of a and b after rescaling and the mutually exclusive step and before centring, so fitting and prediction form it identically.

doAssertions

Logical. If TRUE, the default, the function will test a few minor things for consistency. This should be set to FALSE for operational situations, as the assertions take some small amount of time.

logisticPars

Numeric vector of logistic parameters. Unless link names the form, its length selects the variant logisticAll dispatches to – except that a vector with an element named upperTail1 is always logistic3pUpper, whatever its length.

covPars

Numeric vector of covariate coefficients (same length as ncol(mat)); mat %*% covPars forms the linear predictor.

maxFireSpread

A value for spreadProb that is considered impossible to go above. Default spreadProbCeiling, also the upper bound of maxAsymptote. maxAsymptote is the spread-probability ceiling in a typical year. The year random effect (yearSpreadSD) is added on the logit of the final spread probability, after the link, so in a given year p can exceed maxAsymptote or fall below lowerSpreadProb; that is intended. There is no absolute cap, because spreadCpp does not need one; maxAsymptote is bounded because runaway fires are slow to simulate and wasted if the parameters are wrong.

lowerSpreadProb

Numeric. Lower bound for spreadProb; if a candidate spreadProb falls at or below this, the call exits early to avoid wasted simulation work. Default spreadProbFloor.

covCentre

Optional named list or vector: covCentre[[col]] is subtracted from column col after rescaling, mutual exclusivity and the range assertion. NULL (default) does no centring. Supply the fitted values at prediction.

Value

This returns the full data.table to be used for fireSense, on the original numeric i.e., real scale, with the x1000 reversed.


Would parameter sets pass the objective's spreadProb gates in its first block of years?

Description

Computes each parameter set's spreadProb on the covariates of the first block (the two years with the most burned area) exactly as .objfunSpreadFit() does, and applies spreadProbGateTest(), which the objective itself calls, without simulating any fire. A parameter set that fails is one the objective would bail on in the first block. It is cheap enough to screen thousands of draws.

Usage

spreadProbGates(
  par,
  annualDTx1000,
  nonAnnualDTx1000,
  historicalFires,
  formulaToFit,
  covMinMax = NULL,
  mutuallyExclusive = list(youngAge = c("class", "nf")),
  covCentre = NULL,
  link = NULL,
  maxFireSpread = spreadProbCeiling,
  lowerSpreadProb = spreadProbFloor,
  lanscape1stQuantileThresh = 0.265,
  minFireSize = 2,
  escapeSizeHa = NULL,
  landscape = NULL,
  years = NULL,
  doAssertions = FALSE,
  climateRef = NULL,
  powerLawGamma = spreadPowerLawGamma,
  powerLawShape = spreadPowerLawShape,
  lowerAsymptote = spreadProbFloor,
  richardsNu = spreadRichardsNu,
  powerLawPc50 = NULL
)

Arguments

par

a named numeric vector as .objfunSpreadFit() takes (logistic parameters, then the covariate coefficients, then yearSpreadSD if fitted), or a list of them.

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()).

formulaToFit

character; the spread formula, as in the objective.

years

character; the years to test. Default: the objective's first block.

doAssertions

logical; as in the objective.

powerLawGamma, powerLawShape, lowerAsymptote, richardsNu, powerLawPc50

As in .objfunSpreadFit().

Value

for one par, a list of logicals pass (every tested year passes), burny and notSpread (any tested year fails that check), medianOK (every year's median is in range) and the tested years; for a list of parameter sets, a data.frame with one row of the same per set.


The objective's spread-probability gates, on one year's spreadProb

Description

.objfunSpreadFit() refuses to simulate a year (it scores the minLik floor, and the parameter set is "bailed") unless its spreadProb passes these checks. The objective calls this function, so the checks cannot differ from spreadProbGates().

Usage

spreadProbGateTest(
  spreadProb,
  ceiling,
  lowerSpreadProb,
  maxFireSpread,
  lanscape1stQuantileThresh,
  spreadOut = TRUE
)

Arguments

spreadProb

numeric; the spreadProb of each pixel of the year.

ceiling

numeric; the logistic's asymptote (its first parameter). Pixels at or above 99% of it (or within 2.5% of lowerSpreadProb) are "edge" values and are left out of the spread checks.

lowerSpreadProb, maxFireSpread

numeric; the median must be within them.

lanscape1stQuantileThresh

numeric; the first quartile of the non-edge values must be below this.

spreadOut

logical; FALSE skips the "spread out enough" check. A model with no covariate (~ 1, see spreadHasCovariates()) gives every pixel the same spreadProb, which that check refuses.

Value

a list: pass; burny (first quartile too high, "Too burny a landscape"); notSpread ((q90 - q10) / median <= 0.025, "Not spread out enough"); medianOK; and the nonEdgeValues and their summary that the objective logs.


The random-effect arguments of the spread objective, from a fit's bounds

Description

A spread fit fits a random effect when its bounds name it: fireSpreadSD and yearSpreadSD (spreadRandomEffectTxt), which must be the last of lower, in that order. runDEoptim() passes the result to .objfunSpreadFit(); anything else that calls the objective of a fit (an emulator) should too.

Usage

spreadRandomEffectArgs(lower, wholeLandscape = FALSE)

Arguments

lower

Named lower bounds of the fit, as runDEoptim(lower = ).

wholeLandscape

As in runDEoptim(): fireSpreadSD needs TRUE (an error otherwise).

Value

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.


Prepare covariate table with ignition year, fuel class, climate value, and land cover

Description

Prepare covariate table with ignition year, fuel class, climate value, and land cover

Usage

stackAndExtract(years, fuel, LCC, climate, fires = NULL)

Arguments

years

character vector of fire years with FS notation e.g. "year2002"

fuel

raster brick of aggregated fuel classes, or a list of them named by years (one per year, as prepare_FuelCovsCoarseByYear() makes)

LCC

raster brick of aggregated LCC classes, or a list named by years

climate

list of raster layers named by climate variable with raster layer names matching years

fires

list of spatial points representing annual ignitions

Value

a data.frame with cell numbers, ignitions, and covariates for each year


Stop unless non-forest can be youngAge

Description

youngAge is resolved for each fire year from time since disturbance (youngAgeAtYear()), which covers forest and non-forest pixels alike, so the mode where non-forest is never young is not available, in the spread fit, the ignition fit and the hindcasts that follow them.

Usage

stopIfNonForestCannotBeYoung(nonForestCanBeYoungAge)

Arguments

nonForestCanBeYoungAge

the nonForestCanBeYoungAge parameter.

Value

NULL, invisibly.


Convert numeric values to integers x 1000

Description

This simply converts to integers times 1000 so that the values can be saved more quickly to disk, for example.

Usage

toX1000(lst, omitCols = "pixelID")

Arguments

lst

a data.frame of (at least some) numeric columns

omitCols

character A vector of column names to not convert

Value

The same data.frame, but with columns converted to integer and times 1000


Time since disturbance of every pixel, as the table youngAgeAtYear() reads

Description

Time since disturbance of every pixel, as the table youngAgeAtYear() reads

Usage

tsdTable(tsd)

Arguments

tsd

SpatRaster of time since disturbance at the data year (see makeTSD()).

Value

data.table with pixelID (the cell numbers) and tsd.


Link parameters of cells that cannot burn

Description

n rows of valid parameters for link (pc = floor = lower = 0, so p = 0), named as spreadLinkParNames says: what SpaDES.tools::spreadCpp(linkPars = ) is given for a cell with no linear predictor, as it accepts no NA row.

Usage

unburnableLinkPars(link, n = 1L)

Arguments

link

One of spreadLinearLinks.

n

The number of rows.

Value

A numeric matrix with n rows and the columns of spreadLinkParNames for link.


Update name of layers in a climate raster stack

Description

Update name of layers in a climate raster stack

Usage

updateStackYearNames(annualDataStack, desiredYears)

Arguments

annualDataStack

RasterStack

desiredYears

character


Make histograms of DEoptim object pars

Description

Make histograms of DEoptim object pars

Usage

visualizeDE(DE, cachePath, titles, lower, upper)

Arguments

DE

An object from a DEoptim::DEoptim call

cachePath

A cacheRepo to pass to showCache and loadFromCache if DE is missing.

titles

titles of plots

lower

lower limit on x axis

upper

upper limit on x axis


The features of an ignition or escape fit, and whether a stored fit can predict

Description

fireSense_ignitionFit gives xgboost every covariate column except pixelID, year, coreFractionTxt, the ⁠yearChar*⁠ columns and the responses (ignitionsTxt, escapesTxt), in alphabetical order (xgbFeatureNames()). A fit stored in the ledger records the features it was trained on (its fold boosters' variable.names()); if the covariates have changed since (e.g. non-forest land-cover groups merged into one), predict() fails on the missing columns. fireSense_ignitionFit checks this before reusing a stored fit, against the covariates it would fit with; fireSense_ignitionPredict checks it before predicting, against the covariates it predicts with, so the check holds when no fit data were prepared.

Usage

xgbFeatureNames(cols)

foreignObjectives(fitted)

storedFitProblem(fitted, covariates)

Arguments

cols

Character vector of the column names of the covariates.

fitted

A stored fireSense_IgnitionFitted or fireSense_EscapeFitted: a list with modelList$model, or NULL.

covariates

The covariates the stored fit would predict (or be refitted) with: a data.frame, or anything with colnames().

Value

xgbFeatureNames(): character vector.

foreignObjectives(): the objectives of the fold boosters that differ from ignitionObjectiveTxt (empty when all match); "unknown" stands for a booster whose objective cannot be read (xgbObjective()).

storedFitProblem(): NULL when fitted has fold boosters, all fitted with ignitionObjectiveTxt, whose features are all among xgbFeatureNames(colnames(covariates)); otherwise one string saying why not (no model; the objectives; the missing features, and the covariates the model does not use), for the caller's message.


The objective an xgboost model was fitted with

Description

Reads xgboost::xgb.config(model)$learner$objective$name, then attr(model, "params")$objective. The second is the only source for models that carry their parameters as an attribute; the first is the only one for xgboost (>= 3) boosters, which have no ⁠$params⁠ and, once read back from a file, are external pointers. Every fireSense module that needs the objective (to check a stored fit against ignitionObjectiveTxt, or to tell fireSense_burn how to draw counts) uses this function.

Usage

xgbObjective(model)

Arguments

model

An xgb.Booster, or a plain (unclassed) list of them, e.g. the folds of a fit.

Value

For one booster a single string; for a list a character vector with one element per booster, keeping the list's names. NA_character_ stands for a model whose objective cannot be read.

Examples

if (requireNamespace("xgboost", quietly = TRUE)) {
  x <- matrix(rnorm(100), ncol = 2)
  b <- xgboost::xgboost(x, rpois(50, 1), objective = "count:poisson", nrounds = 2, nthreads = 1)
  xgbObjective(b)
  xgbObjective(list(Fold1 = b, Fold2 = b))
}

The year effect on an expected count: a mean-one lognormal multiplier

Description

FireSense gives every simulated year one draw z ~ N(0, 1), shared by spread, ignitions and escapes (drawn in fireSense_burn): a bad spread year is also a bad ignition and escape year. Spread adds z * yearSpreadSD to its linear predictor (see yearSpreadSD in .objfunSpreadFit()). An expected count (ignitions or escapes per pixel) is multiplied by u = exp(sd * z - sd^2 / 2), so E(u) = 1 over z: the long-run mean is kept and the result is a valid Poisson mean (⁠>= 0⁠). yearEffectSD() is the matching estimator of sd.

yearEffectSD() estimates the sd of the year effect from yearly totals, by the method of moments. Model: O_j ~ Poisson(mu_j * u_j) with u_j = yearEffectMultiplier(sd, z_j), so Var(u_j) = exp(sd^2) - 1 and E((O_j - mu_j)^2 - O_j) = mu_j^2 * (exp(sd^2) - 1): subtracting O_j removes the Poisson sampling variance. The estimate is exp(sd^2) - 1 = sum((O_j - mu_j)^2 - O_j) / sum(mu_j^2), floored at 0 (less than Poisson spread means no year effect). mu_j is predicted_j * sum(O) / sum(predicted), so a bias in the overall level is not counted as year-to-year variation. It works on counts, not on log(O_j / mu_j), so years with no event (common for escapes) need no special treatment.

Usage

yearEffectMultiplier(sd, z)

yearEffectSD(observed, predicted)

Arguments

sd

Numeric: the sd of the year effect, one number or one per element of z; NA is 0.

z

Numeric: the year's draw(s) from N(0, 1).

observed, predicted

Numeric vectors, one element per year: the observed and the predicted totals. Years with an NA in either are dropped.

Value

yearEffectMultiplier(): numeric, exp(sd * z - sd^2 / 2), recycled to the longer of sd and z; exactly 1 where sd is 0.

yearEffectSD(): sd, one number ⁠>= 0⁠; 0 with fewer than 2 years, or when nothing was observed or predicted.

Examples

yearEffectMultiplier(0.5, c(-2, 0, 2))
mean(yearEffectMultiplier(0.5, rnorm(1e5)))   # about 1
set.seed(1)
mu <- rep(c(30, 80, 150, 300), 10)
obs <- rpois(length(mu), mu * yearEffectMultiplier(0.5, rnorm(length(mu))))
yearEffectSD(obs, mu)                          # about 0.5
yearEffectSD(rpois(40, 100), rep(100, 40))     # about 0: Poisson noise only

youngAge of pixels at one fire year

Description

Time since disturbance at year is the smaller of the data year's time since disturbance aged to year (tsd + (year - dataYear)) and the years since the last fire before year (year - fireYear), taken over all fires in firePixelsByYear, not only the fires being fitted. A pixel is young when that is at or below cutoffForYoungAge. A pixel with NA time since disturbance (non-flammable or unknown) is never young, whether or not a fire covers it. A fire in year itself does not count: fire years are compared with the state before they burn.

Usage

youngAgeAtYear(
  tsd,
  dataYear,
  year,
  firePixelsByYear = list(),
  cutoffForYoungAge = fireSenseYoungAgeCutoff,
  pixelID = tsd$pixelID
)

Arguments

tsd

data.table with columns pixelID and tsd, the time since disturbance at dataYear (for example from makeTSD()).

dataYear

the year tsd describes.

year

the fire year.

firePixelsByYear

list named by fire year ("2001", or "year2001") of the pixelIDs that burned that year (see firePixelsByYear()). Years with no fire may be absent.

cutoffForYoungAge

Numeric. Default is 15. This is the age below which the pixel is considered "young" –> youngAge column will be 1 if age <= 15

pixelID

integer, the pixels to return, in this order. Default: all rows of tsd.

Details

It works on pixel IDs, so the same call serves the buffered pixels of a spread fit and every pixel of the landscape (ignition, validation). Only fires in (year - cutoffForYoungAge):(year - 1) can make a pixel young, so only those are read.

Value

integer vector, 1 for young and 0 otherwise, one per pixelID.


Columns youngAge is mutually exclusive with

Description

youngAge is mutually exclusive with every other non-climate spread covariate: wherever it is non-zero, fuel biomass, non-forest land cover (always named ⁠nfLCC_*⁠, see fuelClassPrep()) and treedWetland are all zero. fireSense_spreadFit derives this from the covariates it holds apart from climate (its non-annual covariate table); fireSense_spreadPredict has no such table, so it identifies fuel columns itself (their covMinMax range) and calls this for the rest, so both modules end up applying the identical rule.

Usage

youngAgeExclusiveCols(covNames, fuelCols = character())

Arguments

covNames

character vector of all covariate column names present (excluding pixelID).

fuelCols

character vector, the fuel biomass column names among covNames.

Value

a named list, ⁠list(youngAge = <matched column names>)⁠, suitable as makeMutuallyExclusive()'s mutuallyExclusiveCols argument.