| 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 |
fireSenseUtils packageUtilities for working with the 'fireSense' group of 'SpaDES' modules.
Maintainer: Eliot J B McIntire [email protected] (ORCID)
Authors:
Jean Marchal [email protected]
Alex M Chubaty [email protected] (ORCID)
Ian Eddy [email protected] (ORCID)
Useful links:
Report bugs at https://github.com/PredictiveEcology/fireSenseUtils/issues
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.
.objFunIgnition(params, linkinv, nll, sm, nx, mm, mod_env, offset).objFunIgnition(params, linkinv, nll, sm, nx, mm, mod_env, offset)
params |
Numeric vector of parameter values supplied by the optimizer. |
linkinv |
Function. Inverse link function (e.g. |
nll |
Quoted/unevaluated R expression that computes the negative
log-likelihood when evaluated in |
sm |
Square numeric matrix. Parameter scaling matrix applied as
|
nx |
Integer. Number of covariate parameters (i.e. number of
columns in |
mm |
Numeric model matrix containing covariate values. |
mod_env |
An environment (or data-frame coerced via |
offset |
Numeric vector the same length as |
Numeric scalar: the negative log-likelihood, or 1e20 if the
inverse-link produces non-finite or non-positive values.
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.
.objFunIgnitionPW( params, formula, linkinv, nll, sm, updateKnotExpr, nx, mod_env, offset ).objFunIgnitionPW( params, formula, linkinv, nll, sm, updateKnotExpr, nx, mod_env, offset )
params |
Numeric vector of parameter values supplied by the optimizer. Includes both covariate coefficients and knot values. |
formula |
Model formula (or string coercible by |
linkinv |
Function. Inverse link function. |
nll |
Quoted R expression evaluating to the negative log-likelihood
when evaluated in |
sm |
Square numeric matrix. Parameter scaling matrix. |
updateKnotExpr |
Quoted R expression that copies the latest knot
values from |
nx |
Integer. Number of covariate parameters. |
mod_env |
An environment (or data-frame) containing the covariates
and the variables updated by |
offset |
Numeric vector. Model offset added to the linear predictor. |
Numeric scalar: the negative log-likelihood, or 1e20 if the
inverse-link produces negative, NA, or infinite values.
fireSense_spreadFit moduleObjective function for fireSense_spreadFit module
.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, ... ).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, ... )
par |
parameters |
landscape |
A |
annualDTx1000 |
A list of data.table class objects. Each list element is
data from a single calendar year, and whose name takes the form |
nonAnnualDTx1000 |
Like |
formulaToFit |
Formula, put provided as a character string, not class |
historicalFires |
A named list of |
fireBufferedListDT |
A named list of |
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 |
lowerSpreadProb |
Numeric. Lower bound for |
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 |
tests |
One or more of |
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 |
doAssertions |
Logical. If |
plot.it |
Passed to |
objFunCoresInternal |
Internally, this function can use |
lanscape1stQuantileThresh |
A |
thresh |
Threshold multiplier used in SNLL fire size ( |
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 |
... |
This is not used here, but allows for extraneous arguments to not break this function. |
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
abbreviateSpNames(df)abbreviateSpNames(df)
df |
data.table |
data.table
SpatRaster to data.table
Convert list of annual SpatRaster to data.table
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, ...)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, ...)
x |
|
whNotNA |
Pixel indexes that should go through this process (i.e. not NA) |
... |
Not currently used |
data.table of the SpatRaster or the list
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()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
assessFuelClasses( landscape, fuelCol, sppEquiv, sppEquivCol, targetNonForestClasses = 2, targetFuelClasses = 5, nonforestLCC, pValue = 0.001 )assessFuelClasses( landscape, fuelCol, sppEquiv, sppEquivCol, targetNonForestClasses = 2, targetFuelClasses = 5, nonforestLCC, pValue = 0.001 )
landscape |
data.table created by |
fuelCol |
the column in |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
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 |
a list of three objects:
modSppEquiv, a data.table with assigned fuel classes for each tree species;
nonForestedLCCGroups, a named list of non-forest land cover classes grouped by fuel class;
missingLCCgroup, the class in nonForestLCCGroups to assign forested pixels missing from cohortData;
Buffer ignition points to create non-ignitions for model
bufferIgnitionPoints(ignitionPoints, rtm, bufferSize)bufferIgnitionPoints(ignitionPoints, rtm, bufferSize)
ignitionPoints |
|
rtm |
a template raster |
bufferSize |
the size of the buffers |
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
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, ... )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, ... )
poly |
|
rasterToMatch |
A |
areaMultiplier |
Either a scalar that will buffer |
verb |
Logical or numeric related to how much verbosity is printed. |
polyName |
Optional character string of the polygon layer name (not the individual polygons
on a |
field |
Passed to |
minSize |
The absolute minimum size of the buffer & non-buffer together. This will
be imposed after |
cores |
number of processor cores to use |
... |
passed to |
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
bufferToAreaRast(fireIDraster, areaMultiplier, minSize, flammableRTM, verb = 1)bufferToAreaRast(fireIDraster, areaMultiplier, minSize, flammableRTM, verb = 1)
fireIDraster |
a |
areaMultiplier |
A scalar that will buffer |
minSize |
The absolute minimum size of the buffer & non-buffer together.
This will be imposed after |
flammableRTM |
a |
verb |
Logical or numeric related to how much verbosity is printed. |
a data.table with fire ID, buffer status, and pixelID
cohortData with burn columnModify cohortData with burn column
buildCohortBurnHistory(cohortData, pixelGroupMap, firePolys, year)buildCohortBurnHistory(cohortData, pixelGroupMap, firePolys, year)
cohortData |
either a |
pixelGroupMap |
either a |
firePolys |
the output of |
year |
length-two vector giving temporal period used to subset |
cohortData modified with burn status
Generate, Summarize, Predict Burn Classes from Covariates
burnClassGenerator(df, numClasses = 4:9, AUC = TRUE, plotAUC = FALSE) burnClassSummary(mod) burnClassPredict(mod, df) burnProbFromClass(mod, df)burnClassGenerator(df, numClasses = 4:9, AUC = TRUE, plotAUC = FALSE) burnClassSummary(mod) burnClassPredict(mod, df) burnProbFromClass(mod, df)
df |
A |
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 |
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).
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 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.
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.
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.
Eliot McIntire
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
## 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)## 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)
youngAge maskIdentifies 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).
calcNonForestYoungAge(landcoverDT, NFTSD, LCCras, cutoffForYoungAge)calcNonForestYoungAge(landcoverDT, NFTSD, LCCras, cutoffForYoungAge)
landcoverDT |
data.table.
A |
NFTSD |
numeric.
A numeric vector (or similar) that can be indexed by |
LCCras |
SpatRaster.
A |
cutoffForYoungAge |
numeric(1).
Age threshold; pixels with |
The function proceeds as follows:
Determines the set of non-forest columns as all columns in landcoverDT
except pixelID, and computes a per-row sum (sumRows).
Retrieves pixel ages from NFTSD using pixelID as indices.
Selects pixels where sumRows > 0 and age < cutoffForYoungAge;
these pixels are considered "young non-forest".
Sets those pixels to 0 in every layer of LCCras using cell indexing.
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.
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.
Terra package reference manual and vignettes for SpatRaster operations
(Hijmans, R.J.).
data.table reference: .SD, :=, and efficient grouping/filtering
(Dowle, M., & Srinivasan, A.).
terra::rast(), terra::values(), terra::setValues() for raster creation
and manipulation.
data.table semantics for .SD, in-place updates (:=), and fast
row/column operations.
## 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)## 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)
youngAge column in FS covariatesIteratively calculate youngAge column in FS covariates
calcYoungAge( years, annualCovariates, standAgeMap, fireBufferedListDT, cutoffForYoungAge = 15 )calcYoungAge( years, annualCovariates, standAgeMap, fireBufferedListDT, cutoffForYoungAge = 15 )
years |
the years over which to iterate |
annualCovariates |
list of data.table objects with |
standAgeMap |
template |
fireBufferedListDT |
data.table containing non-annual burn and buffer |
cutoffForYoungAge |
Numeric. Default is 15. This is the age below which the pixel is considered
"young" –> |
a raster layer with unified stand age and time-since-disturbance values
preparing covariates for fitting modules
castCohortData( cohortData, pixelGroupMap, lcc, ageMap = NULL, missingLCC, year = NULL, cutoffForYoungAge = 15 )castCohortData( cohortData, pixelGroupMap, lcc, ageMap = NULL, missingLCC, year = NULL, cutoffForYoungAge = 15 )
cohortData |
A |
pixelGroupMap |
A |
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 |
year |
numeric representing the year represented by |
cutoffForYoungAge |
Numeric. Default is 15. This is the age below which the pixel is considered
"young" –> |
a trimmed cohortData with wide-layout and rows for every pixel in lcc
spreadFitRun
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.
chk_duplicatedStartPixels(cells, size) .doDataChecks(moduleName, envir, attribs, fml)chk_duplicatedStartPixels(cells, size) .doDataChecks(moduleName, envir, attribs, fml)
cells |
Integer vector of raster cell indices (pixel IDs) at which fires are scheduled to start. |
size |
Integer vector the same length as |
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 |
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 |
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.
Map
Ensure fire points are located on flammable pixels inside a fire polygon
Intended to be run using Map
cleanUpSpreadFirePoints(firePoints, bufferDT, flammableRTM, idCol)cleanUpSpreadFirePoints(firePoints, bufferDT, flammableRTM, idCol)
firePoints |
a |
bufferDT |
a data.table of burned cells, output from |
flammableRTM |
a |
idCol |
Character. Name of the column in |
a list of harmonized points and polygons
Converts stacks of climate rasters to data.table and optionally subsets to index
climateRasterToDataTable(historicalClimateRasters, Index = NULL)climateRasterToDataTable(historicalClimateRasters, Index = NULL)
historicalClimateRasters |
named list of |
Index |
optional list of |
a long-layout data.table of climate values in each pixel and year
pixelGroups by flammabilityClassify pixelGroups by flammability
cohortsToFuelClasses( cohortData, pixelGroupMap, flammableRTM, landcoverDT = NULL, sppEquiv, sppEquivCol, cutoffForYoungAge, fuelClassCol = "FuelClass", requiredFuelClasses )cohortsToFuelClasses( cohortData, pixelGroupMap, flammableRTM, landcoverDT = NULL, sppEquiv, sppEquivCol, cutoffForYoungAge, fuelClassCol = "FuelClass", requiredFuelClasses )
cohortData |
A |
pixelGroupMap |
A |
flammableRTM |
a |
landcoverDT |
Optional table of non-forest land cover classes and pixel indices.
It will override pixel values in |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
cutoffForYoungAge |
age at and below which pixels are considered 'young' |
fuelClassCol |
the column in |
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. |
a SpatRaster of biomass by fuel class as determined by fuelClassCol and cohortData.
Merging and assignment of fuel classes
combine_fuel_classes(df, targetFuelClasses = 5, lowThreshold = 0.05)combine_fuel_classes(df, targetFuelClasses = 5, lowThreshold = 0.05)
df |
created during |
targetFuelClasses |
the number of classes at which to stop further merging |
lowThreshold |
species with |
a data.table with assigned fuel classes for each species
Plot the historical and projected climate values for flammable land surface
compareClimate( historicalClimate, projectedClimate, flammableRTM = NULL, Ylimits = NULL, firstHistoricalYear = 2001, firstProjectedYear = 2011, climVar = "climate variable" )compareClimate( historicalClimate, projectedClimate, flammableRTM = NULL, Ylimits = NULL, firstHistoricalYear = 2001, firstProjectedYear = 2011, climVar = "climate variable" )
historicalClimate |
|
projectedClimate |
|
flammableRTM |
a |
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 |
a ggplot object
## Not run: compareClimate( historicalClimate = simOutPreamble$historicalClimateRasters$Climate, projectedClimate = simOutPreamble$projectedClimateRasters$Climate, flammableRTM = fSsimDataPrep$flammableRTM ) ## End(Not run)## 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
compareMDC( historicalMDC, projectedMDC, flammableRTM = NULL, Ylimits = c(80, 220), firstHistoricalYear = 2001, firstProjectedYear = 2011 )compareMDC( historicalMDC, projectedMDC, flammableRTM = NULL, Ylimits = c(80, 220), firstHistoricalYear = 2001, firstProjectedYear = 2011 )
historicalMDC |
raster stack of historical MDC |
projectedMDC |
raster stack of projected MDC |
flammableRTM |
a |
Ylimits |
the upper and lower MDC range for the plot |
firstHistoricalYear |
the earliest year of historical data |
firstProjectedYear |
the earliest year of projected data |
a ggplot object
## Not run: compareMDC( historicalMDC = simOutPreamble$historicalClimateRasters$MDC, projectedMDC = simOutPreamble$projectedClimateRasters$MDC, flammableRTM = fSsimDataPrep$flammableRTM ) ## End(Not run)## Not run: compareMDC( historicalMDC = simOutPreamble$historicalClimateRasters$MDC, projectedMDC = simOutPreamble$projectedClimateRasters$MDC, flammableRTM = fSsimDataPrep$flammableRTM ) ## End(Not run)
data.frame
Convert covariates to/from integers for smaller footprint; make data.frame
covsX1000AndSetDF( annualList, nonAnnualList, fireBufferedList, fireLociList, paramOrder, toX1000Integer = TRUE )covsX1000AndSetDF( annualList, nonAnnualList, fireBufferedList, fireLociList, paramOrder, toX1000Integer = TRUE )
annualList |
Named list of |
nonAnnualList |
Named list of |
fireBufferedList |
Named list of |
fireLociList |
Named list of |
paramOrder |
Character vector of the order of covariates that will be used. |
toX1000Integer |
Logical. If |
a data.table with relevant columns made mutually exclusive
NAs in a data.table with zerosModifies 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.
dtReplaceNAwith0(DT, colsToUse = NULL)dtReplaceNAwith0(DT, colsToUse = NULL)
DT |
A |
colsToUse |
Character vector of column names in |
DT, invisibly modified by reference; columns are unchanged
where no NAs were present.
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.
ELFsInStudyArea(studyArea, inputPath, ELFsRaster = NULL, ELFsPolygon = NULL)ELFsInStudyArea(studyArea, inputPath, ELFsRaster = NULL, ELFsPolygon = NULL)
studyArea |
A |
inputPath |
Character. Directory in which to store any downloads
produced by |
ELFsRaster |
Optional named list (one entry per ELF) of |
ELFsPolygon |
Optional |
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.
A categorical SpatRaster with a value/ELFind levels table,
where ELFind gives the ELF identifier (or "none" for background).
makeELFs(), terra::classify(), terra::mosaic(),
terra::cover()
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.
ELFtemplateRaster(inputPath)ELFtemplateRaster(inputPath)
inputPath |
Character. Directory in which to store the downloaded
source raster and the resulting |
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.
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.
reproducible::prepInputs(), reproducible::Cache(),
terra::aggregate(), terra::writeRaster()
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().
extractSpecial(v, k)extractSpecial(v, k)
v |
The variable symbol or expression appearing inside |
k |
The knot value or symbol; must be supplied. |
A list with elements variable (character, or AsIs expression)
and knot (character form of k). Errors if k is missing.
Download the FireSense parameter object, strip the list columns and convert to a SpatVector or SpatRaster.
fireSenseCloudParameters( url = paste0("https://drive.google.com/file/d/", "1oJX7V5wPSj49C6wt59yD9RBplfZ7Cp-f/view?usp=drive_link"), targetFile = "fireSenseParams.rds", destinationPath = ".", useCache = TRUE )fireSenseCloudParameters( url = paste0("https://drive.google.com/file/d/", "1oJX7V5wPSj49C6wt59yD9RBplfZ7Cp-f/view?usp=drive_link"), targetFile = "fireSenseParams.rds", destinationPath = ".", useCache = TRUE )
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 |
The object and the rds file saved to destinationPath.
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.
fireSenseCloudParametersMap(rasterize = FALSE, plot = TRUE, res = 5000, ...)fireSenseCloudParametersMap(rasterize = FALSE, plot = TRUE, res = 5000, ...)
rasterize |
Logical. If |
plot |
Logical. If |
res |
The resolution of the raster if |
... |
Other parameters passed to |
The map, either SpatRaster or SpatVector
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.
fireSenseCovariatesCreate( cohortData, pixelGroupMap, flammableRTM, sppEquiv, landcoverDT, fuelClassCol, requiredFuelClasses = NULL, sppEquivCol, missingLCCgroup, nonForestedLCCGroups, nonForest_timeSinceDisturbance, cutoffForYoungAge, nonForestCanBeYoungAge, studyAreaName, useCache = TRUE )fireSenseCovariatesCreate( cohortData, pixelGroupMap, flammableRTM, sppEquiv, landcoverDT, fuelClassCol, requiredFuelClasses = NULL, sppEquivCol, missingLCCgroup, nonForestedLCCGroups, nonForest_timeSinceDisturbance, cutoffForYoungAge, nonForestCanBeYoungAge, studyAreaName, useCache = TRUE )
cohortData |
|
pixelGroupMap |
A raster (SpatRaster) or mapping structure linking cohort groups to pixels. |
flammableRTM |
A raster (SpatRaster) mask of flammable pixels (non-flammable typically |
sppEquiv |
Species equivalency table used to map species codes to fuel-class groupings. |
landcoverDT |
|
fuelClassCol |
Character name of the fuel-class column produced/expected by |
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 |
missingLCCgroup |
A single unquoted column name (passed to |
nonForestedLCCGroups |
Named vector or list where names correspond to the non-forest land-cover
columns in |
nonForest_timeSinceDisturbance |
A raster/vector of time-since-disturbance (TSD) for non-forest pixels;
indexed by |
cutoffForYoungAge |
Numeric threshold (years). Pixels with TSD |
nonForestCanBeYoungAge |
Logical. If |
studyAreaName |
Character tag used for caching/user tags. |
useCache |
Logical. If |
The function:
Calls cohortsToFuelClasses() to derive fuel-class rasters from cohorts.
Converts these to a long data table keyed by pixelID and joins to landcoverDT.
Verifies there are no NA values across covariate columns and raises an error otherwise.
Marks pixels with all-zero covariates as the provided missingLCCgroup.
Enforces mutual exclusivity among the specified fuel/landcover columns.
Applies logMinB to all fuel-class columns (excluding youngAge).
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.
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).
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).
cohortsToFuelClasses, makeMutuallyExclusive,
logMinB, putBackIntoRaster, calcNonForestYoungAge
## 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)## 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)
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.
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
fuelClassPrep( pixelGroupMap, cohortData, rstLCC, nonflammableLCC, fires, nonforestLCC, yearRange )fuelClassPrep( pixelGroupMap, cohortData, rstLCC, nonflammableLCC, fires, nonforestLCC, yearRange )
pixelGroupMap |
A |
cohortData |
A |
rstLCC |
a landcover map |
nonflammableLCC |
nonflammable landcover in |
fires |
a single |
nonforestLCC |
vector or list of vectors of flammable non-forest LCC |
yearRange |
the range of years represented by this landscape |
data.table with cell, biomass, tree species or LCC for non-forest, and year of fire
# 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) # )# 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) # )
SpatialPoints from Canadian Fire DatabaseGet Fire SpatialPoints from Canadian Fire Database
getFirePoints_NFDB( url = NULL, studyArea = NULL, rasterToMatch = NULL, redownloadIn = 1, years = 1991:2017, fireSizeColName = "SIZE_HA", NFDB_pointPath )getFirePoints_NFDB( url = NULL, studyArea = NULL, rasterToMatch = NULL, redownloadIn = 1, years = 1991:2017, fireSizeColName = "SIZE_HA", NFDB_pointPath )
url |
Passed to |
studyArea |
A |
rasterToMatch |
A |
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 |
A sf spatial points object.
SpatialPoints from Canadian Fire DatabaseGet Fire SpatialPoints from Canadian Fire Database
getFirePoints_NFDB_V2( url = NULL, studyArea = NULL, redownloadIn = 1, years = 1991:2017, fireSizeColName = "SIZE_HA", NFDB_pointPath = NULL, fun = "sf::st_read", plot = FALSE )getFirePoints_NFDB_V2( url = NULL, studyArea = NULL, redownloadIn = 1, years = 1991:2017, fireSizeColName = "SIZE_HA", NFDB_pointPath = NULL, fun = "sf::st_read", plot = FALSE )
url |
Passed to |
studyArea |
A |
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 |
fun |
Character. The function (as a string, e.g., |
plot |
logical indicating whether to produce plot of fire points. Default FALSE. |
A sf spatial points object.
Download and prepare fire data from National Fire Database
getFirePolygons(url, years, useInnerCache = FALSE, ...)getFirePolygons(url, years, useInnerCache = FALSE, ...)
url |
Character (or |
years |
years to filter fire polygons by |
useInnerCache |
logical indicating whether to cache the |
... |
additional arguments passed to |
list of fire polygons by year
latestNBACUrl() for the discovery helper used when url is missing.
Mostly this is about 2 things:
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.
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:
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.
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.
harmonizeBufferAndPoints(cent, buff, ras, idCol = "FIRE_ID") harmonizeBufferAndPoints(cent, buff, ras, idCol = "FIRE_ID")harmonizeBufferAndPoints(cent, buff, ras, idCol = "FIRE_ID") harmonizeBufferAndPoints(cent, buff, ras, idCol = "FIRE_ID")
cent |
List of points as |
buff |
List of |
ras |
The raster that created the |
idCol |
The column name as a character string with the fire ids.
Defaults to |
Outer wrapper on spread fire polygon data munging that does several things:
ensure buffered fires are entirely in studyArea;
ensure every fire has a corresponding ignition point, and vice versa;
ensure these points are flammable.
harmonizeFireData( firePolys, flammableRTM, spreadFirePoints, areaMultiplier, minSize, pointsIDcolumn = "FIRE_ID", cores = 1 )harmonizeFireData( firePolys, flammableRTM, spreadFirePoints, areaMultiplier, minSize, pointsIDcolumn = "FIRE_ID", cores = 1 )
firePolys |
the semi-processed fire polys, with field matching |
flammableRTM |
a |
spreadFirePoints |
the ignition points corresponding to |
areaMultiplier |
Either a scalar that will buffer |
minSize |
an alternative to |
pointsIDcolumn |
the name of the column denoting fire ids in both
|
cores |
Positive integer.Number of CPU cores (threads) to use for parallel operations. |
Creates a standardized name by combining a pre prefix, a normalized
igOrEsc token (case-transformed), and a post suffix.
igOrEscNames( igOrEsc, pre = "fireSense_", post, case = c("lower", "camel", "sentence", "title") )igOrEscNames( igOrEsc, pre = "fireSense_", post, case = c("lower", "camel", "sentence", "title") )
igOrEsc |
|
pre |
|
post |
|
case |
One of |
character(1) constructed as paste0(pre, transformed(igOrEsc), post).
igOrEscNames("ignition", post = "Covariates") igOrEscNames("escape", pre = "fs_", post = "_Formula", case = "camel")igOrEscNames("ignition", post = "Covariates") igOrEscNames("escape", pre = "fs_", post = "_Formula", case = "camel")
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.
latestNBACUrl( base = "https://cwfis.cfs.nrcan.gc.ca/downloads/nbac/", fallback = paste0(base, "NBAC_1972to2025_20260513_shp.zip") )latestNBACUrl( base = "https://cwfis.cfs.nrcan.gc.ca/downloads/nbac/", fallback = paste0(base, "NBAC_1972to2025_20260513_shp.zip") )
base |
Character. Directory listing URL (must be the parent folder that serves the autoindex page). |
fallback |
Character. URL to return when discovery fails. |
A single character URL.
Logistic functions using 2, 3, 4, or 5 parameters; logisticAll dispatches
to one of them based on length(logisticPars).
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)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)
x |
Numeric vector. Linear predictor (e.g. |
par |
Numeric vector of logistic parameters whose length matches the
variant: 2 for |
par1 |
Numeric scalar. Lower asymptote (replaces |
par4 |
Numeric scalar. Asymmetry factor (replaces |
logisticPars |
Numeric vector of logistic parameters; its length
selects which variant |
mat |
Numeric matrix of covariate values, one row per observation. |
covPars |
Numeric vector of covariate coefficients (same length as
|
lowerSpreadProb |
Numeric scalar in |
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.
Numeric vector of logistic values; same length as x (or
nrow(mat) for logisticAll).
Logistic parameter names
logisticParamNameslogisticParamNames
An object of class list of length 4.
A named list of length 4, with "2p", "3p", "4p", "5p" as names representing the 2-parameter etc. logistic curve.
Used for transforming Biomass to the log scale
logMinB(x)logMinB(x)
x |
Any value to be adjusted with log and a minimum B |
The original vector, logged with a minimum.
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.
makeELFs( x, desiredBuffer = 20000, maxArea = 2.4e+11, destinationPath = ".", singleSpatVector = FALSE, useCache = TRUE ) plotELFs(destinationPath = ".")makeELFs( x, desiredBuffer = 20000, maxArea = 2.4e+11, destinationPath = ".", singleSpatVector = FALSE, useCache = TRUE ) plotELFs(destinationPath = ".")
x |
A polygon layer ( |
desiredBuffer |
The distance in |
maxArea |
The area in |
destinationPath |
A path where any downloads should be put. |
singleSpatVector |
Logical. If |
useCache |
Logical. If |
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).
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.
Identify each year's individual fires and buffer them accordingly
makeFireIDs( year, fireRaster, flammableRTM, bufferForFireRaster, areaMultiplier, minSize = 5000, verb = 1 )makeFireIDs( year, fireRaster, flammableRTM, bufferForFireRaster, areaMultiplier, minSize = 5000, verb = 1 )
year |
numeric fire year |
fireRaster |
a |
flammableRTM |
a |
bufferForFireRaster |
buffer size used to group discrete patches of burned pixels as belonging to the same fire |
areaMultiplier |
A scalar that will buffer |
minSize |
The absolute minimum size of the buffer & non-buffer together.
This will be imposed after |
verb |
Logical or numeric related to how much verbosity is printed. |
a data.table with fire ID, buffer status, and pixelID
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.
makeFireSenseLCC( neededYear, to, maskTo = NULL, nonflammableLCC = c(20, 31, 32, 33), flammabilityThreshold = 0.1, writeTo = NULL, overwrite = TRUE, destinationPath )makeFireSenseLCC( neededYear, to, maskTo = NULL, nonflammableLCC = c(20, 31, 32, 33), flammabilityThreshold = 0.1, writeTo = NULL, overwrite = TRUE, destinationPath )
neededYear |
Numeric. The specific year required for the NTEMS Land Cover Classification (LCC) data. |
to |
A |
maskTo |
Optional. A |
nonflammableLCC |
Numeric vector. LCC codes representing non-flammable
land cover types (e.g., water, rock, urban). Defaults to |
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 |
overwrite |
Logical. Overwrite NTEMS FAO and flammable pixels rasters. |
destinationPath |
Character string. Directory path where source NTEMS data
will be downloaded/loaded (via |
This function performs several steps:
Downloads and prepares NTEMS LCC data for the specified neededYear using
LandR::prepInputs_NTEMS_LCC_FAO, cropping and masking to the target extent.
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.
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.
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.
A list of two SpatRaster objects:
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
the proportion of each pixel that is flammable in the native resolution
## 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)## 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)
glm that creates separate GLMs for each item in fuelWrapper on glm that creates separate GLMs for each item in fuel
makeGLM(fuel, landscape, form)makeGLM(fuel, landscape, form)
fuel |
vector of tree species or LCC in landscape by which to subset |
landscape |
created by |
form |
the formula to use - as a character |
landcoverDT object to classify and track non-forest land cover classesCreate landcoverDT object to classify and track non-forest land cover classes
makeLandcoverDT(rstLCC, flammableRTM, forestedLCC, nonForestedLCCGroups)makeLandcoverDT(rstLCC, flammableRTM, forestedLCC, nonForestedLCCGroups)
rstLCC |
landcover raster |
flammableRTM |
a |
forestedLCC |
vector of values representing forested landcover classes in |
nonForestedLCCGroups |
a named list of non-forested flammable landcover groups |
a data.table with columns for pixelID and binary presence of landcover
SpatialPointsDataFrame object to a list of data.table objectsMust 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.
makeLociList( ras, pts, idsCol = "FIRE_ID", dateCol = "YEAR", sizeCol = "POLY_HA", sizeColUnits = "ha", yearPrefix = "year" )makeLociList( ras, pts, idsCol = "FIRE_ID", dateCol = "YEAR", sizeCol = "POLY_HA", sizeColUnits = "ha", yearPrefix = "year" )
ras |
A raster that will be the template for cells (pixel ids) |
pts |
A list of |
idsCol |
Character string identifying column name in |
dateCol |
Character string identifying column name in |
sizeCol |
Character string identifying column name in |
sizeColUnits |
Character string. Either |
yearPrefix |
Character string prefixed to each year when naming the
output list elements (e.g. |
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
makeMutuallyExclusive(dt, mutuallyExclusiveCols = list(youngAge = c("vegPC")))makeMutuallyExclusive(dt, mutuallyExclusiveCols = list(youngAge = c("vegPC")))
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 |
a data.table with relevant columns made mutually exclusive
cohortData back into a SpatRaster with some extra detailsPut cohortData back into a SpatRaster with some extra details
makeRastersFromCD(class, cohortData, flammableRTM, pixelGroupMap)makeRastersFromCD(class, cohortData, flammableRTM, pixelGroupMap)
class |
|
cohortData |
A |
flammableRTM |
a |
pixelGroupMap |
A |
a SpatRaster with values equal to class biomass (B)
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).
makeTSD( year, firePolys = NULL, fireRaster = NULL, standAgeMap, lcc = NULL, cutoffForYoungAge = 15, pixToUpdate = NULL, flammablePixels = NULL )makeTSD( year, firePolys = NULL, fireRaster = NULL, standAgeMap, lcc = NULL, cutoffForYoungAge = 15, pixToUpdate = NULL, flammablePixels = NULL )
year |
the year represented by |
firePolys |
list of |
fireRaster |
a |
standAgeMap |
initial stand age map |
lcc |
Optional |
cutoffForYoungAge |
Numeric. Default is 15. This is the age below which the pixel is considered
"young" –> |
pixToUpdate |
Optional integer vector of |
flammablePixels |
Optional integer vector of flammable |
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.
a SpatRaster with values representing time since disturbance
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.
mergePreparedCovs( years, fuelCovsCoarse, ignitionFirePoints, nonForestedLCCGroups, ignitionClimateCoarse, lightningMap, digest, useCache = TRUE )mergePreparedCovs( years, fuelCovsCoarse, ignitionFirePoints, nonForestedLCCGroups, ignitionClimateCoarse, lightningMap, digest, useCache = TRUE )
years |
A vector or list of year identifiers passed to
|
fuelCovsCoarse |
A list (possibly nested by year) of named raster-layer
collections (e.g., |
ignitionFirePoints |
Ignition point locations (e.g., |
nonForestedLCCGroups |
A named vector or list whose names identify the LCC
(land-cover) classes considered non-forested. These names are used to split
|
ignitionClimateCoarse |
A list (possibly by year) of coarse climate rasters
(e.g., |
lightningMap |
A named |
digest |
A cache key supplement (character or list) forwarded to
|
useCache |
|
Processing steps:
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.
Optionally caches the list of per-year extractions with
reproducible::Cache() (function name tagged as "stackAndExtract").
Combines the list to a single data.table via data.table::rbindlist().
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).
Renames the cell column to pixelID, coerces year to numeric,
and appends lightning columns by indexing terra::values(terra::rast(lightningMap))
with pixelID.
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.
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
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.
fireSenseUtils::stackAndExtract, reproducible::Cache, data.table::rbindlist, terra::rast, terra::values
## 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)## 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)
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.
multiplier(size, minSize = 1000, baseMultiplier = 5)multiplier(size, minSize = 1000, baseMultiplier = 5)
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 |
baseMultiplier |
Numeric scalar. Asymptotic multiplier for large
fires (as |
Integer vector the same length as size, giving the target
buffered area in pixels for each fire.
objNlminbWrapper 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).
objNlminb(x, objective, lower, upper, control, hvPW, ...)objNlminb(x, objective, lower, upper, control, hvPW, ...)
x |
Numeric vector. Starting parameter values for the optimizer. |
objective |
Function. Objective function to minimize, typically
|
lower |
Numeric vector. Lower bounds on each parameter, same length
as |
upper |
Numeric vector. Upper bounds on each parameter, same length
as |
control |
List of control options passed to |
hvPW |
Logical. If |
... |
Additional arguments passed through to |
The list returned by stats::nlminb() on success, or the result
of stats::optim() (with value renamed to objective) on fallback.
Order of Magnitude
oom(x)oom(x)
x |
a numeric |
the order of magnitude
covPars and logisticPars
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.
paramsSeparate(par, parsModel)paramsSeparate(par, parsModel)
par |
Numeric vector of all parameters. The covariate parameters must be the second group. |
parsModel |
Integer. The number of covariates. |
list of 2 numeric vectors covPars and logisticPars, representing the
parameters for the covariates and the logistic equation, respectively.
Create plot with subplots showing: a) area burned; b) number of fires; c) mean fire size.
plotBurnSummary( climateScenario, studyAreaName, outputDir, Nreps, years, pixelSize )plotBurnSummary( climateScenario, studyAreaName, outputDir, Nreps, years, pixelSize )
climateScenario |
character string specifying the name of a CIMP6 climate scenario,
including SSP, formatted as in |
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: |
years |
integer (length 2). start and end years for comparison. |
pixelSize |
raster pixel (Cell) size |
list of file names corresponding to the figures and/or objects written to disk
Plot cumulative burn maps
plotCumulativeBurns( climateScenario, studyAreaName, outputDir, Nreps, years, rasterToMatch )plotCumulativeBurns( climateScenario, studyAreaName, outputDir, Nreps, years, rasterToMatch )
climateScenario |
character string specifying the name of a CIMP6 climate scenario,
including SSP, formatted as in |
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: |
years |
integer (length 2). start and end years for comparison. |
rasterToMatch |
A |
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
plotHistoricFires( climateScenario, studyAreaName, outputDir, pixelSize, firePolys, ignitionPoints )plotHistoricFires( climateScenario, studyAreaName, outputDir, pixelSize, firePolys, ignitionPoints )
climateScenario |
character string specifying the name of a CIMP6 climate scenario,
including SSP, formatted as in |
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 |
ignitionPoints |
A |
list of file names corresponding to the figures and/or objects written to disk
Predictions from ignition model
predictIgnition(model, data, rescaleFactor, lambdaRescaleFactor)predictIgnition(model, data, rescaleFactor, lambdaRescaleFactor)
model |
the model used to fit ignition data (must have a |
data |
data for prediction |
rescaleFactor |
spatial rescaling factor when predicted and fitted data are at different scales.
Calculated as: |
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). |
vector of predicted values.
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.
prepare_FuelCovsCoarse(..., rasTemplate, fact)prepare_FuelCovsCoarse(..., rasTemplate, fact)
... |
Arguments forwarded directly to
|
rasTemplate |
A raster-like object (typically |
fact |
|
The function performs the following steps:
Generates a fuel covariate data frame using
fireSenseUtils:::fireSenseCovariatesCreate(...).
Converts the data frame to a raster aligned with rasTemplate via
SpaDES.tools::rastFromDF().
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.
A terra::SpatRaster containing aggregated fuel covariate layers at the
coarser spatial resolution defined by fact.
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().
This function uses a non-exported function from fireSenseUtils via :::,
which may change without notice across package versions.
terra package reference manual: raster aggregation with aggregate().
SpaDES.tools package reference manual: rastFromDF().
fireSenseUtils package source code: fireSenseCovariatesCreate() (internal API).
terra::aggregate(), SpaDES.tools::rastFromDF()
## Not run: fuelCovsCoarse <- prepare_FuelCovsCoarse( fuels = fuelTable, rasTemplate = templateRaster, fact = 4 ) ## End(Not run)## Not run: fuelCovsCoarse <- prepare_FuelCovsCoarse( fuels = fuelTable, rasTemplate = templateRaster, fact = 4 ) ## End(Not run)
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.
prepare_ignitionClimate( ignitionClimateList, fact, digest = NULL, useCache = TRUE )prepare_ignitionClimate( ignitionClimateList, fact, digest = NULL, useCache = TRUE )
ignitionClimateList |
A named or unnamed |
fact |
|
digest |
A digest object (e.g., |
useCache |
|
The function:
Computes a robust digest of ignitionClimateList using
.robustDigest() to capture changes in input rasters.
Appends that digest to the user-supplied digest to form a composite
cache key (dig3).
Aggregates each raster via terra::aggregate(fact = fact, fun = mean).
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.
A list of aggregated climate rasters (typically terra::SpatRaster), in
one-to-one correspondence with ignitionClimateList.
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).
The symbols .robustDigest() and reproducible::Cache() must be available.
No validation is performed on input types. Aggregation is controlled by the fact parameter.
terra package reference manual: aggregate() (spatial raster aggregation).
reproducible package reference manual and vignettes: Cache() and .cacheExtra.
terra::aggregate(), reproducible::Cache()
## 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)## 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)
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.
prepare_LightningData(rtm, igAggFactor, dPath)prepare_LightningData(rtm, igAggFactor, dPath)
rtm |
|
igAggFactor |
|
dPath |
Character. Destination path forwarded to
|
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:
Resolves the Drive ID to a human URL, obtains remote metadata (hash),
Calls reproducible::prepInputs() with a reading function that should
return a raster aligned to sim$rasterToMatch,
Aggregates the raster with terra::aggregate(fact = P(sim)$igAggFactor),
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.
A named list of aggregated lightning rasters (class list of
terra::SpatRaster), with names matching:
c("lightningDays", "lightningDensity", "positiveCG", "positiveCGdensity").
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.
If prepInputs() expects a function for fun, prefer:
fun = function(...) rld(targetFile, to = sim$rasterToMatch)
instead of calling rld(...) immediately.
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.
reproducible::prepInputs(), reproducible::Cache(), terra::aggregate()
## Not run: out <- prepare_LightningData( rtm = sim$rasterToMatch, igAggFactor = P(sim)$igAggFactor, rld = readLightningData ) out$lightningDensity ## End(Not run)## Not run: out <- prepare_LightningData( rtm = sim$rasterToMatch, igAggFactor = P(sim)$igAggFactor, rld = readLightningData ) out$lightningDensity ## End(Not run)
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.
prepareCovariatesOuter(unscaledData, algorithm, rescaleVars, useCache = TRUE)prepareCovariatesOuter(unscaledData, algorithm, rescaleVars, useCache = TRUE)
unscaledData |
A |
algorithm |
|
rescaleVars |
|
useCache |
|
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()).
A list with elements:
A data.table with rescaled/standardized covariates.
NULL (the non-xgboost formula path is disabled).
Named numeric vector of per-variable 10-based
rescalers (non-xgboost path) or NULL for xgboost / no-rescale.
Character vector indicating which year-like column(s) were found.
The digest used for caching, or NULL if useCache = FALSE.
rescaleCovariates(), reproducible::Cache()
## 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)## 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)
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.
putBackIntoRaster(lcc, landcoverDT, flammableMap)putBackIntoRaster(lcc, landcoverDT, flammableMap)
lcc |
character vector.
Names of the land cover class columns in |
landcoverDT |
data.table.
A
|
flammableMap |
SpatRaster.
A |
This function:
Creates a working copy of the template raster's values (initialized to 0
on all non-NA cells and keeping original NAs).
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.
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.
A multi-layer terra::SpatRaster where each layer corresponds to one entry
in lcc, with layer names set to lcc.
terra::rast(), terra::values(), terra::setValues()
## 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)## 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)
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.
pw(variable, knot)pw(variable, knot)
variable |
Numeric vector of covariate values. |
knot |
Numeric scalar threshold (knot) below which the term is |
Numeric vector the same length as variable, with each element
equal to max(variable[i] - knot, 0).
lapply with bufferForFireRaster.
Years are iteratively processed by makeFireID.this is a wrapper to simplify caching of lapply with bufferForFireRaster.
Years are iteratively processed by makeFireID.
rasterFireBufferDT( years, fireRaster, flammableRTM, bufferForFireRaster, areaMultiplier, minSize = 5000, verb = 1, cores = 1 )rasterFireBufferDT( years, fireRaster, flammableRTM, bufferForFireRaster, areaMultiplier, minSize = 5000, verb = 1, cores = 1 )
years |
numeric fire years |
fireRaster |
a |
flammableRTM |
a |
bufferForFireRaster |
buffer size used to group discrete patches of burned pixels as belonging to the same fire |
areaMultiplier |
A scalar that will buffer |
minSize |
The absolute minimum size of the buffer & non-buffer together.
This will be imposed after |
verb |
Logical or numeric related to how much verbosity is printed.
|
cores |
number of processor cores to use |
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
rasterFireSpreadPoints(fireBufferDT, flammableRTM)rasterFireSpreadPoints(fireBufferDT, flammableRTM)
fireBufferDT |
a |
flammableRTM |
@template flammableRTM |
a list of sf point objects
Generate random beta variates between 2 values and a mean
rbetaBetween(n, l, u, m, shape1, shape2 = NULL)rbetaBetween(n, l, u, m, shape1, shape2 = NULL)
n |
number of observations. If |
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 |
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.
readLightningData(filename, ...)readLightningData(filename, ...)
filename |
The local filename to read with |
... |
Passed to |
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).
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
## 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)## 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)
fireBufferedListDT that are outside flammableRTM
Remove buffered fires in fireBufferedListDT that are outside flammableRTM
removeBufferedFiresOutsideRTM(fireBufferedDT, flammableRTM)removeBufferedFiresOutsideRTM(fireBufferedDT, flammableRTM)
fireBufferedDT |
data.table containing indices for buffered annual fires |
flammableRTM |
a |
fireBufferedDT excluding fires with indices (burned or unburned) outside flammableRTM
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.
rescaleCovariates(formula, covariates, rescaleVars, modelAlgorithm)rescaleCovariates(formula, covariates, rescaleVars, modelAlgorithm)
formula |
A model formula or |
covariates |
A |
rescaleVars |
|
modelAlgorithm |
|
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).
A list with elements:
A data.table after rescaling/standardization.
The input formula (often NULL in current usage).
Named numeric vector of per-variable rescalers (non-xgb) or NULL.
Character vector with detected year-like column(s) or (bug) rows.
## 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)## 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
rescaleKnown2(x, minNew, maxNew, minOrig, maxOrig)rescaleKnown2(x, minNew, maxNew, minOrig, maxOrig)
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 |
the rescaled vector
data.table according to a named vector of rescalersRescale a data.table according to a named vector of rescalers
rescaleVarsByMagnitude(dt, rescalers)rescaleVarsByMagnitude(dt, rescalers)
dt |
a |
rescalers |
a named vector of rescalers |
the data.table with rescaled values
DEoptim
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.
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)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)
landscape |
A |
annualDTx1000 |
A list of data.table objects. Each list element will be from 1
year, and it must be the same length as |
nonAnnualDTx1000 |
A list of data.table objects. Each list element must be named
with a concatenated sequence of names from |
fireBufferedListDT |
A list of data.table objects. It must be same length as
|
historicalFires |
A named list of |
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 |
NP |
Optional. The number of population members (individuals) in DEoptim::DEoptim.
If |
trace |
Integer or Logical. Controls the level of tracing information printed by DEoptim::DEoptim during optimization. Passed to DEoptim::DEoptim.control. |
strategy |
Integer |
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 |
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
|
doObjFunAssertions |
logical indicating whether to do assertions. |
iterStep |
Integer. Must be less than |
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,. |
formulaToFit |
Passed to DEoptim::DEoptim |
objFunCoresInternal |
Integer. The number of cores to use for potential
parallelization within a single call to the objective function ( |
covMinMax, tests, maxFireSpread, Nreps, .verbose
|
Passed to |
thresh |
The threshold for accepting fits; e.g., from |
.c |
Numeric scalar in |
visualizeDEoptim |
Logical. If |
.plots |
Character string. Specifies the plot destination device (e.g., "screen", "png", "pdf").
Passed to internal plotting functions (likely via |
.plotSize |
List specifying plot |
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
|
control |
passed to DEoptim::DEoptim.control |
figPath |
directory where figures will be saved, if relevant |
cachePath |
A |
fireSense_spreadFormula |
The formula to be submitted to |
numParams |
The number of parameters (TODO: improve description) |
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.
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.
runELFs( preRunSetupProject, whatOut = c("fittedNamesOnly", "allNames", "maps"), urlELFresults = paste0("https://drive.google.com/file/d/", "1tkC944mPzR9-y-qCMDB5o2cAR_1MoDz4/view?usp=drive_link") )runELFs( preRunSetupProject, whatOut = c("fittedNamesOnly", "allNames", "maps"), urlELFresults = paste0("https://drive.google.com/file/d/", "1tkC944mPzR9-y-qCMDB5o2cAR_1MoDz4/view?usp=drive_link") )
preRunSetupProject |
list. A SpaDES project object prepared for
|
whatOut |
string. One of |
urlELFresults |
A googledrive url where the ELF data.frame that contains geometries and fitted SpreadFit parameters and several other attributes. |
The function:
Restricts preRunSetupProject$modules to entries matching "ELFs".
Collects all .R source files under each module directory (recursively),
excluding any under tests/, and uses these as part of the cache key.
Retrieves remote metadata (hash) from a Google Drive file URL and assigns
the remote hash to preRunSetupProject$params$fireSense_ELFs$hashSpreadFitRemoteFile.
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.
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).
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.
A vector corresponding to sim$spreadFitPreRun[[fireSenseUtils::polygonIDTxt]].
Currently, no high arctic
ELFs are returned (e.g., Ecoprovinces starting with either 1. or 2.)
Updates a Google Drive file when the current user is "emcintir" and when
the run produces outputs with names containing "ELF".
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.
Based on the provided code snippet.
simInitAndSpades2,
Cache,
drive_update
## Not run: # Assuming 'prj' is a valid SpaDES project list: # prj <- somePreparationFunction(...) ids <- runELFs(prj) ## End(Not run)## Not run: # Assuming 'prj' is a valid SpaDES project list: # prj <- somePreparationFunction(...) ids <- runELFs(prj) ## End(Not run)
x1000 integer to usable by spreadConvert covariates from their x1000 integer to usable by spread
spreadProbFromIntegerCovs( shortAnnDTx1000 = NULL, annDTx1000, nonAnnualDTx1000, indexNonAnnual, yr, covMinMax = NULL, mutuallyExclusive, colsToUse, doAssertions, logisticPars, covPars, maxFireSpread, lowerSpreadProb )spreadProbFromIntegerCovs( shortAnnDTx1000 = NULL, annDTx1000, nonAnnualDTx1000, indexNonAnnual, yr, covMinMax = NULL, mutuallyExclusive, colsToUse, doAssertions, logisticPars, covPars, maxFireSpread, lowerSpreadProb )
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 |
nonAnnualDTx1000 |
If |
indexNonAnnual |
|
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 |
covMinMax |
A data.table, one column for each column in |
mutuallyExclusive |
If there are any covariates, e.g,. |
colsToUse |
Optional. If this is supplied, it must be a character vector indicating
the column names to use in |
doAssertions |
Logical. If |
logisticPars |
Numeric vector of logistic parameters; its length
selects which variant |
covPars |
Numeric vector of covariate coefficients (same length as
|
maxFireSpread |
A value for |
lowerSpreadProb |
Numeric. Lower bound for |
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
stackAndExtract(years, fuel, LCC, climate, fires = NULL)stackAndExtract(years, fuel, LCC, climate, fires = NULL)
years |
character vector of fire years with FS notation e.g. |
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 |
fires |
list of spatial points representing annual ignitions |
a data.frame with cell numbers, ignitions, and covariates for each year
This simply converts to integers times 1000 so that the values can be saved more quickly to disk, for example.
toX1000(lst, omitCols = "pixelID")toX1000(lst, omitCols = "pixelID")
lst |
a data.frame of (at least some) numeric columns |
omitCols |
character A vector of column names to not convert |
The same data.frame, but with columns converted to integer and times 1000
Update name of layers in a climate raster stack
updateStackYearNames(annualDataStack, desiredYears)updateStackYearNames(annualDataStack, desiredYears)
annualDataStack |
|
desiredYears |
character |
DEoptim object pars
Make histograms of DEoptim object pars
visualizeDE(DE, cachePath, titles, lower, upper)visualizeDE(DE, cachePath, titles, lower, upper)
DE |
An object from a DEoptim::DEoptim call |
cachePath |
A |
titles |
titles of plots |
lower |
lower limit on x axis |
upper |
upper limit on x axis |