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
Built: 2026-06-05 07:22:59 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 when no piecewise model is used

Description

Internal callback passed to the optimizer (e.g. stats::nlminb()) when the ignition formula contains no pw() terms. Computes the linear predictor mm %*% params + offset, applies linkinv, and returns the negative log-likelihood evaluated in mod_env. A large sentinel (1e20) is returned whenever the link inverse produces invalid values (non-positive, NA, infinite, or empty), preventing the optimizer from wandering into infeasible regions.

Usage

.objFunIgnition(params, linkinv, nll, sm, nx, mm, mod_env, offset)

Arguments

params

Numeric vector of parameter values supplied by the optimizer.

linkinv

Function. Inverse link function (e.g. stats::plogis() for a logit link).

nll

Quoted/unevaluated R expression that computes the negative log-likelihood when evaluated in mod_env.

sm

Square numeric matrix. Parameter scaling matrix applied as params %*% sm before the linear predictor is formed.

nx

Integer. Number of covariate parameters (i.e. number of columns in mm).

mm

Numeric model matrix containing covariate values.

mod_env

An environment (or data-frame coerced via base::list2env()) containing the variables referenced by nll.

offset

Numeric vector the same length as nrow(mm). Model offset added to the linear predictor.

Value

Numeric scalar: the negative log-likelihood, or 1e20 if the inverse-link produces non-finite or non-positive values.


Function to pass to the optimizer - Piece-wise version

Description

Internal callback for the optimizer when the ignition formula contains pw() terms. Differs from .objFunIgnition in that the model matrix is rebuilt at every call (via stats::model.matrix()) after running updateKnotExpr, which updates the knot values in mod_env. This lets the optimizer jointly fit covariate coefficients and knot positions.

Usage

.objFunIgnitionPW(
  params,
  formula,
  linkinv,
  nll,
  sm,
  updateKnotExpr,
  nx,
  mod_env,
  offset
)

Arguments

params

Numeric vector of parameter values supplied by the optimizer. Includes both covariate coefficients and knot values.

formula

Model formula (or string coercible by stats::as.formula()) containing one or more pw() calls.

linkinv

Function. Inverse link function.

nll

Quoted R expression evaluating to the negative log-likelihood when evaluated in mod_env.

sm

Square numeric matrix. Parameter scaling matrix.

updateKnotExpr

Quoted R expression that copies the latest knot values from params into the variables in mod_env referenced by formula.

nx

Integer. Number of covariate parameters.

mod_env

An environment (or data-frame) containing the covariates and the variables updated by updateKnotExpr.

offset

Numeric vector. Model offset added to the linear predictor.

Value

Numeric scalar: the negative log-likelihood, or 1e20 if the inverse-link produces negative, NA, or infinite values.


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 = 0.28,
  lowerSpreadProb = 0.13,
  minFireSize = 2,
  tests = "snll_fs",
  Nreps = 10,
  mutuallyExclusive = list(youngAge = c("class", "nf")),
  doAssertions = TRUE,
  plot.it = FALSE,
  objFunCoresInternal = 1,
  lanscape1stQuantileThresh = 0.265,
  thresh = 550,
  weighted = TRUE,
  verbose = 2,
  ...
)

Arguments

par

parameters

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 0.28, which is overly generous unless there are many non-flammable pixels (e.g., lakes).

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 0.13.

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.

tests

One or more of "mad", "adTest", "SNLL", or "snll_fs". Default: "snll_fs".

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.

thresh

Threshold multiplier used in SNLL fire size ("snll_fs") test. Default 550. Lowering the threshold value will be more restrictive, but being too restrictive will result in DEoptim::DEoptim rejecting more tests and using the "fail value" of 10000. Too high a threshold, and more years will be run and it will take longer to find values.

weighted

Logical. Should empirical likelihood be weighted by log of the actual fire size? This will give large fires more influence on the SNLL.

verbose

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

...

This is not used here, but allows for extraneous arguments to not break this function.

Value

Attempting a weighted likelihood, https://stats.stackexchange.com/questions/267464/algorithms-for-weighted-maximum-likelihood-parameter-estimation. With log(fireSize) * likelihood for each fire.


Abbreviate species names for fuel classes

Description

Abbreviate species names for fuel classes

Usage

abbreviateSpNames(df)

Arguments

df

data.table

Value

data.table


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()

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
)

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

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;


Buffer ignition points to create non-ignitions for model

Description

Buffer ignition points to create non-ignitions for model

Usage

bufferIgnitionPoints(ignitionPoints, rtm, bufferSize)

Arguments

ignitionPoints

sf points with year of ignition

rtm

a template raster

bufferSize

the size of the buffers

Value

a list of data.tables containing indices inside buffered area of each year's ignitions


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


Generate, Summarize, Predict Burn Classes from Covariates

Description

Generate, Summarize, Predict Burn Classes from Covariates

Usage

burnClassGenerator(df, numClasses = 4:9, AUC = TRUE, plotAUC = FALSE)

burnClassSummary(mod)

burnClassPredict(mod, df)

burnProbFromClass(mod, df)

Arguments

df

A data.frame (or data.table), with covariates, including "burned" (a binary 0, 1; not burned = 0, burned = 1), e.g., timeSinceFire, biomassJackPine, etc. that will be used to find fuel classes. This set of covariates must be available both during fitting and for prediction. These must be quantitative.

numClasses

A vector indicating how many classes should be attempted. The function will return the number of classes that best classify the data into homogeneous groups.

AUC

Logical. Should the Area Under the receiver operating Curve be returned?

plotAUC

Logical. Should the plot of the AUC be made.

mod

A model of class Mclust, e.g,. coming from Mclust or burnClassGenerator

Details

This was inspired by reading https://www.datanovia.com/en/blog/types-of-clustering-methods-overview-and-quick-start-r-code/ and https://www.datanovia.com/en/lessons/model-based-clustering-essentials/, based on Scrucca et al. (2016).

Value

A list with 2 elements, first the model, which comes from mclust::Mclust, and second the Area Under the Curve or AUC as an indicator of the overall goodness of fit.

The algorithm

The basic solution is to take all covariates, including the binary "not burned", "burned" (coded as 0 and 1, respectively), and do model-based clustering with the mclust R package. We can choose a fixed number of burn classes, or a finite range (see numClasses argument. This will make numClasses "homogeneous" groups, including whether they burned or not. From this, we can identify groups by looking at the mean values of "burned" to see what their burn tendency is as a "homogeneous" group.

Categorical data

For now, it is recommended to convert categorical data to dummy variables, 0 and 1. E.g., For land cover, wetland class can be converted to a column "wetland" with 1 for data points that are wetlands and 0 for non-wetland.

How much data to include

This has not been tested yet; however, I believe that having a relatively similar number of "burned" and "unburned" pixels (within ⁠3x⁠ either way), is probably a good idea. In other words, if there are 100,000 burned data points, there should be between 30,000 and 300,000 unburned data points. If there are already buffers around the burned polygons that include unburned pixels, then these buffers can be used as part of the unburned content.

Author(s)

Eliot McIntire

References

Scrucca L., Fop M., Murphy T. B. and Raftery A. E. (2016) mclust 5: clustering, classification and density estimation using Gaussian finite mixture models, The R Journal, 8/1, pp. 205-233. https://journal.r-project.org/archive/2016/RJ-2016-021/RJ-2016-021.pdf

Examples

## Not run: 
#################################
# Use own data; here is a generated set for reprex
withr::local_package("data.table")

N <- 1e5
DT <- list()
for (i in c("train", "test")) {
  DT[[i]] <- data.table(burned = sample(c(0, 0, 0, 1), replace = TRUE, size = N))
  set(DT[[i]], NULL, "jp", rlnorm(N, mean = 4 + 0.5 * DT[[i]]$burned, sd = 0.25))
  set(DT[[i]], NULL, "bs", rlnorm(N, mean = 4 + 0.3 * DT[[i]]$burned, sd = 0.25))
  set(DT[[i]], NULL, "ws", rlnorm(N, mean = 4 + 0.2 * DT[[i]]$burned, sd = 0.25))
  set(DT[[i]], NULL, "age", rlnorm(N, mean = 4 - 0.2 * DT[[i]]$burned, sd = 0.25))
  DT[[i]][, c("jp", "bs", "ws", "age") := lapply(.SD, function(x) x / max(x) * 1000),
    .SDcols = c("jp", "bs", "ws", "age")
  ]
  DT[[i]][, c("age") := lapply(.SD, function(x) x / max(x) * 200), .SDcols = c("age")]
  summary(DT[[i]])
  boxplot(DT[[i]]$age ~ DT[[i]]$burned)
}

bc <- burnClassGenerator(DT[["train"]], 4:8)
# Show if the model is good at predicting burn state
(bc$AUC) # area under the curve

# print summary of mean values of each burn class
(summ <- burnClassSummary(bc$model))

# predict -- add Burn Class to object
set(DT[["test"]], NULL, "burnClass", burnClassPredict(bc$model, df = DT[["test"]]))
prob <- burnProbFromClass(bc$model, DT[["test"]])

## cleanup
withr::deferred_run()

## End(Not run)

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 (sumRows).

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

  3. Selects pixels where sumRows > 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.

  • The landcoverDT temporary columns sumRows and age are removed prior to return.

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

Iteratively calculate youngAge column in FS covariates

Usage

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

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


preparing covariates for fitting modules

Description

preparing covariates for fitting modules

Usage

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

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


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.


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


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 list of data.table objects named by fireYear and containing fire buffer indices

Value

a long-layout data.table of climate values in each pixel and year


Classify pixelGroups by flammability

Description

Classify pixelGroups by flammability

Usage

cohortsToFuelClasses(
  cohortData,
  pixelGroupMap,
  flammableRTM,
  landcoverDT = NULL,
  sppEquiv,
  sppEquivCol,
  cutoffForYoungAge,
  fuelClassCol = "FuelClass",
  requiredFuelClasses
)

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.

Value

a SpatRaster of biomass by fuel class as determined by fuelClassCol and cohortData.


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


Plot the historical and projected climate values for flammable land surface

Description

Plot the historical and projected climate values for flammable land surface

Usage

compareClimate(
  historicalClimate,
  projectedClimate,
  flammableRTM = NULL,
  Ylimits = NULL,
  firstHistoricalYear = 2001,
  firstProjectedYear = 2011,
  climVar = "climate variable"
)

Arguments

historicalClimate

SpatRaster of historical climate variable

projectedClimate

SpatRaster of projected climate variable

flammableRTM

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

Ylimits

the upper and lower MDC range for the plot

firstHistoricalYear

the earliest year of historical data

firstProjectedYear

the earliest year of projected data

climVar

the name of the climate variable for axis label

Value

a ggplot object

Examples

## Not run: 
compareClimate(
  historicalClimate = simOutPreamble$historicalClimateRasters$Climate,
  projectedClimate = simOutPreamble$projectedClimateRasters$Climate,
  flammableRTM = fSsimDataPrep$flammableRTM
)

## End(Not run)

Plot the historical and projected MDC for a flammable land surface

Description

Plot the historical and projected MDC for a flammable land surface

Usage

compareMDC(
  historicalMDC,
  projectedMDC,
  flammableRTM = NULL,
  Ylimits = c(80, 220),
  firstHistoricalYear = 2001,
  firstProjectedYear = 2011
)

Arguments

historicalMDC

raster stack of historical MDC

projectedMDC

raster stack of projected MDC

flammableRTM

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

Ylimits

the upper and lower MDC range for the plot

firstHistoricalYear

the earliest year of historical data

firstProjectedYear

the earliest year of projected data

Value

a ggplot object

Examples

## Not run: 
compareMDC(
  historicalMDC = simOutPreamble$historicalClimateRasters$MDC,
  projectedMDC = simOutPreamble$projectedClimateRasters$MDC,
  flammableRTM = fSsimDataPrep$flammableRTM
)

## End(Not run)

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


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.


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. The output raster encodes three priority layers: cells classified as 2 in any ELF (highest priority, labelled by ELF ID), cells classified as 1 in two or more ELFs (shared agreement, labelled by ELF ID), and a 0 background for all other in-domain cells.

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:

  • 2 hits override everything else,

  • 1 hits appear only where at least two ELFs agree, 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::classify(), terra::mosaic(), terra::cover()


Build a Canada-wide raster template for ELF construction

Description

Downloads the SCANFI v1.2 Douglas-fir (SW) raster from NRCan, aggregates it by a factor of 8, 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 the remote file's hash, so the template is only rebuilt when the upstream source changes.

Usage

ELFtemplateRaster(inputPath)

Arguments

inputPath

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

Details

The Douglas-fir layer is used purely for its spatial footprint and grid — the cell values themselves are not meaningful for ELF construction. The source layer is fetched from ⁠https://ftp.maps.canada.ca/pub/nrcan_rncan/Forests_Foret/SCANFI/v1/⁠. 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 8× the native SCANFI resolution and is suitable as a template for downstream ELF construction.

See Also

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


Extract the elements of the special terms, i.e. the variable and the knot value

Description

Used by the ignition formula machinery to parse a pw(v, k) term and return its components without evaluating them. The variable and knot names are returned as character strings (the captured symbols), or kept as AsIs if v was wrapped with I().

Usage

extractSpecial(v, k)

Arguments

v

The variable symbol or expression appearing inside pw().

k

The knot value or symbol; must be supplied.

Value

A list with elements variable (character, or AsIs expression) and knot (character form of k). Errors if k is missing.


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. Default is correct on GoogleDrive. Must be a folder.

targetFile

A filename to search on the folder on Google Drive. The default is correct for fireSense parameters.

destinationPath

A path for the downloaded file.

useCache

Logical. Forwarded to reproducible::prepInputs(useCache = ...) to control whether downloaded/processed inputs are cached. Default TRUE.

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
)

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.

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.

  • Mutual exclusivity is enforced via makeMutuallyExclusive() using all fuel-class columns and the land-cover columns (excluding pixelID); youngAge is made exclusive to them.

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

  • 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.

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)

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.

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").

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

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

  • spreadFitAdditionalColNamesTxt: character vector of extra simList-slot/column names attached to spread-fit outputs ("numIterations", "objFunVal", "params", "sppEquiv", "nonForestedLCCGroups", "missingLCCgroup").


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)
# )

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.


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 = ...).

plot

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

Value

A sf spatial points object.


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

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.

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")

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.


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")

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.


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)

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

logisticAll(logisticPars, mat, covPars, lowerSpreadProb)

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; its length selects which variant logisticAll dispatches to.

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.

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.

Value

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


Logistic parameter names

Description

Logistic parameter names

Usage

logisticParamNames

Format

An object of class list of length 4.

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 = ".")

Arguments

x

A polygon layer (SpatVector or sf) or gridded layer (SpatRaster) that maps the entire area of interest for the ELFs. If missing, it will try to use scfmutils::prepInputsFireRegimePolys(type = "FRU") if scfmutils is installed. Currently, only options with a column called FRU will work.

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.

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 = c(20, 31, 32, 33),
  flammabilityThreshold = 0.1,
  writeTo = NULL,
  overwrite = TRUE,
  destinationPath
)

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 c(20, 31, 32, 33). 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.

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.

  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)

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.

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 = 15,
  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


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. The result is then clamped from below by minSize. Used when generating non-burned "control" pixels around historical fire perimeters.

Usage

multiplier(size, minSize = 1000, baseMultiplier = 5)

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 1000.

baseMultiplier

Numeric scalar. Asymptotic multiplier for large fires (as size grows, the effective multiplier tends to baseMultiplier). Default 5.

Value

Integer vector the same length as size, giving the target buffered area in pixels for each fire.


objNlminb

Description

Wrapper around stats::nlminb() that calls one of the ignition objective functions (.objFunIgnition or .objFunIgnitionPW, dispatched by hvPW) and falls back to stats::optim() (L-BFGS-B) when nlminb reports a "false convergence" or similar non-convergence code (codes 7-14).

Usage

objNlminb(x, objective, lower, upper, control, hvPW, ...)

Arguments

x

Numeric vector. Starting parameter values for the optimizer.

objective

Function. Objective function to minimize, typically .objFunIgnition or .objFunIgnitionPW.

lower

Numeric vector. Lower bounds on each parameter, same length as x.

upper

Numeric vector. Upper bounds on each parameter, same length as x.

control

List of control options passed to stats::nlminb() (or stats::optim() on fallback, with iter.max and eval.max dropped).

hvPW

Logical. If TRUE, dispatches to the piecewise objective (formula is rebuilt per call); if FALSE, dispatches to the non-piecewise objective (pre-built mm is supplied).

...

Additional arguments passed through to objective. Expected names are: linkinv, nll, sm, nx, mm, updateKnotExpr, mod_env, offset, formula.

Value

The list returned by stats::nlminb() on success, or the result of stats::optim() (with value renamed to objective) on fallback.


Order of Magnitude

Description

Order of Magnitude

Usage

oom(x)

Arguments

x

a numeric

Value

the order of magnitude


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.


Plot burn summary

Description

Create plot with subplots showing: a) area burned; b) number of fires; c) mean fire size.

Usage

plotBurnSummary(
  climateScenario,
  studyAreaName,
  outputDir,
  Nreps,
  years,
  pixelSize
)

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

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
)

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).

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


Plot historic ignitions, escapes, and area burned

Description

Plot historic ignitions, escapes, and area burned

Usage

plotHistoricFires(
  climateScenario,
  studyAreaName,
  outputDir,
  pixelSize,
  firePolys,
  ignitionPoints
)

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) size

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.

Value

list of file names corresponding to the figures and/or objects written to disk


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)

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.

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).

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.

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)

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)

Handling piecewise terms in a formula

Description

Implements the right-hand half of a piecewise-linear (hinge) term: pmax(variable - knot, 0). Used in formulas passed to the ignition fitting routines so that a covariate can have zero effect below a threshold and a linear effect above it.

Usage

pw(variable, knot)

Arguments

variable

Numeric vector of covariate values.

knot

Numeric scalar threshold (knot) below which the term is 0.

Value

Numeric vector the same length as variable, with each element equal to max(variable[i] - knot, 0).


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
)

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

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)

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 and escapesTxt to refer to the expected response column names. 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


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).

Internal function called by runDEoptim. Runs DEoptim::DEoptim in steps, caching results and optionally visualizing progress after each step.

Usage

runDEoptim(
  landscape,
  annualDTx1000,
  nonAnnualDTx1000,
  fireBufferedListDT,
  historicalFires,
  itermax,
  initialpop = NULL,
  NP = NULL,
  trace,
  strategy,
  cores = NULL,
  paths,
  libPath = .libPaths()[1],
  logPath = tempfile(sprintf("fireSense_SpreadFit_%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 = c("SNLL", "adTest"),
  maxFireSpread,
  Nreps,
  thresh = 550,
  .c = 0.5,
  .verbose,
  visualizeDEoptim = logPath,
  .plots = "screen",
  .plotSize = list(height = 1600, width = 2000),
  rep = 1L,
  runName = ""
)

DEoptimIterative(
  itermax,
  lower,
  upper,
  control,
  formulaToFit,
  covMinMax,
  tests = c("SNLL", "adTest"),
  objFunCoresInternal,
  maxFireSpread,
  Nreps,
  visualizeDEoptim,
  figPath,
  cachePath,
  mutuallyExclusive,
  doObjFunAssertions = getOption("fireSenseUtils.assertions", TRUE),
  iterStep = 25,
  thresh = 550,
  .c = 0.5,
  .verbose,
  .plots = "screen",
  .plotSize = list(height = 1600, width = 2000),
  rep = 1L
)

termsInDEoptim(fireSense_spreadFormula, thresh, 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

A character string indicating an R package library directory. This location must exist on each machine, though the function will make sure it does internally.

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.

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().

thresh

The threshold for accepting fits; e.g., from mod$thresh.

.c

Numeric scalar in ⁠[0, 1]⁠. Crossover constant passed through to DEoptim::DEoptim.control() as c (the speed of crossover adaptation). Default 0.5.

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".

.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 DEoptimIterative() and used as a suffix for the cache .functionName so that runs with different runName values get distinct cache entries. Default "" (no suffix).

control

passed to DEoptim::DEoptim.control

figPath

directory where figures will be saved, if relevant

cachePath

A cacheRepo (see reproducible::Cache()).

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 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 ELFs modules and optionally update googledrive png

Description

Extracting only the "ELF" module, runs the projectmodule via SpaDES.core::simInitAndSpades2() with caching (optionally updates a Google Drive file if the current user is "emcintir"), and returns the vector of polygon IDs from spreadFitPreRun.

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, $paths$modulePath, and $params$fireSense_ELFs.

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

A googledrive url where the ELF data.frame that contains geometries and fitted SpreadFit parameters and several other attributes.

Details

The function:

  1. Restricts preRunSetupProject$modules to entries matching "ELFs".

  2. Collects all .R source files under each module directory (recursively), excluding any under tests/, and uses these as part of the cache key.

  3. Retrieves remote metadata (hash) from a Google Drive file URL and assigns the remote hash to preRunSetupProject$params$fireSense_ELFs$hashSpreadFitRemoteFile.

  4. Initializes and runs the simulation with SpaDES.core::simInitAndSpades2(), wrapping the call in Cache() so that the run is skipped unless inputs (source files and remote hash) have changed.

  5. If the current SpaDES.project::user() is "emcintir", updates the Google Drive file at the provided URL with any output files whose names contain "ELF", caching the update by cacheId(sim).

  6. Returns sim$spreadFitPreRun[[fireSenseUtils::polygonIDTxt]].

Internal Cacheing relies on two extra keys:

  • src: paths to module .R files (excluding tests/).

  • remoteHash: the remote metadata hash obtained from the URL.

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.

  • $params$fireSense_ELFs: a list where hashSpreadFitRemoteFile can be set.

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.)

Side Effects

Updates a Google Drive file when the current user is "emcintir" and when the run produces outputs with names containing "ELF".

Notes

  • The remote file URL is hard-coded as: "https://drive.google.com/file/d/1tkC944mPzR9-y-qCMDB5o2cAR_1MoDz4/view?usp=drive_link".

  • Cache() and cacheId() are assumed to be available (typically from reproducible in SpaDES workflows).

  • asPath() is expected to be available in your environment (commonly from reproducible); adjust if your project defines it elsewhere.

Author(s)

Based on the provided code snippet.

See Also

simInitAndSpades2, Cache, drive_update

Examples

## Not run: 
# Assuming 'prj' is a valid SpaDES project list:
# prj <- somePreparationFunction(...)
ids <- runELFs(prj)

## End(Not run)

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
)

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. These non annual covariates must have a date column that can be assessed against yr (via nonAnnualDTx1000[[whKeep]][annDTx1000, on = "pixelID"])

indexNonAnnual

data.table with 2 columns: ind and date which links the list elements in nonAnnualDTx1000 with their date (in case nonAnnualDTx1000 is not a named list. This is not necessary if the nonAnnualDTx1000 is named with equivalent convention (e.g., character or numeric with year) as yr.

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.

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; its length selects which variant logisticAll dispatches to.

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 0.28, which is overly generous unless there are many non-flammable pixels (e.g., lakes).

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 0.13.

Value

This returns the full data.table to be used for fireSense, on the original numeric i.e., real scale, with the x1000 reversed.


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

LCC

raster brick of aggregated LCC classes

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


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


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