Package 'LandWebUtils'

Title: Helper functions for the LandWeb project
Description: Additional utilities for LandWeb analyses.
Authors: Eliot J B McIntire [aut] (ORCID: <https://orcid.org/0000-0002-6914-8316>), Alex M Chubaty [aut, cre] (ORCID: <https://orcid.org/0000-0001-7146-8135>), His Majesty the Queen in Right of Canada, as represented by the Minister of Natural Resources Canada [cph]
Maintainer: Alex M Chubaty <[email protected]>
License: GPL-3
Version: 1.0.3.9010
Built: 2026-06-02 23:46:49 UTC
Source: https://github.com/PredictiveEcology/LandWebUtils

Help Index


Clean up the LandWeb LTHFCs

Description

Clean up the LandWeb LTHFCs

Usage

.cleanLandWebStudyArea(poly, minFRI = 40)

Arguments

poly

A polygon or character string identifying the path to polygon

minFRI

Numeric or integer, indicating the minimum fire return interval that will be part of the cleanup of polygon. Anything below this will be NA.


Simulation timesteps for analyses

Description

Simulation timesteps for analyses

Usage

analysesOutputsTimes(period, interval)

Arguments

period

numeric vector of length 2 corresponding to the start and end times to use for analyses.

interval

numeric indicating the interval between timesteps for analyses

Value

numeric vector of timesteps for which to run analyses


CASFRItoSpRasts

Description

TODO: description and title needed

Usage

CASFRItoSpRasts(
  CASFRIRas,
  CASFRIattrLong,
  CASFRIdt,
  sppEquiv,
  sppEquivCol,
  destinationPath
)

Arguments

CASFRIRas

TODO: description needed

CASFRIattrLong

TODO: description needed

CASFRIdt

TODO: description needed

sppEquiv

table with species name equivalencies between the kNN and final naming formats. See data("sppEquivalencies_CA", "LandR"). For functions that have mixedType e.g., vegTypeMapGenerator, this only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use data("sppEquivalencies_CA", "LandR").

sppEquivCol

the column name to use from sppEquiv. For functions that have mixedType e.g., vegTypeMapGenerator, Only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use "Boreal".

destinationPath

path to data directory where objects will be downloaded or saved to

Value

TODO: description needed


Extract study area name from run name

Description

Extract study area name from run name

Usage

cleanAreaName(area)

Arguments

area

Simulated area (i.e., run) name


Extract boundary polygon(s) for LandWeb forest management area(s)

Description

Extract boundary polygon(s) for LandWeb forest management area(s)

Usage

extractFMA(fmas, name)

Arguments

fmas

sf object with LandWeb FMA boundaries

name

A character (regex) string to match.

Value

sf polygons object


Extract boundary polygon(s) for Alberta forest management unit(s)

Description

Extract boundary polygon(s) for Alberta forest management unit(s)

Usage

extractFMU(fmus, name)

Arguments

fmus

sf object with Alberta FMU boundaries

name

A character (regex) string to match.

Value

sf polygons object


Find LandWeb simulation output files

Description

Find LandWeb simulation output files

Usage

findSimFile(outputDir = NULL, rep = NULL)

findOldSimFiles(outputDir = NULL, rep = NULL, before = "2024-01-01")

Arguments

outputDir

path to LandWeb output directory.

rep

integer giving the replicate id, or character string in the form of "rep01".

before

date before which files are considered outdated (default "2024-01-01").

Value

path to the file

Examples

## Not run: 
  outDir <- file.path("~/GitHub/LandWeb/outputs/Tolko_AB_S_aspenDispersal_logROS")
  if (dir.exists(outdir)) {
    oldFiles <- findOldSimFiles(outDir)      ## search all reps
    oldFiles <- findOldSimFiles(outDir, 1:5) ## search specific reps
    # fs::file_delete(oldFiles) ## double check before deleting
  }

## End(Not run)

Join reporting polygons and intersect their features

Description

Join two reporting polygons, preserving their features; concatenate the ⁠Name.*⁠ fields into a single Name field. E.g., if x and y each contain 2 features, the resulting object will contain 4 features (corresponding to x1.y1, x1.y2, x2.y1, and x2.y2).

Usage

joinReportingPolygons(x, y)

Arguments

x, y

a sf

Value

an sf polygons object


Core Burn function for Andison's LandMine Fire Module

Description

The main function for the Andison Fire Module. See details.

Usage

landmine_burn1(
  landscape,
  startCells,
  fireSizes = 5,
  nActiveCells1 = c(10, 36),
  spawnNewActive = c(0.46, 0.2, 0.26, 0.11),
  maxRetriesPerID = 10L,
  sizeCutoffs = c(8000, 20000),
  spreadProbRel = NA_real_,
  spreadProb = 0.77,
  omitPixels = NULL
)

landmine_burn(
  landscape,
  startCells,
  fireSizes = 5,
  nActiveCells1 = c(10, 36),
  spawnNewActive = c(0.46, 0.2, 0.26, 0.11),
  sizeCutoffs = c(8000, 20000),
  spreadProbRel = 0.23
)

Arguments

landscape

A SpatRaster. This only provides the extent and resolution for the fire spread algorithm.

startCells

A numeric vector indicating the indices on the landscape where the fires will start with 100%% certainty.

fireSizes

A numeric vector indicating the final size of each of the fires. Must be same length as startCells.

nActiveCells1

A numeric vector of length 2. These are cutoffs above and below each of which different values of spawnNewActive are used. See details.

spawnNewActive

A numeric vector of length 4. These are the probabilities of creating spreading to 2 neighbours instead of the 1 default neighbour, each time step. The 4 values are for 4 different fire size conditions. See details.

maxRetriesPerID

Integer. Maximum number of retry attempts per firelet ID.

sizeCutoffs

A numeric vector of length 2. These are 2 size (in hectares) thresholds that affect which spawnNewActive probabilities are used. See details.

spreadProbRel

A raster layer of of relative probabilities, with non-flammable pixels NA.

spreadProb

A raster layer of spread probabilities, with non-flammable pixels NA.

omitPixels

An optional vector of pixel IDs to omit from fire size calculations. Can be used if spreadProb or spreadProbRel do not designate non-flammable pixels as NA, to allow fires to move through these pixels, while excluding these pixels from burn area calculations. Useful in study areas with discontinuous fuels, which would otherwise result in fires getting 'stuck' too often, and not reach their target size.

Details

This algorithm is a modified contagious cellular automaton.

Value

A data.table with 4 columns (initialPixels, pixels, state, order).

Algorithm

Core

Each fire starts at a single pixel, startCells and will spread, i.e., visit and convert from a 0 to the fire id number. It will iteratively spread until the number of cells visited is equal to floor(fireSizes).

Adjustments due to current fire size and number of active pixels

That can vary too, but it gets a bit complicated, so use that for now. Spawning probability was originally set at 13%, but created problems with very large and very small fires, so over time has been adjusted to vary depending on: a) number of active "firelets" (NF); and b) fire size (FS), such that:

  - If 10 <= NF < 36 and FS < 20,000 ha then P = 20%;
  - If NF > 36 and FS < 8,000 ha, P = 11%;
  - If NF < 36 and FS > 20,000 ha, P = 26%;
  - If NF < 10 then P = 46%;

These rule create more heterogeneity in the pattern of burning.

Fire jumping

If the fire has not reached its target size, it will try to pick new neighbours among the 8 immediate neighbours up to 4 times. If it still did not find enough neighbours, then it will jump or "spot" up to 4 pixels away. It will then repeat the previous 2 stages again once (i.e., 4 neighbours, 1 jump, repeat), then it will stop, unable to achieve the desired fireSize.

Note

The original version (landmine_burn()) is deprecated and should not be used. Use landmine_burn1() instead.


LandMine burn optimization function

Description

LandMine burn optimization function

Usage

landmine_optim_burnFun(
  ros,
  centreCell,
  fireSize,
  spawnNewActive,
  sizeCutoffs,
  spreadProb
)

Arguments

ros

SpatRaster of LandMine Rate Of Spread values.

centreCell

See startCells in landmine_burn1().

fireSize

See fireSizes in landmine_burn1().

spawnNewActive

A numeric vector of length 4. These are the probabilities of creating spreading to 2 neighbours instead of the 1 default neighbour, each time step. The 4 values are for 4 different fire size conditions. See details.

sizeCutoffs

A numeric vector of length 2. These are 2 size (in hectares) thresholds that affect which spawnNewActive probabilities are used. See details.

spreadProb

A raster layer of spread probabilities, with non-flammable pixels NA.

Value

named list of length 2 containing:

  • burnedMap: SpatRaster of burned pixels;

  • LM: data.frame of patch statistics from landscapemetrics.


Export objects used for optimization and load packages on cluster

Description

Export objects used for optimization and load packages on cluster

Usage

landmine_optim_clusterExport(cl = NULL, objs = NULL, pkgs = NULL)

Arguments

cl

a cluster object or NULL

objs

character vector of names of objects to export

pkgs

character vector of packages to pre-load on the cluster nodes

Value

NULL. Invoked for its side effects.


Setup a cluster for LandMine optimization

Description

Setup a cluster for LandMine optimization

Usage

landmine_optim_clusterSetup(nodes = NULL)

Arguments

nodes

positive integer of length 1 specifying the number of threads to use on the current machine (localhost), or a character vector of hostnames on which to run worker copies.

Value

a cluster object


Wrapper function to setup cluster, export objects and load packages

Description

Wrapper function to setup cluster, export objects and load packages

Usage

landmine_optim_clusterWrap(cl = NULL, nodes, reps, objs, pkgs)

Arguments

cl

a cluster object or NULL

nodes

positive integer of length 1 specifying the number of threads to use on the current machine (localhost), or a character vector of hostnames on which to run worker copies.

reps

integer. number of replicates to run.

objs

character vector of names of objects to export

pkgs

character vector of packages to pre-load on the cluster nodes

Value

named list of length 2 containing: cl, a cluster object; out, a list of burn maps (aka burnMapList).


LandMine objective functions

Description

landmine_fitSN() is used for the module.

Usage

landmine_optim_fitSN(
  sna,
  ros,
  centreCell,
  fireSizes = 10^(2:5),
  desiredPerimeterArea = 0.004
)

landmine_optim_fitSN2(
  par,
  ros,
  centreCell,
  fireSizes = 10^(2:5),
  desiredPerimeterArea = 0.003,
  spreadProb = 0.9
)

Arguments

sna

(i.e., spawnNewActive) A numeric vector of length 4. These are the probabilities of creating spreading to 2 neighbours instead of the 1 default neighbour, each time step. The 4 values are for 4 different fire size conditions. See details in landmine_optim_burnFun().

ros

Character, specifying the file path to raster of LandMine Rate Of Spread values.

centreCell

Integer id of the centre (start) cell of ros raster. See startCells in landmine_burn1().

fireSizes

A numeric vector indicating the final size of each of the fires. See landmine_burn1().

desiredPerimeterArea

Numeric target perimeter-area ratio.

par

parameter vector of length 5

spreadProb

spread probability

Details

landmine_fitSN2() is an alternative version tries the optimization using fewer parameters, to test whether a simpler version gets better/different results. Although this version was not used for the final module, we preserve it here for posterity.

Value

Summary data.table of fit results.

See Also

landmine_burn1(), landmine_optim_burnFun()


LandMine diagnostic plots

Description

  • landmine_plot_areaBurnedOverTime() plots the area burned over time by LTHFC polygon;

  • landmine_plot_LTHFC() produces a rasterVis::levelplot() a map of the LTHFC polygons;

  • landmine_plot_FRI() plots

Usage

landmine_plot_areaBurnedOverTime(areaBurnedOverTime)

landmine_plot_LTHFC(lthfc, studyAreaName, ...)

landmine_plot_FRI(friSummary)

Arguments

areaBurnedOverTime

Summary data.frame of area burned over time, containing the following columns: time (numeric) gives the simulation time (year); haBurned (numeric) gives the burned area in hectares; FRI (numeric) identifies the fire return interval polygon.

lthfc

long-term historic fire cycle map (raster).

studyAreaName

study area name (character).

...

additional arguments passed to rasterVis::levelplot().

friSummary

Summary data.frame of simulated fire return intervals (FRI) vs. the long-term historic fire cycles (LTHFC), containing the following columns: simArea (character) gives the study area name; LTHFC (numeric) is the expected (i.e., historic) FRI; FRI (numeric) is the simulated FRI.

Value

a ggplot2 or rasterVis object; invoked for side effect of creating plots.


Target CRS (projection) to use with LandWeb

Description

As of September 2025, this corresponds to the SCANFI's NAD_1983_Canada_Lambert projection.

Usage

LandWebCRS

Format

An object of class character of length 1.

Note

needs to be character, not CRS class, for downstream use with data.table


Study areas available for LandWeb simulations

Description

Study areas available for LandWeb simulations

Usage

LandWebStudyAreas

studyAreaProv(name)

studyAreaIn(name, prov)

Arguments

name

character specifying the study area name. Must be one of LandWebStudyAreas$Name.

prov

character specifying the province abbreviation (i.e., "AB", "BC", "MB", "NWT", or "SK").

Format

An object of class data.frame with 32 rows and 4 columns.

Value

LandWebStudyAreas is a data.frame' with 4 columns:

  • Name specifies the shortname of the study area for use with simulation setup;

  • Province identifies the location of the study area;

  • ID corresponds to the polygon ID of the Updated FMA Boundaries polygons;

  • Description provides the full study area name and additional context (if any);

studyAreaProv returns a character indicating the province the study area is in.

studyAreaIn returns a logical indicating whether study area name is in prov.


Calculate proportion of large patches in NRV

Description

TODO: needs description

Usage

LargePatches(
  tsf,
  vtm,
  poly,
  labelColumn,
  id,
  ageClassCutOffs,
  ageClasses,
  sppEquivCol,
  sppEquiv,
  crop2poly = FALSE
)

Arguments

tsf

A single filename, relative or absolute, pointing to a Time Since Fire raster. Can be any format that terra can use.

vtm

A single filename, relative or absolute, pointing to a Vegetation Type Map raster. Can be any format that terra can use.

poly

A single sf object or a factor SpatRaster. This layer MUST have a column labelled shinyLabel

labelColumn

TODO: description needed

id

TODO: description needed

ageClassCutOffs

A numeric vector with the endpoints for the ageClasses. Should be length(ageClasses) + 1. See .ageClassCutOffs.

ageClasses

A character vector with labels for age classes to bin the tsf times, e.g., c("Young", "Immature", "Mature", "Old"). See .ageClasses.

sppEquivCol

Character giving the column name to use in sppEquiv.

sppEquiv

Species equivalency table, e.g., derived from LandR::sppEquivalencies_CA.

crop2poly

logical indicating whether to crop/mask vtm and tsf rasters to poly. Default FALSE for backwards compatibility.


Calculate proportion of landscape occupied by each vegetation class

Description

This function is recursive. If poly is a SpatialPolygon, then the function will enter once, and convert this to a fasterized version, and pass that into the function replacing poly. It is also recursive of passed a vector of filenames for tsf and vtm.

Usage

LeadingVegTypeByAgeClass(
  tsf,
  vtm,
  poly,
  ageClassCutOffs,
  ageClasses,
  sppEquivCol,
  sppEquiv
)

Arguments

tsf

A single filename, relative or absolute, pointing to a Time Since Fire raster. Can be any format that terra can use.

vtm

A single filename, relative or absolute, pointing to a Vegetation Type Map raster. Can be any format that terra can use.

poly

A single sf object or a factor SpatRaster.

ageClassCutOffs

A numeric vector with the endpoints for the ageClasses. Should be length(ageClasses) + 1. See .ageClassCutOffs.

ageClasses

A character vector with labels for age classes to bin the tsf times, e.g., c("Young", "Immature", "Mature", "Old"). See .ageClasses.

sppEquivCol

Character giving the column name to use in sppEquiv.

sppEquiv

Species equivalency table, e.g., derived from LandR::sppEquivalencies_CA.

Value

A data.table with proportion of the pixels in each vegetation class, for each given age class within each polygon.


Load CASFRI data for LandWeb

Description

Using CASFRI v4 data prepared for LandWeb.

Usage

loadCASFRI(
  CASFRIRas,
  attrFile,
  headerFile,
  sppEquiv,
  sppEquivCol,
  type = c("cover", "age")
)

Arguments

CASFRIRas

TODO: description needed

attrFile

TODO: description needed

headerFile

TODO: description needed

sppEquiv

table with species name equivalencies between the kNN and final naming formats. See data("sppEquivalencies_CA", "LandR"). For functions that have mixedType e.g., vegTypeMapGenerator, this only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use data("sppEquivalencies_CA", "LandR").

sppEquivCol

the column name to use from sppEquiv. For functions that have mixedType e.g., vegTypeMapGenerator, Only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use "Boreal".

type

Character string. Either "cover" or "age".

Value

TODO: description needed


Calculate the mean of a truncated Pareto distribution

Description

Calculate the mean of a truncated Pareto distribution

Usage

meanTruncPareto(k, lower, upper, alpha)

Arguments

k

TODO: description needed

lower

TODO: description needed

upper

TODO: description needed

alpha

TODO: description needed

Value

TODO: description needed


Plot boundary polygon(s) for forest management areas

Description

Plot boundary polygon(s) for forest management areas

Usage

plotFMA(x, provs, caribou = NULL, xsr = NULL, title = NULL, png = NULL)

plotLandWeb(x, provs, caribou = NULL, xsr = NULL, title = NULL, png = NULL)

plotGG(x, provs, caribou = NULL, png = NULL, title = NULL)

Arguments

x

sf object corresponding to the FMA to be plotted

provs

sf object corresponding to the provincial (or territorial) boundaries to plot

caribou

Optional sf object corresponding to caribou boundaries

xsr

Optional sf object corresponding to a buffered studyArea

title

Character string to use for plot title

png

Optional. If non-NULL, must be a valid file path to write a png


Do an arbitrary set of operations on a polygon

Description

Do an arbitrary set of operations on a polygon

Usage

polygonClean(poly, fn = NULL, type = NULL, ...)

Arguments

poly

A polygon object, or a character string identifying the shapefile path to load, and clean.

fn

A function identifying the type of cleaning to do.

type

If fn is not known, an character string can be specified to identify which fn to use. This must be a known type for this function.

...

Passed to fn


Prepare reporting polygons

Description

  • LandWeb FMA boundaries (FMAs);

  • Alberta FMU boundaries (FMUs);

  • Alberta Natural Subregions (ANSRs);

Usage

prepFMAs(destinationPath, targetCRS = LandWebCRS)

prepFMUs(destinationPath, targetCRS = LandWebCRS)

prepANSRs(destinationPath, targetCRS = LandWebCRS)

Arguments

destinationPath

character specifying path to destination directory

targetCRS

character specifying the CRS to reproject polygons to


Prepare species layers from CASFRI v4

Description

Prepare species layers from CASFRI v4

Usage

prepSpeciesLayers_CASFRI(
  destinationPath,
  outputPath,
  url = NULL,
  studyArea,
  rasterToMatch,
  sppEquiv,
  sppEquivCol,
  ...
)

Arguments

destinationPath

path to data directory where objects will be downloaded or saved to

outputPath

character, specifying the output directory to use

url

if NULL, the default, use the default source url

studyArea

A ⁠SpatialPolygons*⁠ object used as the principle study region, passed to reproducible::prepInputs().

rasterToMatch

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

sppEquiv

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

sppEquivCol

the column name to use from sppEquiv. For functions that have mixedType, only necessary if mixedType == 2. If not provided and mixedType == 2, will attempt to use "Boreal".

...

other arguments, used for compatibility with other prepSpeciesLayers functions.


Extract boundary polygon(s) for LandWeb study areas

Description

Extract boundary polygon(s) for LandWeb study areas

Usage

prepStudyArea(name, destinationPath, targetCRS = LandWebCRS)

prepTestStudyArea(destinationPath, targetCRS = LandWebCRS, .seed = 867)

Arguments

name

A character (regex) string to match.

destinationPath

character specifying path to destination directory

targetCRS

character specifying the CRS to reproject polygons to

.seed

integer specifying the random seed to use to generate study area boundary

Value

sf polygons object


Create a list of rasters in each rep, at each timestep, for each polygon area

Description

Create a list of rasters in each rep, at each timestep, for each polygon area

Usage

rasterListByPoly(files, polys, names, col, filter)

Arguments

files

character vector giving paths to raster files

polys

polygon object of class sf

names

character vector giving the names of each of the subpolygons in poly

col

character string giving the column name in poly to use

filter

regex string giving partial filename in files to be filtered out (i.e., when extracting reps, times, etc. from filenames) (e.g., 'rstTimeSinceFire_', 'vegTypeMap_')

Value

list of SpatRaster objects with attributes reps, times, polyNames

Note

uses future_lapply internally to loop across files; set e.g., option future.availableCores.fallback appropriately for your system.


Generate box and whisker plots for leading vegetation cover

Description

Generate box and whisker plots for leading vegetation cover

Usage

runBoxPlotsVegCover(map, functionName, analysisGroups, dPath)

Arguments

map

A map object.

functionName

TODO: description needed

analysisGroups

TODO: description needed

dPath

Destination path for the resulting PNG files.


Generate histograms for large patches

Description

TODO: description needed

Usage

runHistsLargePatches(map, functionName, analysisGroups, dPath)

Arguments

map

A map object.

functionName

TODO: description needed

analysisGroups

TODO: description needed

dPath

Destination path for the resulting PNG files.


Generate histograms for leading vegetation cover

Description

Generate histograms for leading vegetation cover

Usage

runHistsVegCover(map, functionName, analysisGroups, dPath)

Arguments

map

A map object.

functionName

Character specifying the name of the function to apply.

analysisGroups

Character specifying the analysis groups to run.

dPath

Destination path for the resulting PNG files.