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] , Alex M Chubaty [aut] , Ian Eddy [aut] |
Maintainer: | Eliot J B McIntire <[email protected]> |
License: | GPL-3 |
Version: | 0.0.5.9078 |
Built: | 2024-12-20 23:23:55 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
Objective function when no piecewise model is used
.objFunIgnition(params, linkinv, nll, sm, nx, mm, mod_env, offset)
.objFunIgnition(params, linkinv, nll, sm, nx, mm, mod_env, offset)
params |
DESCRIPTION NEEDED |
linkinv |
the link function |
nll |
the log-likelihood function |
sm |
scaling matrix |
nx |
number of covariates |
mm |
model matrix containing data |
mod_env |
the environment containing params - can be a data.frame |
offset |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
Function to pass to the optimizer - Piece-wise version
.objFunIgnitionPW( params, formula, linkinv, nll, sm, updateKnotExpr, nx, mod_env, offset )
.objFunIgnitionPW( params, formula, linkinv, nll, sm, updateKnotExpr, nx, mod_env, offset )
params |
DESCRIPTION NEEDED |
formula |
DESCRIPTION NEEDED |
linkinv |
DESCRIPTION NEEDED |
nll |
DESCRIPTION NEEDED |
sm |
DESCRIPTION NEEDED |
updateKnotExpr |
DESCRIPTION NEEDED |
nx |
DESCRIPTION NEEDED |
mod_env |
the environment containing params - can be a data.frame |
offset |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
fireSense_spreadFit
moduleObjective function for fireSense_spreadFit
module
.objfunSpreadFit( par, landscape, annualDTx1000, nonAnnualDTx1000, FS_formula, historicalFires, fireBufferedListDT, covMinMax = NULL, maxFireSpread = 0.28, 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 = TRUE )
.objfunSpreadFit( par, landscape, annualDTx1000, nonAnnualDTx1000, FS_formula, historicalFires, fireBufferedListDT, covMinMax = NULL, maxFireSpread = 0.28, 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 = TRUE )
par |
parameters |
landscape |
A SpatRaster with extent, res, proj used for SpaDES.tools::spread2 |
annualDTx1000 |
A list of data.table class objects. Each list element is data from a single calendar year, and whose name is "yearxxxx" where xxxx is the 4 number year. The columns in the data.table must integers, that are 1000x their actual values as this function will divide by 1000. |
nonAnnualDTx1000 |
Like |
FS_formula |
Formula, put provided as a character string, not class |
historicalFires |
DESCRIPTION NEEDED |
fireBufferedListDT |
DESCRIPTION NEEDED |
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 |
minFireSize |
DESCRIPTION NEEDED |
tests |
One or more of |
Nreps |
Integer. The number of replicates, per ignition, to run. |
mutuallyExclusive |
If there are any covariates, e.g,. youngAge, that should be
considered mutually exclusive, i.e., "if youngAge is non-zero, should vegPC2 be set to zero", then
this can be done here. A named list, where the name of the list element must be a single
covariate column name in either |
doAssertions |
Logical. If |
plot.it |
Passed to |
objFunCoresInternal |
Internally, this function can use |
lanscape1stQuantileThresh |
A |
thresh |
Threshold multiplier used in SNLL fire size (SNLL_FS) test. Default 550.
Lowering the threshold value will be more restrictive, but being too restrictive will result
in |
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 |
DESCRIPTION NEEDED |
Attempting a weighted likelihood, https://stats.stackexchange.com/questions/267464/algorithms-for-weighted-maximum-likelihood-parameter-estimation. With log(fireSize) * likelihood for each fire.
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
library(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)
library(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)
buffer ignition points to create non-ignitions for model
bufferIgnitionPoints(ignitionPoints, rtm, bufferSize)
bufferIgnitionPoints(ignitionPoints, rtm, bufferSize)
ignitionPoints |
SpatialPolygonsDataFrame with year of ignition |
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.table
s 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 |
@template flammableRTM |
verb |
Logical or numeric related to how much verbosity is printed. |
a data.table with fire ID, buffer status, and pixelID
Modify 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 firePolys. Closed interval |
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 here: https://www.datanovia.com/en/blog/types-of-clustering-methods-overview-and-quick-start-r-code/ and here: https://www.datanovia.com/en/lessons/model-based-clustering-essentials/, with citation here: 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
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
## Not run: ################################# # Use own data; here is a generated set for reprex library("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"]]) ## End(Not run)
## Not run: ################################# # Use own data; here is a generated set for reprex library("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"]]) ## 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 pixelID |
standAgeMap |
template |
fireBufferedListDT |
data.table containing non-annual burn and buffer pixelIDs |
cutoffForYoungAge |
Numeric. Default is 15. This is the age below which the pixel is considered
"young" –> |
a raster layer with unified standAge 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
Data checks and assertions for spreadFitRun
chk_duplicatedStartPixels(cells, size) .doDataChecks(moduleName, envir, attribs, fml)
chk_duplicatedStartPixels(cells, size) .doDataChecks(moduleName, envir, attribs, fml)
cells |
DESCRIPTION NEEDED |
size |
DESCRIPTION NEEDED |
moduleName |
DESCRIPTION NEEDED |
envir |
DESCRIPTION NEEDED |
attribs |
DESCRIPTION NEEDED |
fml |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
DESCRIPTION NEEDED
Map
Ensure fire points are located on flammable pixels inside a fire polygon
Intended to be run using Map
cleanUpSpreadFirePoints(firePoints, bufferDT, flammableRTM)
cleanUpSpreadFirePoints(firePoints, bufferDT, flammableRTM)
firePoints |
a |
bufferDT |
a data.table of burned cells, output from |
flammableRTM |
a |
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" )
cohortsToFuelClasses( cohortData, pixelGroupMap, flammableRTM, landcoverDT = NULL, sppEquiv, sppEquivCol, cutoffForYoungAge, fuelClassCol = "FuelClass" )
cohortData |
A |
pixelGroupMap |
A |
flammableRTM |
a |
landcoverDT |
Optional table of nonforest landcovers 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 |
a SpatRaster
of biomass by fuel class as determined by fuelClassCol
and cohortData
Download and prepare fire data from National Fire Database
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 |
an optional raster of flammable pixels to subset data |
Ylimits |
the upper and lower MDC range for the plot |
firstHistoricalYear |
the earliest year of historical data |
firstProjectedYear |
the earliest year of projected data |
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)
NA
s in a data.table
with zerosReplace NA
s in a data.table
with zeros
dtReplaceNAwith0(DT, colsToUse = NULL)
dtReplaceNAwith0(DT, colsToUse = NULL)
DT |
DESCRIPTION NEEDED |
colsToUse |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
Extract the elements of the special terms, i.e. the variable and the knot value
extractSpecial(v, k)
extractSpecial(v, k)
v |
DESCRIPTION NEEDED |
k |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
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, plot = FALSE )
getFirePoints_NFDB_V2( url = NULL, studyArea = NULL, redownloadIn = 1, years = 1991:2017, fireSizeColName = "SIZE_HA", NFDB_pointPath = NULL, 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 |
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(years, useInnerCache = FALSE, ...)
getFirePolygons(years, useInnerCache = FALSE, ...)
years |
years to filter fire polygons by |
useInnerCache |
logical indicating whether to cache the |
... |
additional arguments passed to |
list of fire polygons by year
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 |
ensure buffered fires are entirely in studyArea
ensure every fire has a corresponding ignition point, and vice versa
ensure these points are flammable
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 pointsIDcolumn |
flammableRTM |
a |
spreadFirePoints |
the ignition points corresponding to |
areaMultiplier |
Either a scalar that will buffer |
minSize |
an alternative to areaMultiplier, typically used when fires are small |
pointsIDcolumn |
the name of the column denoting fire ids in both spreadFirePoints and firePolys |
Four- and five-parameter logistic functions
logistic4p(x, par) logistic5p(x, par) logistic3p(x, par, par1 = 0.1) logistic2p(x, par, par1 = 0.1, par4 = 0.5)
logistic4p(x, par) logistic5p(x, par) logistic3p(x, par, par1 = 0.1) logistic2p(x, par, par1 = 0.1, par4 = 0.5)
x |
DESCRIPTION NEEDED |
par |
DESCRIPTION NEEDED |
par1 |
DESCRIPTION NEEDED |
par4 |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
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
Create landcoverDT object to classify and track non-forest lcc
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" )
makeLociList( ras, pts, idsCol = "FIRE_ID", dateCol = "YEAR", sizeCol = "POLY_HA", sizeColUnits = "ha" )
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 |
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 |
fuelClass from |
cohortData |
A |
flammableRTM |
a |
pixelGroupMap |
A |
a SpatRaster with values equal to class
biomass (B)
preparing a time since disturbance map from stand age and fire data
makeTSD( year, firePolys = NULL, fireRaster = NULL, standAgeMap, lcc, cutoffForYoungAge = 15 )
makeTSD( year, firePolys = NULL, fireRaster = NULL, standAgeMap, lcc, cutoffForYoungAge = 15 )
year |
the year represented by |
firePolys |
list of |
fireRaster |
a |
standAgeMap |
initial stand age map |
lcc |
|
cutoffForYoungAge |
Numeric. Default is 15. This is the age below which the pixel is considered
"young" –> |
a SpatRaster
with values representing time since disturbance
DESCRIPTION NEEDED
multiplier(size, minSize = 1000, baseMultiplier = 5)
multiplier(size, minSize = 1000, baseMultiplier = 5)
size |
DESCRIPTION NEEDED |
minSize |
DESCRIPTION NEEDED |
baseMultiplier |
DESCRIPTION NEEDED |
objNlminb
Wrapper around stats::nlminb
objNlminb(x, objective, lower, upper, control, hvPW, ...)
objNlminb(x, objective, lower, upper, control, hvPW, ...)
x |
DESCRIPTION NEEDED |
objective |
objective function |
lower |
lower bounds on coefficients |
upper |
upper bounds on coefficients |
control |
DESCRIPTION NEEDED |
hvPW |
logical indicating whether the formula is piece-wise #IE added |
... |
additional arguments passed to objective function |
DESCRIPTION NEEDED
Order of Magnitude
oom(x)
oom(x)
x |
a numeric |
the order of magnitude
Create plot with subplots showing: a) area burned; b) number of fires; c) mean fire size.
plotBurnSummary(studyAreaName, climateScenario, outputDir, Nreps)
plotBurnSummary(studyAreaName, climateScenario, outputDir, Nreps)
studyAreaName |
character string giving the study area name |
climateScenario |
character string specifying the name of a CIMP6 climate scenario,
including SSP, formatted as in |
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: |
list of file names corresponding to the figures and/or objects written to disk
Plot cumulative burn maps
plotCumulativeBurns( studyAreaName, climateScenario, outputDir, Nreps, rasterToMatch )
plotCumulativeBurns( studyAreaName, climateScenario, outputDir, Nreps, rasterToMatch )
studyAreaName |
character string giving the study area name |
climateScenario |
character string specifying the name of a CIMP6 climate scenario,
including SSP, formatted as in |
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: |
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, firePolys, ignitionPoints )
plotHistoricFires( climateScenario, studyAreaName, outputDir, 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. |
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 ingition data - must have a predict method |
data |
data for prediction |
rescaleFactor |
spatial rescaling factor when predicted and fitted data are at different scales. Calculated as: (predResolution/fitResolution)^2 |
lambdaRescaleFactor |
If the data for fitting has been sampled for pseudo-absences, this imposes a new baseline probability of fire occurrences, hence predictions need to be adjusted. If the original fire prob. is (total no. fires)/(total no. fires + total no. absences), and the fire probability imposed by sampling is (total no. fires)/(total no. fires + no. sampled pseudo-absences), to adjust predicted values, one needs to multiply them by (total no. fires + no. sampled pseudo-absences/(total no. fires + total no. absences) |
vector of predicted values.
Handling piecewise terms in a formula
pw(variable, knot)
pw(variable, knot)
variable |
DESCRIPTION NEEDED |
knot |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
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.table
s 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 |
stats::rbeta
remove buffered fires in fireBufferedListDT that are outside RTM
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
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
DEoptim
callDoes the multiple cluster connections. This will only work if ssh keys are correctly made between machines (if using multiple machines).
runDEoptim( landscape, annualDTx1000, nonAnnualDTx1000, fireBufferedListDT, historicalFires, itermax, initialpop = NULL, NP = NULL, trace, strategy, cores = NULL, 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), cachePath, iterStep = 25, lower, upper, mutuallyExclusive, FS_formula, objFunCoresInternal, covMinMax = covMinMax, tests = c("SNLL", "adTest"), maxFireSpread, Nreps, thresh = 550, .verbose, visualizeDEoptim, .plotSize = list(height = 1600, width = 2000) ) DEoptimIterative( itermax, lower, upper, control, FS_formula, covMinMax, tests = c("SNLL", "adTest"), objFunCoresInternal, maxFireSpread, Nreps, visualizeDEoptim, cachePath, mutuallyExclusive, doObjFunAssertions = getOption("fireSenseUtils.assertions", TRUE), iterStep = 25, thresh = 550, .verbose, .plotSize = list(height = 1600, width = 2000) )
runDEoptim( landscape, annualDTx1000, nonAnnualDTx1000, fireBufferedListDT, historicalFires, itermax, initialpop = NULL, NP = NULL, trace, strategy, cores = NULL, 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), cachePath, iterStep = 25, lower, upper, mutuallyExclusive, FS_formula, objFunCoresInternal, covMinMax = covMinMax, tests = c("SNLL", "adTest"), maxFireSpread, Nreps, thresh = 550, .verbose, visualizeDEoptim, .plotSize = list(height = 1600, width = 2000) ) DEoptimIterative( itermax, lower, upper, control, FS_formula, covMinMax, tests = c("SNLL", "adTest"), objFunCoresInternal, maxFireSpread, Nreps, visualizeDEoptim, cachePath, mutuallyExclusive, doObjFunAssertions = getOption("fireSenseUtils.assertions", TRUE), iterStep = 25, thresh = 550, .verbose, .plotSize = list(height = 1600, width = 2000) )
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 |
DESCRIPTION NEEDED |
itermax |
Passed to |
initialpop |
DESCRIPTION NEEDED |
NP |
DESCRIPTION NEEDED |
trace |
Passed to |
strategy |
Passed to |
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. |
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. |
cachePath |
The |
iterStep |
Integer. Must be less than |
lower |
Passed to |
upper |
Passed to |
mutuallyExclusive |
If there are any covariates, e.g,. youngAge, that should be
considered mutually exclusive, i.e., "if youngAge is non-zero, should vegPC2 be set to zero", then
this can be done here. A named list, where the name of the list element must be a single
covariate column name in either |
FS_formula |
Passed to |
objFunCoresInternal |
DESCRIPTION NEEDED |
covMinMax |
Passed to |
tests |
Passed to |
maxFireSpread |
Passed to |
Nreps |
Passed to |
thresh |
Threshold multiplier used in SNLL fire size (SNLL_FS) test. Default 550. |
.verbose |
Passed to |
visualizeDEoptim |
Logical. If |
.plotSize |
List specifying plot |
control |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
prepare covariate table with ignition year, fuel class, climate value, and land cover
stackAndExtract(years, fuel, LCC, climate, fires)
stackAndExtract(years, fuel, LCC, climate, fires)
years |
character vector of fire years with FS notation e.g. year2002 |
fuel |
raster brick of aggregated fuel classes |
LCC |
raster brick of aggregated LCC classes |
climate |
list of raster layers named by climate variable
with raster layer names matching |
fires |
list of spatial points representing annual ignitions |
a data.frame with cell numbers, ignitions, and covariates for each year
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)
visualizeDE(DE, cachePath)
DE |
An object from a |
cachePath |
A |