| Title: | Landscape Ecosystem Modelling in R |
|---|---|
| Description: | Utilities for 'LandR' suite of landscape simulation models. These models simulate forest vegetation dynamics based on LANDIS-II, and incorporate fire and insect disturbance, as well as other important ecological processes. Models are implemented as 'SpaDES' modules. |
| Authors: | 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>), Ceres Barros [aut] (ORCID: <https://orcid.org/0000-0003-4036-977X>), Ian M S Eddy [aut] (ORCID: <https://orcid.org/0000-0001-7397-2116>), His Majesty the King in Right of Canada, as represented by the Minister of Natural Resources Canada [cph] |
| Maintainer: | Eliot J B McIntire <[email protected]> |
| License: | GPL-3 |
| Version: | 1.2.0.9002 |
| Built: | 2026-06-09 03:58:33 UTC |
| Source: | https://github.com/PredictiveEcology/LandR |
LandR packageUtilities for 'LandR' suite of landscape simulation models. These models simulate forest vegetation dynamics based on LANDIS-II, and incorporate fire and insect disturbance, as well as other important ecological processes. Models are implemented as 'SpaDES' modules.
LandR packages use the following options() to configure behaviour:
LandR.assertions: If TRUE, additional code checks are run during function calls.
Default FALSE.
Maintainer: Eliot J B McIntire [email protected] (ORCID)
Authors:
Eliot J B McIntire [email protected] (ORCID)
Alex M Chubaty [email protected] (ORCID)
Ceres Barros [email protected] (ORCID)
Ian M S Eddy [email protected] (ORCID)
Other contributors:
His Majesty the King in Right of Canada, as represented by the Minister of Natural Resources Canada [copyright holder]
Useful links:
Report bugs at https://github.com/PredictiveEcology/LandR/issues
TODO: Move to reproducible
TODO: Move to reproducible
TODO: expand to multiple objects
.compareRas(x, ...) .compareCRS(x, y).compareRas(x, ...) .compareCRS(x, y)
x, y
|
a |
... |
additional |
the projected extent
this function internally converts Raster to SpatRaster to allow using compareGeom(),
and benefit from its complexity.
Uses likelihood parameter estimation to fit non linear models while attempting several starting values.
.fitNLMwCovariates( data, nonLinModelQuoted, linModelQuoted, mllsOuterPrev, model = c("CR", "Logistic"), maxCover = 1L, starts = NULL, lower = NULL, upper = NULL, nbWorkers = 1L ).fitNLMwCovariates( data, nonLinModelQuoted, linModelQuoted, mllsOuterPrev, model = c("CR", "Logistic"), maxCover = 1L, starts = NULL, lower = NULL, upper = NULL, nbWorkers = 1L )
data |
a |
nonLinModelQuoted |
The non-linear equation as a |
linModelQuoted |
A list of linear equations/modes relating each
parameter ('A', 'p' and 'k') with a set of covariates. A |
mllsOuterPrev |
the output of a previous |
model |
character. Non-linear model form used to estimate average maximum
biomass. One of "CR" (Chapman-Richards) or "Logistic". In both cases, maximum biomass
is equivalent to the 'A' asymptote parameter, which is estimated using observed mean
values of predictors entering its linear equation and |
maxCover |
numeric. Value indicating maximum cover/dominance. |
starts |
|
lower |
passed to bbmle::mle2 |
upper |
passed to bbmle::mle2 |
nbWorkers |
integer. If > 1, the number of workers to use in |
a list with entries mll (the maximum likelihood-estimated
coefficients) and AICbest (the AIC of the best models generating these coefficients)
Extracts the names of linear coefficients for the maximum-biomass-equivalent parameter in the non-linear growth equations
.getMaxBCoefs(mll, model = c("CR", "Logistic")).getMaxBCoefs(mll, model = c("CR", "Logistic"))
mll |
the output of an |
model |
character. Non-linear model form used to estimate average maximum biomass. One of "CR" (Chapman-Richards) or "Logistic". |
a list of two vectors of parameter names one following
coefficient names in mll ('mllCoefNames'), the other using the original
names as in the data used for model fitting ('origCoefNames')
Find interpolated value of light probability
.interpolateLightProb(x, x0, x1, y0, y1).interpolateLightProb(x, x0, x1, y0, y1)
x |
the species shade tolerance trait value for which we want to find the interpolated probability. |
x0 |
the |
x1 |
the |
y0 |
the probability of germination in the |
y1 |
the probability of germination in the |
vector of the interpolated value
Prepare data for model plotting
.MLLMaxBPartialPlotData( mll, nonLinModelQuoted, linModelQuoted, targetCovar = "cover", fixMaxCover = TRUE, maxCover = 1, data, fun = "mean", plotCIs = TRUE ).MLLMaxBPartialPlotData( mll, nonLinModelQuoted, linModelQuoted, targetCovar = "cover", fixMaxCover = TRUE, maxCover = 1, data, fun = "mean", plotCIs = TRUE )
mll |
outputs of an |
nonLinModelQuoted |
The non-linear equation as a |
linModelQuoted |
A list of linear equations/modes relating each
parameter ('A', 'p' and 'k') with a set of covariates. A |
targetCovar |
the covariate for which variation in |
fixMaxCover |
logical. If |
maxCover |
numeric. Value indicating maximum cover/dominance. |
data |
data for estimation of maximum biomass. Should contain at least
an 'age' column. Note that other covariates will be averaged and 'cover' values
will be replaced with the maximum cover value ( |
fun |
The function to apply when summarizing other variables. By default,
the all other variables except age are averaged ( |
plotCIs |
should confidence intervals be calculated and plotted? |
Prepare data for model plotting
.MLLMaxBplotData( mll, nonLinModelQuoted, linModelQuoted, maxCover, data, averageCovariates = TRUE, observedAge = FALSE, plotCIs = TRUE ).MLLMaxBplotData( mll, nonLinModelQuoted, linModelQuoted, maxCover, data, averageCovariates = TRUE, observedAge = FALSE, plotCIs = TRUE )
mll |
outputs of an |
nonLinModelQuoted |
The non-linear equation as a |
linModelQuoted |
A list of linear equations/modes relating each
parameter ('A', 'p' and 'k') with a set of covariates. A |
maxCover |
numeric. Value indicating maximum cover/dominance. |
data |
data for estimation of maximum biomass. Should contain at least
an 'age' column. Note that other covariates will be averaged and 'cover' values
will be replaced with the maximum cover value ( |
averageCovariates |
should covariates other than age/cover be averaged for
biomass predictions? If not, for each age (at maximum cover) there will be as
many predictions as other covariate values. If |
observedAge |
should observed age values be used, or should these be generated
as |
plotCIs |
should confidence intervals be calculated and plotted? |
Raster or SpatRaster
These all create a single function that can be used for either Raster or SpatRaster objects.
.NAvalueFlag(ras, NAval) .stack(rasList) .projectExtent(ras, crs) asInt(ras) isInt(ras) reclass(ras, tab).NAvalueFlag(ras, NAval) .stack(rasList) .projectExtent(ras, crs) asInt(ras) isInt(ras) reclass(ras, tab)
ras |
a |
NAval |
the value to use as |
rasList |
a list of |
crs |
passed to |
tab |
matrix of values to reclassify. See |
a raster with attributed NA values
a stacked raster
the projected extent
asInt returns a *Raster with values converted to integer, if they weren't already.
isInt returns a logical as per is.integer.
reclass returns a *Raster with values reclassified as per terra::classify
and raster::reclassify.
pixelGroup and add it has a new column to cohortData
Add number of pixels per pixelGroup and add it has a new column to cohortData
addNoPixel2CohortData( cohortData, pixelGroupMap, cohortDefinitionCols = LandR::cohortDefinitionCols(), doAssertion = getOption("LandR.assertions", TRUE) )addNoPixel2CohortData( cohortData, pixelGroupMap, cohortDefinitionCols = LandR::cohortDefinitionCols(), doAssertion = getOption("LandR.assertions", TRUE) )
cohortData |
A |
pixelGroupMap |
A |
cohortDefinitionCols |
the columns in |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
An cohortData dat.table with a new noPixels
column
cohortData table per pixel:Generate cohortData table per pixel:
addPixels2CohortData( cohortData, pixelGroupMap, cohortDefinitionCols = LandR::cohortDefinitionCols(), doAssertion = getOption("LandR.assertions", TRUE) )addPixels2CohortData( cohortData, pixelGroupMap, cohortDefinitionCols = LandR::cohortDefinitionCols(), doAssertion = getOption("LandR.assertions", TRUE) )
cohortData |
A |
pixelGroupMap |
A |
cohortDefinitionCols |
the columns in |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
An expanded cohortData data.table with a new pixelIndex column.
longevity x adjustmentFactor
Reduces the age of cohorts that exceed their longevity x adjustmentFactor
adjustAgeToLongevity(pixelCohortData, longevity, adjustmentFactor)adjustAgeToLongevity(pixelCohortData, longevity, adjustmentFactor)
pixelCohortData |
The full |
longevity |
A data.table with the longevity of each species. |
adjustmentFactor |
A numeric controlling the proportion of species longevity that cohort ages cannot exceed. |
A cohortData data.table with corrected ages.
Uses data.table to perform aggregation calculations, which is faster than
raster::aggregate.
aggregateRasByDT(ras, newRas, fn = sum)aggregateRasByDT(ras, newRas, fn = sum)
ras |
|
newRas |
|
fn |
function to use to aggregate pixel values |
RasterLayer
Essentially a wrapper around round, rather than truncate, which is what as.integer
does. Internally, this is simply as.integer(floor(x + 0.5)).
asInteger(x)asInteger(x)
x |
A numeric vector |
An integer vector of length x, rounded to zero decimal places
prior to as.integer
Values ending in .5 will be rounded up, whether positive or negative.
This is different than round.
x <- seq(-2, 2, 0.25) data.frame(dbl = x, int = asInteger(x))x <- seq(-2, 2, 0.25) data.frame(dbl = x, int = asInteger(x))
assert1: Assert that ecoregionCodes that were replaced, were correctly identified;
This is the full pixelCohortData, not the collapsed one.
assert1( cohortData34to36, cohortData, rmZeroBiomassQuote, classesToReplace = 34:36, doAssertion = getOption("LandR.assertions", TRUE) ) assert2( cohortDataNo34to36, classesToReplace = 34:36, doAssertion = getOption("LandR.assertions", TRUE) ) assertSppMaxBMaxANPP( speciesEcoregion, doAssertion = getOption("LandR.assertions", TRUE) ) assertUniqueCohortData( cohortData, columns, doAssertion = getOption("LandR.assertions", TRUE) ) assertERGs( ecoregionMap, cohortData, speciesEcoregion, minRelativeB, doAssertion = getOption("LandR.assertions", TRUE) ) assertColumns( obj, colClasses, doAssertion = getOption("LandR.assertions", TRUE) ) assertCohortData( cohortData, pixelGroupMap, maxExpectedNumDiverge = 1, message = "", doAssertion = getOption("LandR.assertions", TRUE), verbose = getOption("LandR.verbose", TRUE), cohortDefinitionCols = LandR::cohortDefinitionCols() ) assertCohortDataERG( cohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertPixelCohortData( pixelCohortData, pixelGroupMap, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesPlotLabels( speciesNames, sppEquiv, doAssertion = getOption("LandR.assertions", TRUE) ) assertFireToleranceDif( burnedPixelCohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesLayers( speciesLayers, thresh, doAssertion = getOption("LandR.assertions", TRUE) ) assertRstLCChange( rstLCChange, rasterToMatch, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesEcoregionCohortDataMatch( cohortData, speciesEcoregion, doAssertion = getOption("LandR.assertions", TRUE) ) assertPixelCohortDataValid( standCohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertRepsAllCohortData( allCohortData, reps, years, doAssertion = getOption("LandR.assertions", TRUE) ) assertStandAgeMapAttr( standAgeMap, doAssertion = getOption("LandR.assertions", TRUE) ) assertCohortDataAttr( cohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertSppVectors( sppEquiv = NULL, sppNameVector = NULL, sppColorVect = NULL, sppEquivCol = NULL, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesTableRaw( speciesTableRaw, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesTable( speciesTable, doAssertion = getOption("LandR.assertions", TRUE) )assert1( cohortData34to36, cohortData, rmZeroBiomassQuote, classesToReplace = 34:36, doAssertion = getOption("LandR.assertions", TRUE) ) assert2( cohortDataNo34to36, classesToReplace = 34:36, doAssertion = getOption("LandR.assertions", TRUE) ) assertSppMaxBMaxANPP( speciesEcoregion, doAssertion = getOption("LandR.assertions", TRUE) ) assertUniqueCohortData( cohortData, columns, doAssertion = getOption("LandR.assertions", TRUE) ) assertERGs( ecoregionMap, cohortData, speciesEcoregion, minRelativeB, doAssertion = getOption("LandR.assertions", TRUE) ) assertColumns( obj, colClasses, doAssertion = getOption("LandR.assertions", TRUE) ) assertCohortData( cohortData, pixelGroupMap, maxExpectedNumDiverge = 1, message = "", doAssertion = getOption("LandR.assertions", TRUE), verbose = getOption("LandR.verbose", TRUE), cohortDefinitionCols = LandR::cohortDefinitionCols() ) assertCohortDataERG( cohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertPixelCohortData( pixelCohortData, pixelGroupMap, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesPlotLabels( speciesNames, sppEquiv, doAssertion = getOption("LandR.assertions", TRUE) ) assertFireToleranceDif( burnedPixelCohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesLayers( speciesLayers, thresh, doAssertion = getOption("LandR.assertions", TRUE) ) assertRstLCChange( rstLCChange, rasterToMatch, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesEcoregionCohortDataMatch( cohortData, speciesEcoregion, doAssertion = getOption("LandR.assertions", TRUE) ) assertPixelCohortDataValid( standCohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertRepsAllCohortData( allCohortData, reps, years, doAssertion = getOption("LandR.assertions", TRUE) ) assertStandAgeMapAttr( standAgeMap, doAssertion = getOption("LandR.assertions", TRUE) ) assertCohortDataAttr( cohortData, doAssertion = getOption("LandR.assertions", TRUE) ) assertSppVectors( sppEquiv = NULL, sppNameVector = NULL, sppColorVect = NULL, sppEquivCol = NULL, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesTableRaw( speciesTableRaw, doAssertion = getOption("LandR.assertions", TRUE) ) assertSpeciesTable( speciesTable, doAssertion = getOption("LandR.assertions", TRUE) )
cohortData34to36 |
A |
cohortData |
A |
rmZeroBiomassQuote |
An expression to evaluate, in the form of |
classesToReplace |
Integer vector of classes that are are to be replaced, e.g., 34, 35, 36 on LCC2005, which are burned young, burned 10 year, and cities. |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
cohortDataNo34to36 |
A |
speciesEcoregion |
A |
columns |
Vector of column names on which to test for unique |
ecoregionMap |
The |
minRelativeB |
a |
obj |
A |
colClasses |
A named vector of column classes, where the names are the column names |
pixelGroupMap |
A |
maxExpectedNumDiverge |
A numeric, length 1, indicating by how many they can diverge. Default 1. |
message |
An optional message to print. This may help identify where this function was called. |
verbose |
Controls message output. Defaults to |
cohortDefinitionCols |
the columns in |
pixelCohortData |
The full |
speciesNames |
A vector of species names for which the labels will be checked |
sppEquiv |
an table with a column containing species names |
burnedPixelCohortData |
An expanded |
speciesLayers |
A |
thresh |
the minimum number of pixels where the species must have
|
rstLCChange |
a raster layer indicating pixels were land-use change occurred as 1s |
rasterToMatch |
A |
standCohortData |
A |
allCohortData |
A |
reps |
repetition ids |
years |
years |
standAgeMap |
A |
sppNameVector |
A character vector of species to use. These species must all
be from one naming convention, i.e., from one column in the |
sppColorVect |
A named vector of colours to use for plotting.
The names must conform with species name convention used
(see sppEquivalencies_CA for possible naming
conventions) and should also contain a colour for 'Mixed',
when a mixed forest type is supported (see |
sppEquivCol |
the column name to use from |
speciesTableRaw |
raw species traits |
speciesTable |
species traits |
Assert post-fire disturbance mortality and regeneration
assertPostPartialDist( cohortDataOrig, pixelGroupMapOrig, cohortDataNew, pixelGroupMapNew, postDistPixelCohortData, distrbdPixelCohortData, doAssertion = getOption("LandR.assertions", TRUE) )assertPostPartialDist( cohortDataOrig, pixelGroupMapOrig, cohortDataNew, pixelGroupMapNew, postDistPixelCohortData, distrbdPixelCohortData, doAssertion = getOption("LandR.assertions", TRUE) )
cohortDataOrig |
original |
pixelGroupMapOrig |
original |
cohortDataNew |
modified |
pixelGroupMapNew |
modified |
postDistPixelCohortData |
modified |
distrbdPixelCohortData |
|
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
Assign light probability
assignLightProb( sufficientLight, newCohortData, interpolate = TRUE, doAssertion = getOption("LandR.assertions", TRUE) )assignLightProb( sufficientLight, newCohortData, interpolate = TRUE, doAssertion = getOption("LandR.assertions", TRUE) )
sufficientLight |
a |
newCohortData |
a modified version of |
interpolate |
Logical. Activates interpolation of probabilities of establishment between any two values of shade tolerance in the sufficient light table, allowing species shade tolerance trait values to take any decimal value between 1 and 5 (inclusively). If FALSE, species shade tolerances can only take integer values between 1 and 5 (inclusively). |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
newCohortData with a lightProb column
biomod2::BIOMOD_EnsembleForecasting()
Simple wrapper around biomod2::BIOMOD_EnsembleForecasting()
biomodEnsembleFrcstWrapper( bm.em, bm.proj = NULL, proj.name = NULL, new.env = NULL, new.env.xy = NULL, keep.in.memory = TRUE, ... )biomodEnsembleFrcstWrapper( bm.em, bm.proj = NULL, proj.name = NULL, new.env = NULL, new.env.xy = NULL, keep.in.memory = TRUE, ... )
bm.em |
output of biomod2::BIOMOD_EnsembleModeling |
bm.proj |
output of biomod2::BIOMOD_Projection |
proj.name |
passed to biomod2::BIOMOD_Projection |
new.env |
passed to biomod2::BIOMOD_EnsembleForecasting |
new.env.xy |
passed to biomod2::BIOMOD_EnsembleForecasting |
keep.in.memory |
passed to biomod2::BIOMOD_EnsembleForecasting |
... |
passed to reproducible::Cache |
BIOMOD_EnsembleForecasting() resultsMake maps from BIOMOD_EnsembleForecasting() results
biomodEnsembleProjMaps(bm.em.proj, predModel, rasTemplate, origCRS)biomodEnsembleProjMaps(bm.em.proj, predModel, rasTemplate, origCRS)
bm.em.proj |
output of |
predModel |
character. Which model predictions should be used.
Choose one of |
rasTemplate |
a template |
origCRS |
character. The original CRS projection of |
a SpatRaster object
BIOMOD_EnsembleModeling wrapper
biomodEnsembleWrapper(bm.mod, metric.select.thresh = NULL, ...)biomodEnsembleWrapper(bm.mod, metric.select.thresh = NULL, ...)
bm.mod |
output of biomod2::BIOMOD_Modeling |
metric.select.thresh |
passed biomod2::BIOMOD_EnsembleModeling. By default no thresholding is applied. |
... |
passed to reproducible::Cache |
BIOMOD_Modeling wrapper
biomodModelingWrapper( sp, responseVar, responseVarData, predictorVars, predictorVarsData, dir.name, BIOMOD_ModelingArgs = list(models = c("GLM", "MARS"), bm.options = NULL, CV.k = 5, CV.perc = 100, metric.eval = c("TSS", "ROC"), modeling.id = "test"), ... )biomodModelingWrapper( sp, responseVar, responseVarData, predictorVars, predictorVarsData, dir.name, BIOMOD_ModelingArgs = list(models = c("GLM", "MARS"), bm.options = NULL, CV.k = 5, CV.perc = 100, metric.eval = c("TSS", "ROC"), modeling.id = "test"), ... )
sp |
character of species name to subset |
responseVar |
character vector, or list of character vectors, of response
variable (column) to subset |
responseVarData |
a data.table or list of data.tables with environmental data.
If a list, it should be named according to |
predictorVars |
character vector, or list of character vectors, of environmental
variables (columns) to subset |
predictorVarsData |
environmental data. |
dir.name |
passed to biomod2::BIOMOD_FormatingData |
BIOMOD_ModelingArgs |
a named list of arguments passed to biomod2::BIOMOD_Modeling |
... |
further arguments passed to reproducible::Cache |
BIOMOD_Projection wrapper
biomodProjWrapper( bm.mod, proj.name = "testProj", new.env = NULL, new.env.xy = NULL, ... )biomodProjWrapper( bm.mod, proj.name = "testProj", new.env = NULL, new.env.xy = NULL, ... )
bm.mod |
passed to biomod2::BIOMOD_Projection. If not supplied the data used to fit the model will be used. |
proj.name |
passed to biomod2::BIOMOD_Projection |
new.env |
passed to biomod2::BIOMOD_Projection |
new.env.xy |
passed to biomod2::BIOMOD_Projection |
... |
passed to reproducible::Cache |
BioSIM functionsExtract point locations from DEM raster to pass to BioSIM functions
BioSIM_extractPoints(x)BioSIM_extractPoints(x)
x |
A digital elevation model (DEM) |
data.table with columns Name, Long, Lat, Elev.
BioSIM
Raster stacks for all 9 MPB climate indices. See BioSIM::getModelHelp("MPB_SLR").
BioSIM_getMPBSLR(dem, years, SLR = "R", climModel = "GCM4", rcp = "RCP45")BioSIM_getMPBSLR(dem, years, SLR = "R", climModel = "GCM4", rcp = "RCP45")
dem |
|
years |
numeric vector corresponding to the years to retrieve. |
SLR |
character. Specifies which climate suitability index to extract.
Currently, one of |
climModel |
climate model to use. one of |
rcp |
RCP scenario to use. one of |
RasterStack
Although the BioSIM MPB_SLR model provides several other indices
(see BioSIM::getModelHelp("MPB_SLR")), only 4 are currently used here.
BioSIM
Get annual historic and projected wind maps from BioSIM
BioSIM_getWindAnnual(dem, years, climModel = "GCM4", rcp = "RCP45")BioSIM_getWindAnnual(dem, years, climModel = "GCM4", rcp = "RCP45")
dem |
|
years |
numeric vector corresponding to the years to retrieve. |
climModel |
climate model to use. one of |
rcp |
RCP scenario to use. one of |
RasterStack
BioSIM
Get monthly historic and projected wind maps from BioSIM
BioSIM_getWindMonthly(dem, years, months, climModel = "GCM4", rcp = "RCP45")BioSIM_getWindMonthly(dem, years, months, climModel = "GCM4", rcp = "RCP45")
dem |
|
years |
numeric vector corresponding to the years to retrieve. |
months |
numeric vector corresponding to the months to retrieve
(e.g., |
climModel |
climate model to use. one of |
rcp |
RCP scenario to use. one of |
RasterStack
calc_raster_stats iteratively calculates the frequency of raster values within each polygon.
Supports user-provided polygons or automatic retrieval of ecoregions/ecozones.
calc_raster_counts( raster, polygons = NULL, polygon_id = NULL, filter_ids = NULL ) calc_raster_stats( raster, polygons = NULL, polygon_id = NULL, filter_ids = NULL ) plot_raster_stats( raster, polygons = NULL, polygon_id = NULL, filter_ids = NULL, counts_df = NULL, stats_df = NULL, aggregate_factor = 1, remove_zeros = FALSE, raster_label = NULL, inset_canada = TRUE, bin_width = 10, output_dir = ".", csv_file = NULL )calc_raster_counts( raster, polygons = NULL, polygon_id = NULL, filter_ids = NULL ) calc_raster_stats( raster, polygons = NULL, polygon_id = NULL, filter_ids = NULL ) plot_raster_stats( raster, polygons = NULL, polygon_id = NULL, filter_ids = NULL, counts_df = NULL, stats_df = NULL, aggregate_factor = 1, remove_zeros = FALSE, raster_label = NULL, inset_canada = TRUE, bin_width = 10, output_dir = ".", csv_file = NULL )
raster |
A |
polygons |
A |
polygon_id |
Name of the column in |
filter_ids |
Optional. Polygon IDs to filter. |
counts_df |
optional |
stats_df |
optional |
aggregate_factor |
Optional. Integer factor to aggregate raster for plotting. Default is |
remove_zeros |
Logical. Removes zeroes from raster and counts for plotting. Useful to eliminate non-forested areas from forest rasters. |
raster_label |
Optional. Character label for raster used in plots. Defaults to raster layer name. |
inset_canada |
Logical. Generates a small inset map of plotted polygons within Canada. |
bin_width |
Numeric. Bin size for histogram plots. |
output_dir |
Directory to save figures and optional csv file. |
csv_file |
Optional. Base filename to save the output CSV file.
If provided, a suffix will be added to this filename to denote the 'counts' and 'stats' tables
(e.g., if |
plot_raster_stats calculates and returns statistics (min, max, median, mean,
25th percentile, 75th percentile, and proportion of zeroes) for a raster,
and creates and saves figures for each polygon in a vector layer, including
a histogram of raster values, a map of raster values within the polygon, and
a summary of statistics . Optionally, zero values can be removed from the
analysis, and the raster can be aggregated to a lower resolution to speed up plotting.
A data.frame with columns: ID, value, count.
A data.frame of computed statistics (via calc_raster_stats()), with side effects
of saving summary plots (and optionally a ‘.csv’) to disk.
Large rasters should be processed on disk, where possible, e.g. by setting
terraOptions(memfrac = 0.0).
if (interactive()) { if (requireNamespace("dplyr", quietly = TRUE) && requireNamespace("geodata", quietly = TRUE) && requireNamespace("purrr", quietly = TRUE) && requireNamespace("withr", quietly = TRUE) && requireNamespace("zonal", quietly = TRUE)) { tmp_pth <- withr::local_tempdir() ## work with raster on disk instead of in memory terraOptions(memfrac = 0.0) age <- prepInputsStandAgeMap( dataSource = "KNN", dataYear = 2011, destinationPath = tmp_pth ) ecozones <- reproducible::prepInputs( url = "https://sis.agr.gc.ca/cansis/nsdb/ecostrat/zone/ecozone_shp.zip", destinationPath = tmp_pth ) |> sf::st_make_valid() id_col <- "ZONE_NAME" ## WARNING: don't use Cache() below -- excessive RAM usage ecozone_counts <- calc_raster_counts( raster = age, polygons = ecozones, polygon_id = id_col ) ecozone_stats <- calc_raster_stats( raster = age, polygons = ecozones, polygon_id = id_col ) gc() ## below will call calc_raster_counts and calc_raster_stats internally, ## so we shortcut this by passing the previously-calculated tables stats_ecozone <- plot_raster_stats( raster = age, polygons = ecozones, polygon_id = id_col, filter_ids = NULL, counts_df = ecozone_counts, stats_df = ecozone_stats, aggregate_factor = 1, remove_zeros = FALSE, raster_label = "age", inset_canada = TRUE, bin_width = 10, output_dir = tmp_pth, csv_file = NULL ) gc() ## review the plots produced in tmp_pth list.files(tmp_pth, pattern = "[.]png", full.names = TRUE) identical(ecozone_stats, stats_ecozone) ## TRUE } }if (interactive()) { if (requireNamespace("dplyr", quietly = TRUE) && requireNamespace("geodata", quietly = TRUE) && requireNamespace("purrr", quietly = TRUE) && requireNamespace("withr", quietly = TRUE) && requireNamespace("zonal", quietly = TRUE)) { tmp_pth <- withr::local_tempdir() ## work with raster on disk instead of in memory terraOptions(memfrac = 0.0) age <- prepInputsStandAgeMap( dataSource = "KNN", dataYear = 2011, destinationPath = tmp_pth ) ecozones <- reproducible::prepInputs( url = "https://sis.agr.gc.ca/cansis/nsdb/ecostrat/zone/ecozone_shp.zip", destinationPath = tmp_pth ) |> sf::st_make_valid() id_col <- "ZONE_NAME" ## WARNING: don't use Cache() below -- excessive RAM usage ecozone_counts <- calc_raster_counts( raster = age, polygons = ecozones, polygon_id = id_col ) ecozone_stats <- calc_raster_stats( raster = age, polygons = ecozones, polygon_id = id_col ) gc() ## below will call calc_raster_counts and calc_raster_stats internally, ## so we shortcut this by passing the previously-calculated tables stats_ecozone <- plot_raster_stats( raster = age, polygons = ecozones, polygon_id = id_col, filter_ids = NULL, counts_df = ecozone_counts, stats_df = ecozone_stats, aggregate_factor = 1, remove_zeros = FALSE, raster_label = "age", inset_canada = TRUE, bin_width = 10, output_dir = tmp_pth, csv_file = NULL ) gc() ## review the plots produced in tmp_pth list.files(tmp_pth, pattern = "[.]png", full.names = TRUE) identical(ecozone_stats, stats_ecozone) ## TRUE } }
Calculates fire severity as the loss of pre-fire to post-fire biomass (in absolute and percentual terms).
calcSeverityB(cohortData, burnedPixelCohortData)calcSeverityB(cohortData, burnedPixelCohortData)
cohortData |
A |
burnedPixelCohortData |
An expanded |
data.table with columns pixelIndex,
pixelGroup and severityB (absolute biomass lost)
and severityPropB (proportion of biomass lost)
if burnedPixelCohortData does not have a B
column, the fire is assumed to be stand replacing (i.e.
we assume B to be 0 across all pixels/cohorts in
burnedPixelCohortData)
Calculate site shade
calcSiteShade(currentTime, cohortData, speciesEcoregion, minRelativeB)calcSiteShade(currentTime, cohortData, speciesEcoregion, minRelativeB)
currentTime |
The current simulation time e.g., |
cohortData |
A |
speciesEcoregion |
A |
minRelativeB |
a |
cohortData table with a siteShade column
Default climate effects function in the case where no climate effect is simulated
calculateClimateEffect(cohortData, ...)calculateClimateEffect(cohortData, ...)
cohortData |
A |
... |
additional arguments that are passed to LandR.CS |
the cohortData object is used to calculate the \
reduction/increase of mortality and growth biomasses per cohort.
data.table with pixelGroup, age and speciesCode, as well as
mortPred and growthPred columns with \
growth biomasses resulting from a climate effect.
These percentages are later multiplied by the by baseline biomasses of mortality and growth
(e.g. 0\
This default, no climate effect, function outputs 100\
mortPred and growthPred.
CASFRItoSpRastsExtract CASFRI data.table values and create species layer rasters
CASFRItoSpRasts( CASFRIRas, CASFRIattrLong, CASFRIdt, sppEquiv, sppEquivCol, destinationPath )CASFRItoSpRasts( CASFRIRas, CASFRIattrLong, CASFRIdt, sppEquiv, sppEquivCol, destinationPath )
CASFRIRas |
|
CASFRIattrLong |
data.table of CASFRI attributes (long format) (i.e., from loadCASFRI) |
CASFRIdt |
data.table of CASFRI raster values (i.e., from loadCASFRI) |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
destinationPath |
path to data directory where objects will be downloaded or saved to |
RasterStack (or equivalent)
Check if all species in have trait values
checkSpeciesTraits(speciesLayers, species, sppColorVect)checkSpeciesTraits(speciesLayers, species, sppColorVect)
speciesLayers |
A |
species |
a
|
sppColorVect |
A named vector of colours to use for plotting.
The names must conform with species name convention used
(see sppEquivalencies_CA for possible naming
conventions) and should also contain a colour for 'Mixed',
when a mixed forest type is supported (see |
A list with the speciesLayers and sppColorVect
containing only the species that have trait values in species
Default columns that define cohorts
cohortDefinitionCols()cohortDefinitionCols()
because the name cohortDefinitionCols is also used as a function argument,
be sure to use LandR::cohortDefinitionCols() in those functions or you'll get a
"promise already under evaluation" error.
SpatRaster colorsThis is a wrapper to help with migration to terra.
Currently can only be used for a single layer SpatRaster or a RasterLayer.
Colors(ras, cols, n = NULL)Colors(ras, cols, n = NULL)
ras |
A |
cols |
a character vector of colours. See examples.
Can also be a |
n |
A numeric scalar giving the number of colours to create.
Passed to |
cols <- colorRampPalette(c("blue", "red"))(12) ras <- terra::rast(matrix(1:100, 10, 10)) ras <- Colors(ras, cols) terra::plot(ras) ras <- raster::raster(matrix(1:100, 10, 10)) ras <- Colors(ras, cols) raster::plot(ras)cols <- colorRampPalette(c("blue", "red"))(12) ras <- terra::rast(matrix(1:100, 10, 10)) ras <- Colors(ras, cols) terra::plot(ras) ras <- raster::raster(matrix(1:100, 10, 10)) ras <- Colors(ras, cols) raster::plot(ras)
Default columns that define pixel groups
columnsForPixelGroups()columnsForPixelGroups()
because the name columnsForPixelGroups is also used as a function argument,
be sure to use LandR::columnsForPixelGroups() in those functions or you'll get a
"promise already under evaluation" error.
This function has been run previously to create layers with the correct codes which
are available on Google Drive. These corrected layers are available here:
https://drive.google.com/drive/folders/1zLYV-wcDjJfSflH1VkXG6sosqZZF4SYc
In the respective folder for each year, under the file name
SCANFI_att_nfiLandCover_CanadaLCCclassCodes_S_<YEAR>_v1_1.tif
convert_SCANFI_LCC_codes(year = 2000, dataVersion = "V2", ...)convert_SCANFI_LCC_codes(year = 2000, dataVersion = "V2", ...)
year |
data year for SCANFI landcover data. 2000, 2010, and 2020 possible for V1. 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025 possible for V2. |
dataVersion |
Character. SCANFI product version for data. Default is currently V2. V1 also available. |
... |
additional args (not used) |
a SpatRaster with corrected classification codes
This will search around the pixels on rstLCC that have
classesToReplace, and search in iteratively increasing
radii outwards for other Land Cover Classes than the those indicated in
classesToReplace. This will constrain
It will then take the cohorts that were in pixels with classesToReplace
and assign them new values in the output object. This function will
also check that it must be an ecoregionCode that already exists in
cohortData, i.e., not create new ecoregionCode values. See Details.
convertUnwantedLCC( classesToReplace = 34:36, rstLCC, availableERC_by_Sp, theUnwantedPixels, ecoregionGroupVec, speciesEcoregion, pixelClassesToReplace, doAssertion = getOption("LandR.assertions", TRUE) )convertUnwantedLCC( classesToReplace = 34:36, rstLCC, availableERC_by_Sp, theUnwantedPixels, ecoregionGroupVec, speciesEcoregion, pixelClassesToReplace, doAssertion = getOption("LandR.assertions", TRUE) )
classesToReplace |
Integer vector of classes that are are to be replaced, e.g., 34, 35, 36 on LCC2005, which are burned young, burned 10 year, and cities. |
rstLCC |
LCC raster, e.g., LCC2005 |
availableERC_by_Sp |
A |
theUnwantedPixels |
An optional vector of pixel IDs that need to be changed.
If not provided, then pixels to change will be taken from the match between
|
ecoregionGroupVec |
Deprecated. Use |
speciesEcoregion |
Deprecated. Use |
pixelClassesToReplace |
Deprecated. Use |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
This function is designed to be used in highly constrained situations, where it is not just replacing a Land Cover Class by a neighbouring Land Cover Class. But it can be used for the simpler cases of simply replacing a Land Cover Class.
A data.table with two columns, pixelIndex and ecoregionGroup.
This represents the new codes to used in the pixelIndex locations.
These should have no values overlapping with classesToReplace.
Eliot McIntire
This will search around the pixels on rstLCC that have
classesToReplace, and search in iteratively increasing
radii outwards for other Land Cover Classes than the those indicated in
classesToReplace.
.
convertUnwantedLCC2( classesToReplace = 34:36, rstLCC, nIterations = 6, defaultNewValue = NA, invalidClasses = NA )convertUnwantedLCC2( classesToReplace = 34:36, rstLCC, nIterations = 6, defaultNewValue = NA, invalidClasses = NA )
classesToReplace |
Integer vector of classes that are are to be replaced, e.g., 34, 35, 36 on LCC2005, which are burned young, burned 10 year, and cities. |
rstLCC |
raster of land-cover class, e.g., LCC2005 |
nIterations |
the number of iterations to perform |
defaultNewValue |
the value to assign a pixel in |
invalidClasses |
classes that are not valid options |
A rasterLayer with values in classesToReplace converted to adjacent values or NA.
Eliot McIntire Ian Eddy
Define flammability map
defineFlammable( LandCoverClassifiedMap = NULL, nonFlammClasses = c(0L, 25L, 30L, 33L, 36L, 37L, 38L, 39L), mask = NULL, to = NULL, writeTo = NULL, ... )defineFlammable( LandCoverClassifiedMap = NULL, nonFlammClasses = c(0L, 25L, 30L, 33L, 36L, 37L, 38L, 39L), mask = NULL, to = NULL, writeTo = NULL, ... )
LandCoverClassifiedMap |
A |
nonFlammClasses |
numeric vector defining which classes in |
mask |
A raster to use as a mask (see |
to |
Passed to |
writeTo |
See |
... |
additional args (not used) |
cohortData
Summary for cohortData
describeCohortData(cohortData)describeCohortData(cohortData)
cohortData |
A |
Activate resprouting after a (fire) disturbance
doResprouting( burnedPixelCohortData, postFirePixelCohortData, postFireRegenSummary = NULL, serotinyPixel, treedFirePixelTableSinceLastDisp, currentTime, species, sufficientLight, calibrate = FALSE )doResprouting( burnedPixelCohortData, postFirePixelCohortData, postFireRegenSummary = NULL, serotinyPixel, treedFirePixelTableSinceLastDisp, currentTime, species, sufficientLight, calibrate = FALSE )
burnedPixelCohortData |
An expanded |
postFirePixelCohortData |
an empty |
postFireRegenSummary |
a data.table summarizing for which species serotiny/resprouting were
activated and in how many pixels, for each year. Only necessary if |
serotinyPixel |
a vector of pixels where serotiny was activated; |
treedFirePixelTableSinceLastDisp |
a vector of pixels that burnt and were forested in the previous time step. |
currentTime |
integer. The current simulation time obtained with |
species |
a
|
sufficientLight |
a |
calibrate |
logical. Determines whether to output |
A list of objects:
postFirePixelCohortData, a data.table with the cohorts that undergo serotiny;
serotinyPixel, a vector of pixels where serotiny was activated;
postFireRegenSummary, the updated postFireRegenSummary, if calibrate = TRUE.
Activate serotiny after a (fire) disturbance
doSerotiny( burnedPixelCohortData, postFirePixelCohortData, postFireRegenSummary = NULL, species, sufficientLight, speciesEcoregion, currentTime, treedFirePixelTableSinceLastDisp, calibrate = FALSE )doSerotiny( burnedPixelCohortData, postFirePixelCohortData, postFireRegenSummary = NULL, species, sufficientLight, speciesEcoregion, currentTime, treedFirePixelTableSinceLastDisp, calibrate = FALSE )
burnedPixelCohortData |
An expanded |
postFirePixelCohortData |
an empty |
postFireRegenSummary |
a data.table summarizing for which species serotiny/resprouting were
activated and in how many pixels, for each year. Only necessary if |
species |
a
|
sufficientLight |
a |
speciesEcoregion |
A |
currentTime |
integer. The current simulation time obtained with |
treedFirePixelTableSinceLastDisp |
a vector of pixels that burnt and were forested in the previous time step. |
calibrate |
logical. Determines whether to output |
A list of objects:
postFirePixelCohortData, a data.table with the cohorts that undergo serotiny;
serotinyPixel, a vector of pixels where serotiny was activated;
postFireRegenSummary, the updated postFireRegenSummary, if calibrate = TRUE.
Based on https://stackoverflow.com/a/23382097/1380598.
dropTerm(form, term, dropRanEff = TRUE)dropTerm(form, term, dropRanEff = TRUE)
form |
A model formula. |
term |
Character vector giving the name of the term to drop. |
dropRanEff |
Logical. If |
An updated model formula.
ecoregionMap and ecoregion tableThis function combines an ecoregion map and a land cover map (e.g. ecodistricts and LCC)
and creates a map and table of containing their combined values and pixel IDs.
Used internally in LandR modules to prepare maps for to make cohortData.
ecoregionProducer( ecoregionMaps, ecoregionName = NULL, rasterToMatch, ecoregionTable )ecoregionProducer( ecoregionMaps, ecoregionName = NULL, rasterToMatch, ecoregionTable )
ecoregionMaps |
a |
ecoregionName |
the name describing the type of ecoregions in first map
(e.g. |
rasterToMatch |
A |
ecoregionTable |
A data.table that has 2 columns, |
A list with two objects: the ecoregionMap and a table summarizing
its information per pixelID
data.frame of equivalenciesThis is simply a wrapper around match or \%in\% for
a specific data.frame of values.
equivalentName(value, df, column, multi = FALSE, searchColumn = NULL) equivalentNameColumn(value, df, column, multi = FALSE, searchColumn = NULL)equivalentName(value, df, column, multi = FALSE, searchColumn = NULL) equivalentNameColumn(value, df, column, multi = FALSE, searchColumn = NULL)
value |
Vector of values to match in |
df |
A |
column |
A character string or numeric of length 1, indicating the column
in |
multi |
Logical. If |
searchColumn |
Optionally, provide the name of a column in |
Estimation of maximum biomass as the A parameter in the Chapman-Richards and Logistic growth equations. Since A is modelled as linear term, it is a matrix product of its linear coefficients. It is assumed that all coefficients are related additively.
extractMaxB(mll, newdata, average = FALSE, model = c("CR", "Logistic"))extractMaxB(mll, newdata, average = FALSE, model = c("CR", "Logistic"))
mll |
the output of an |
newdata |
data for estimation of 'A' |
average |
should 'A' be estimated for average values of its predictors. |
model |
character. Non-linear model form used to estimate average maximum biomass. One of "CR" (Chapman-Richards) or "Logistic". |
fasterize
Rasterize polygons using fasterize
fasterizeFromSp(sp, raster, fieldName)fasterizeFromSp(sp, raster, fieldName)
sp |
a shapefile to rasterize |
raster |
the template raster to use |
fieldName |
the field to use (will be ignored if the shapefile has no fields) |
RasterLayer
Disturbance functions
FireDisturbance( cohortData = copy(sim$cohortData), cohortDefinitionCols = c("pixelGroup", "age", "speciesCode"), calibrate = FALSE, postFireRegenSummary = copy(sim$postFireRegenSummary), treedFirePixelTableSinceLastDisp = sim$treedFirePixelTableSinceLastDisp, rstCurrentBurn = sim$rstCurrentBurn, inactivePixelIndex = sim$inactivePixelIndex, pixelGroupMap = sim$pixelGroupMap, currentTime = NULL, rasterToMatch = sim$rasterToMatch, species = copy(sim$species), sufficientLight = copy(sim$sufficientLight), speciesEcoregion = copy(sim$speciesEcoregion), initialB = 10, successionTimestep = 10L, doAssertion = getOption("LandR.assertions", TRUE), verbose = getOption("LandR.verbose", TRUE) ) FireDisturbancePM( cohortData = copy(sim$cohortData), cohortDefinitionCols = c("pixelGroup", "age", "speciesCode"), colsForPixelGroups = LandR::columnsForPixelGroups(), calibrate = FALSE, LANDISPM = TRUE, postFireRegenSummary = copy(sim$postFireRegenSummary), treedFirePixelTableSinceLastDisp = copy(sim$treedFirePixelTableSinceLastDisp), rstCurrentBurn = sim$rstCurrentBurn, inactivePixelIndex = sim$inactivePixelIndex, pixelGroupMap = sim$pixelGroupMap, currentTime = NULL, rasterToMatch = sim$rasterToMatch, fireDamageTable = copy(sim$fireDamageTable), fireRSORas = sim$fireRSORas, fireROSRas = sim$fireROSRas, fireCFBRas = sim$fireCFBRas, species = copy(sim$species), sufficientLight = copy(sim$sufficientLight), speciesEcoregion = copy(sim$speciesEcoregion), initialB = 10, minRelativeB = copy(sim$minRelativeB), successionTimestep = 10L, doAssertion = getOption("LandR.assertions", TRUE), verbose = getOption("LandR.verbose", TRUE) ) PeatlandThermokarst( thawedPixIDs = copy(sim$thawedPixIDs), treedThawedPixelTableSinceLastDisp = copy(sim$treedThawedPixelTableSinceLastDisp), wetlands = sim$wetlands, cohortData = copy(sim$cohortData), pixelGroupMap = sim$pixelGroupMap, rasterToMatch = sim$rasterToMatch, species = copy(sim$species), speciesEcoregion = copy(sim$speciesEcoregion), cohortDefinitionCols = LandR::cohortDefinitionCols(), initialB = 10L, inactivePixelIndex = sim$inactivePixelIndex, currentTime = NULL, successionTimestep = 10L )FireDisturbance( cohortData = copy(sim$cohortData), cohortDefinitionCols = c("pixelGroup", "age", "speciesCode"), calibrate = FALSE, postFireRegenSummary = copy(sim$postFireRegenSummary), treedFirePixelTableSinceLastDisp = sim$treedFirePixelTableSinceLastDisp, rstCurrentBurn = sim$rstCurrentBurn, inactivePixelIndex = sim$inactivePixelIndex, pixelGroupMap = sim$pixelGroupMap, currentTime = NULL, rasterToMatch = sim$rasterToMatch, species = copy(sim$species), sufficientLight = copy(sim$sufficientLight), speciesEcoregion = copy(sim$speciesEcoregion), initialB = 10, successionTimestep = 10L, doAssertion = getOption("LandR.assertions", TRUE), verbose = getOption("LandR.verbose", TRUE) ) FireDisturbancePM( cohortData = copy(sim$cohortData), cohortDefinitionCols = c("pixelGroup", "age", "speciesCode"), colsForPixelGroups = LandR::columnsForPixelGroups(), calibrate = FALSE, LANDISPM = TRUE, postFireRegenSummary = copy(sim$postFireRegenSummary), treedFirePixelTableSinceLastDisp = copy(sim$treedFirePixelTableSinceLastDisp), rstCurrentBurn = sim$rstCurrentBurn, inactivePixelIndex = sim$inactivePixelIndex, pixelGroupMap = sim$pixelGroupMap, currentTime = NULL, rasterToMatch = sim$rasterToMatch, fireDamageTable = copy(sim$fireDamageTable), fireRSORas = sim$fireRSORas, fireROSRas = sim$fireROSRas, fireCFBRas = sim$fireCFBRas, species = copy(sim$species), sufficientLight = copy(sim$sufficientLight), speciesEcoregion = copy(sim$speciesEcoregion), initialB = 10, minRelativeB = copy(sim$minRelativeB), successionTimestep = 10L, doAssertion = getOption("LandR.assertions", TRUE), verbose = getOption("LandR.verbose", TRUE) ) PeatlandThermokarst( thawedPixIDs = copy(sim$thawedPixIDs), treedThawedPixelTableSinceLastDisp = copy(sim$treedThawedPixelTableSinceLastDisp), wetlands = sim$wetlands, cohortData = copy(sim$cohortData), pixelGroupMap = sim$pixelGroupMap, rasterToMatch = sim$rasterToMatch, species = copy(sim$species), speciesEcoregion = copy(sim$speciesEcoregion), cohortDefinitionCols = LandR::cohortDefinitionCols(), initialB = 10L, inactivePixelIndex = sim$inactivePixelIndex, currentTime = NULL, successionTimestep = 10L )
cohortData |
A |
cohortDefinitionCols |
the columns in |
calibrate |
logical. Determines whether to output |
postFireRegenSummary |
a data.table summarizing for which species serotiny/resprouting were
activated and in how many pixels, for each year. Only necessary if |
treedFirePixelTableSinceLastDisp |
data.table with 3 columns: |
rstCurrentBurn |
raster layer with burnt pixels in |
inactivePixelIndex |
an internal object to |
pixelGroupMap |
A |
currentTime |
numeric. Current simulation time step (as in |
rasterToMatch |
A |
species |
a
|
sufficientLight |
a |
speciesEcoregion |
A |
initialB |
the initial biomass of new cohorts. Defaults to 10.
If initialB = asInteger(pmin(maxANPP, asInteger(pmax(1, maxANPP \* exp(-1.6 \* sumB / maxB_eco))))) where |
successionTimestep |
The time between successive seed dispersal events. In LANDIS-II, this is called "Succession Timestep". |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
verbose |
Controls message output. Defaults to |
colsForPixelGroups |
character. |
LANDISPM |
logical. Should partial mortality be calculated as in LANDIS-II Dynamic Fire System v3.0.
Must be |
fireDamageTable |
|
fireRSORas |
raster layer of critical spread rate for crowning (m/min) for each burned pixel. If not provided dummy values are used. |
fireROSRas |
raster layer of equilibrium rate of spread (m/min) for each burned pixel. If not provided dummy values are used. |
fireCFBRas |
raster layer of crown fraction burnt for each burned pixel. If not provided dummy values are used. |
minRelativeB |
a |
thawedPixIDs |
integer. Vector of pixel IDs than underwent thermokarst (and were converted to wetlands) in the current year (not the last thermokarst event). |
treedThawedPixelTableSinceLastDisp |
data.table with 3 columns: |
wetlands |
binary SpatRaster with current wetland pixels. |
a list of objects to be exported to sim:
cohortData
pixelGroupMap
lastFireYear
treedFirePixelTableSinceLastDisp
serotinyResproutSuccessPixels
severityBMap
severityData
postFireRegenSummary (if calibrate == TRUE and !is.null(postFireRegenSummary))
FireDisturbance() simulates post-fire mortality, serotiny and regeneration sequentially occurring after a fire.
Post-fire mortality is assumed to be 100% (stand-replacement). The serotiny and regeneration
algorithms are based on those in LANDIS-II Biomass Succession extension, v3.2.1, with modifications
Requires the following objects in sim (passed as sim$*):
@template FireDisturbance.
For any given burnt pixel, the function begins by killing all cohorts
(i.e. removing them from cohortData). Then it activates serotiny for
serotinous species that had been present pre-fire, and reprouting for reprouter
species. Whether a species successfully regenerates via serotiny or resprouting
depends on its traits (whether it is serotinous, resprouter, both or none;
species table), pre-fire cohort age (in cohortData table), its light/shade
requirements (species table) and its local maxB (speciesEcoregion)
table (see Scheller & Miranda, 2015 and Scheller & Mladenoff, 2004 for details).
Unlike in LANDIS-II Biomass Succession extension, v3.2.1, here we allow serotiny
and resprouting to occur in the same pixel to reflect the competitive advantage
of reprouters. However, for a given species only serotiny (takes precedence)
or resprouting can be activated.
The species table must contain the columns:
sexualmature – age at sexual maturity
postfireregen – post-fire regeneration strategy ("serotiny", "resprout" or "none")
shadetolerance – shade tolerance value relative to other species.
resproutage_min, resproutage_max – minimum and maximum age at which species can repsrout
resproutprob – probability of resporuting success (before light/shade suitability is assessed)
FireDisturbancePM() simulates partial post-fire mortality, serotiny and regeneration
sequentially after a fire. The level of mortality depends of fire severity,
and, by default, follows the mechanisms in LANDIS-II Dynamic Fire System v3.0.
Serotiny and regeneration algorithms algorithms are based on those in
LANDIS-II Biomass Succession extension, v3.2.1, with modifications (see FireDisturbance()).
Requires the following objects in sim (and passed as sim$*):
@template FireDisturbance
fireDamageTable
fireRSORas (Critical spread rate for crowning)
fireROSRas (Equilibrium Head Fire Rate of Spread)
fireCFBRas (Crown Fraction Burnt)
minRelativeB
Rasters of fire behaviour properties (fireRSORas, fireROSRas and fireCFBRas)
can be calculated using the cffdrs package.
The species table must contain the columns:
firetolerance – fire tolerance value relative to other species.
longevity – maximum species age
sexualmature – age at sexual maturity
postfireregen – post-fire regeneration strategy ("serotiny", "resprout" or "none")
shadetolerance – shade tolerance value relative to other species.
resproutage_min, resproutage_max – minimum and maximum age at which species can repsrout
resproutprob – probability of resporuting success (before light/shade suitability is assessed)
PeatlandThermokarst() simulates tree cohort survival/mortality after
peatland permafrost thermokarst. The level of mortality depends on species
tolerance to thermokarst, determined by the thermokarsttol trait column
in the species traits table. At the moment, this level of tolerance is used
as the proportion of a cohort biomass that survives (is kept) when a pixel undergoes
thermokarst. This is similar to the partial disturbance effects used in LANDIS-II Biomass
Harvest v4.0. Requires the following objects in sim (and passed as sim$*):
thawedPixIDs
treedThawedPixelTableSinceLastDisp
wetlands
cohortData
pixelGroupMap
rasterToMatch
species
speciesEcoregion
inactivePixelIndex
The species table must contain the columns:
thermokarsttol – proportion of cohort biomass (B) that survives thermokarst
Scheller, R.M. & Miranda, B.R. (2015). LANDIS-II Biomass Succession v3.2 Extension – User Guide.
Scheller, R.M. & Mladenoff, D.J. (2004). A forest growth and biomass module for a landscape simulation model, LANDIS: design, validation, and application. Ecological Modelling, 180, 211–229.
Sturtevant, B.R., Miranda, B.R., Scheller, R.M. & Shinneman, D. (2018). LANDIS-II Dynamic Fire System Extension v3.0 – User Guide.
Scheller, R.M. & Domingo, J.B. (2021). LANDIS-II Biomass Harvest v4.4 Extension – User Guide
The function will create sensible parameter ranges for A, k and p parameters
of the Chapman-Richards and Logistic growth curves and attempt to run a
forward step-AIC procedure to add covariates to the linear component of the
model (on the A parameter – the asymptote). The maximum number of covariates
to add is determined by maxNoCoefs.
fitNLMModels( sp = NULL, predictorVarsData, sppVarsB, predictorVars, predictorVarsCombos = NULL, maxNoCoefs = 4, doFwdSelection = FALSE, sampleSize = 3000, Ntries = 2000, maxCover = 1L, models = c("CR", "Logistic"), modelOutputsPrev = NULL, randomStarts = FALSE, lowerBounds = TRUE, upperBounds = TRUE, nbWorkers = 1L )fitNLMModels( sp = NULL, predictorVarsData, sppVarsB, predictorVars, predictorVarsCombos = NULL, maxNoCoefs = 4, doFwdSelection = FALSE, sampleSize = 3000, Ntries = 2000, maxCover = 1L, models = c("CR", "Logistic"), modelOutputsPrev = NULL, randomStarts = FALSE, lowerBounds = TRUE, upperBounds = TRUE, nbWorkers = 1L )
sp |
species name – only used for messaging. |
predictorVarsData |
a |
sppVarsB |
s |
predictorVars |
character vector of predictor variables to be included
in the linear component of the model affecting the asymptote (need to correspond to
|
predictorVarsCombos |
a list of sets of covariates in |
maxNoCoefs |
how many covariates from |
doFwdSelection |
should covariates be added one at a time to the
linear component of the model? If |
sampleSize |
how many data points should be randomly sampled to fit the model?
If |
Ntries |
how many times should the models be fit with new randomly
generated starting values? Only used if |
maxCover |
numeric. Value indicating maximum cover/dominance. |
models |
character vector of models to fit. Only Chapman-Richards ('CR') and 'Logistic' can be chosen at the moment. |
modelOutputsPrev |
previous outputs of |
randomStarts |
logical. Should random starting values of A, k and p non-linear parameters be picked from a range sensible values, or should all combinations of values within this range be used? If FALSE, the default, the starting values are spaced at regular intervals within an acceptable range for each parameter – 20 values for A, 10 for k and p – and all combinations are used (2000 starting values in total). Parameter ranges are estimated from data following Fekedulegn et al. (1999) as follows:
|
lowerBounds |
a named vector of lower parameter boundaries. If |
upperBounds |
a named vector of upper parameter boundaries. If |
nbWorkers |
integer. If > 1, the number of workers to use in |
Canada administrative boundaries
gadm_canada(src = "stats_can", dst_path = tempdir())gadm_canada(src = "stats_can", dst_path = tempdir())
src |
Character. One of "stats_can" or (if |
dst_path |
Character specifying the path to download to. |
pixelGroups to a pixelDataTable objectGenerates unique groupings of a data.table object where one or more rows can
all belong to the same pixelIndex. Pixel groups will be identical pixels based
on unique combinations of columns.
generatePixelGroups( pixelDataTable, maxPixelGroup, columns = c("ecoregionGroup", "speciesCode", "age", "B") )generatePixelGroups( pixelDataTable, maxPixelGroup, columns = c("ecoregionGroup", "speciesCode", "age", "B") )
pixelDataTable |
A |
maxPixelGroup |
A length 1 numeric indicating the current maximum |
columns |
A character vector of column names to use as part of the generation of unique
combinations of features. Default is |
Returns a vector of pixelGroup in the original order of the input pixelDataTable.
This should likely be added to the pixelDataTable object immediately.
Extracts points from raster layers using the original raster layer projection.
genericExtract(x, y, field = NULL, ...)genericExtract(x, y, field = NULL, ...)
x |
a raster or polygon object ( |
y |
a points or polygons spatial object ( |
field |
character. The field(s) to extract when x is a polygon.
If |
... |
passed to |
If x and y are both polygons, extract often outputs NA due to misalignments
(this can happen even when x == y), even after snap(y, x).
To circumvent this problem, intersect is used internally and,
if the extract argument fun is passed, it is applied to values of y per polygon ID of x.
a data.table with extracted values and an ID column of y point IDs
pixelGroups in partially disturbed pixels.Re-generate new pixelGroups in partially disturbed pixels.
genPGsPostDisturbance( cohortData, pixelGroupMap, disturbedPixelTable, disturbedPixelCohortData, colsForPixelGroups = LandR::columnsForPixelGroups(), doAssertion = getOption("LandR.assertions", TRUE) )genPGsPostDisturbance( cohortData, pixelGroupMap, disturbedPixelTable, disturbedPixelCohortData, colsForPixelGroups = LandR::columnsForPixelGroups(), doAssertion = getOption("LandR.assertions", TRUE) )
cohortData |
|
pixelGroupMap |
|
disturbedPixelTable |
|
disturbedPixelCohortData |
a |
colsForPixelGroups |
character. |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
This function regenerates pixelGroups in situations where
disturbances are not stand-replacing and create survivor and dead
cohorts in some, but potentially not all, pixels of a pixelGroup. This is
necessary to prevent reintroducing dead cohorts that were not affected
in the other pixels of the same, original, pixelGroup.
ATTENTION This function alone will not generate final pixelGroups,
and will likely need to be followed by an updateCohortData run.
The function:
creates a table of undisturbed pixels, and disturbed pixels with dead and surviving cohorts
but not new cohorts (e.g. from serotiny/resprouting) – these are added by updateCohortData;
generates pixelGroups considering these dead and surviving cohorts – this ensures that
we account for cohorts that died in some but not all pixels of a given pixelGroup;
then removes dead cohorts (as they should not be in tables for downstream
functions like updateCohortData) and recalculates pixelGroups – this ensures that
pixels that became similar/dissimilar after the death of some cohorts can form new pixelGroups.
a named list with:
a cohortData table with the updated pixelGroups, as well as
survivor cohorts, but not dead cohorts.
a pixelGroupMap with the updated pixelGroups in disturbed pixels
Biomass_core moduleprepSpeciesTable
getSpeciesTable(url = NULL, dPath = tempdir(), cacheTags = NULL) prepSpeciesTable( speciesTable, speciesLayers = NULL, sppEquiv = NULL, sppEquivCol = "LandR", areas = c("BSW", "BP", "MC") )getSpeciesTable(url = NULL, dPath = tempdir(), cacheTags = NULL) prepSpeciesTable( speciesTable, speciesLayers = NULL, sppEquiv = NULL, sppEquivCol = "LandR", areas = c("BSW", "BP", "MC") )
url |
If NULL (the default), uses one from D. Cyr's LANDIS-II files: https://github.com/dcyr/LANDIS-II_IA_generalUseFiles/blob/master/speciesTraits.csv). |
dPath |
The destination path. |
cacheTags |
User tags to pass to |
speciesTable |
A species traits table, with at least the following columns:
|
speciesLayers |
Deprecated. |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
areas |
A character vector of areas to use. Can be one or more of
|
getSpeciesTable() returns a data.table with columns LandisCode, Area, Longevity, Maturity, Shade, Fire, SeedEffDist, SeedMaxDist, VegProb, MinAgeVeg, MaxAgeVeg, PostFireRegen, LeafLongevity, WoodDecayRate, MortalityCurve, GrowthCurve, LeafLignin, HardSoft.
See assertSpeciesTableRaw() for expected column data types.
prepSpeciesTable() returns a data.table with columns species, Area, longevity, sexualmature, shadetolerance, firetolerance, seeddistance_eff, seeddistance_max, resproutprob, resproutage_min, resproutage_max, postfireregen, leaflongevity, wooddecayrate, mortalityshape, growthcurve, leafLignin, hardsoft.
See assertSpeciesTable() for expected column data types.
This one is tailored to Canadian forests
Download and prepare raster fire data from NFI
getWildfire_NFI(dPath, rasterToMatch, url = NULL)getWildfire_NFI(dPath, rasterToMatch, url = NULL)
dPath |
destination path for archive |
rasterToMatch |
A |
url |
location from which to download the wildfire raster layer(s) |
a raster with values representing fire year 1985-2015
Plots a maximum biomass estimated at maximum 'cover' (or dominance) levels as a function of age.
ggplotMLL_maxB( mll, data, maxCover = 1L, xCovar = "age", plotTitle = NULL, nonLinModelQuoted, linModelQuoted, averageCovariates = TRUE, observedAge = FALSE, plotCIs = TRUE )ggplotMLL_maxB( mll, data, maxCover = 1L, xCovar = "age", plotTitle = NULL, nonLinModelQuoted, linModelQuoted, averageCovariates = TRUE, observedAge = FALSE, plotCIs = TRUE )
mll |
a named list with outputs of an |
data |
data for estimation of maximum biomass. Should contain at least
an 'age' column. Note that other covariates will be averaged and 'cover' values
will be replaced with the maximum cover value ( |
maxCover |
numeric. Value indicating maximum cover/dominance. |
xCovar |
the variable shown in the x axis. Defaults to |
plotTitle |
character. Passed to |
nonLinModelQuoted |
a named list of non-linear equations as a |
linModelQuoted |
A named list of lists of linear equations/modes relating each
parameter ('A', 'p' and 'k') with a set of covariates. A |
averageCovariates |
should covariates other than age/cover be averaged for
biomass predictions? If not, for each age (at maximum cover) there will be as
many predictions as other covariate values. If |
observedAge |
should observed age values be used, or should these be generated
as |
plotCIs |
should confidence intervals be calculated and plotted? |
BioSIM
Install BioSIM to retrieve climate and other projections using BioSIM
installBioSIM(lib)installBioSIM(lib)
lib |
character vector giving the library directories where to
install the packages. Recycled as needed. If missing, defaults to
the first element of |
Simulate seed dispersal using user defined function. This is a "receiving pixel" focused
dispersal approach.
It is the "potentially receiving" cell that looks around itself for potential seed sources.
If it finds a single seed source, that passes the probability function described by the
dispersalFn.
If this passes a comparison to a uniform random draw, then the receiving cell is deemed to have
a "successful" dispersal for that species.
This function can therefore only be used for a relatively specific situation
where there is a yes/no returned for each potential receiving cell, i.e., not abundance.
This function is also not cumulative, i.e,. there is no higher abundance of seeds received if
a receiving cell has lots of seed sources around it vs. a single seed source.
The difference will come with a higher probability of successfully receiving a "seed".
LANDISDisp( dtSrc, dtRcv, pixelGroupMap, speciesTable, dispersalFn = Ward, b = 0.01, k = 0.95, plot.it = FALSE, successionTimestep, verbose = getOption("LandR.verbose", TRUE), useCpp = getOption("LandR.LANDISDisp.useCpp", TRUE), ... )LANDISDisp( dtSrc, dtRcv, pixelGroupMap, speciesTable, dispersalFn = Ward, b = 0.01, k = 0.95, plot.it = FALSE, successionTimestep, verbose = getOption("LandR.verbose", TRUE), useCpp = getOption("LandR.LANDISDisp.useCpp", TRUE), ... )
dtSrc |
data.table |
dtRcv |
data.table |
pixelGroupMap |
A |
speciesTable |
A species traits table, with at least the following columns:
|
dispersalFn |
An expression that can take a "dis" argument. See details. Default is "Ward" (temporarily unused, as it is hard coded inside Rcpp function) |
b |
LANDIS Ward seed dispersal calibration coefficient (set to 0.01 in LANDIS) |
k |
LANDIS Ward seed dispersal the probability that seed will disperse within the effective distance (e.g., 0.95) |
plot.it |
Deprecated. If |
successionTimestep |
The time between successive seed dispersal events. In LANDIS-II, this is called "Succession Timestep". |
verbose |
Controls message output. Defaults to |
useCpp |
Logical. If |
... |
Additional parameters. Currently none. |
dispersalFn (temporarily unused as code is converted to Rcpp – the default dispersalFn
is hard coded within the spiralSeedDispersal function that uses C++) must be an expression
that returns a probability distribution.
Because it is a dispersal kernel, it must be a probability distribution.
The expression that can take an argument named "dis" (without quotes) as this will be
calculated internally and represents the distance from the initial (receiving) pixel
and all active pixels within that cluster of active pixels.
LandR includes the Ward() kernel as defined in the LANDIS-II documentation.
The spiral inner loop is implemented in C++ (via Rcpp) and is on by
default; it produces bit-identical output to the previous R implementation
under a fixed seed, but is typically ~3x faster end-to-end on
landscape-scale inputs (and uses dramatically less memory by replacing the
per-cell-by-species source matrix with a per-pixelGroup species bitmask).
To fall back to the R reference (e.g., for debugging), pass
useCpp = FALSE or set options(LandR.LANDISDisp.useCpp = FALSE).
A numeric vector of raster pixel indices, in the same resolution and extent as
seedSrc raster.
Eliot McIntire
if (require("googledrive")) { seed <- sample(1e6, 1) set.seed(seed) library(data.table) # keep this here for interactive testing with a larger raster rasterTemplate <- reproducible::rasterRead(terra::ext(0, 2500, 0, 2500), res = 100) # make a pixelGroupMap pgs <- 4 # make even just because of approach below requires even pixelGroupMap <- SpaDES.tools::randomPolygons(rasterTemplate, numTypes = pgs) pixelGroupMap[1:100] <- NA # emulate a mask at the start # Make a receive pixels table -- need pixelGroup and species nSpecies <- 3 maxNSpeciesPerPixel <- min(5, nSpecies) rcvSpByPG <- lapply(seq_len(pgs / 2), function(pg) { data.table(speciesCode = sample(nSpecies, size = sample(maxNSpeciesPerPixel, 1))) }) seedReceive <- rbindlist(rcvSpByPG, idcol = "pixelGroup") # Make a source pixels table -- need pixelGroup and species srcSpByPG <- lapply(seq_len(pgs / 2), function(pg) { data.table(speciesCode = sample(nSpecies, size = sample(maxNSpeciesPerPixel, 1))) }) seedSource <- rbindlist(srcSpByPG, idcol = "pixelGroup") # make source pixels not same pixelGroups as receive seedSource[, pixelGroup := pixelGroup + pgs / 2] # Get a species table -- if using in Canada, can use this destPath <- file.path(tempdir(), "ex_LANDISDisp") speciesTable <- getSpeciesTable(dPath = destPath) speciesTable <- speciesTable[Area == "BSW"] speciesTable[, speciesCode := as.factor(LandisCode)] speciesTable[, seeddistance_eff := SeedEffDist] speciesTable[, seeddistance_max := SeedMaxDist] speciesTable <- speciesTable speciesTable <- data.table(speciesTable)[, speciesCode := seq_along(LandisCode)] seedReceiveFull <- speciesTable[seedReceive, on = "speciesCode"] output <- LANDISDisp( dtRcv = seedReceiveFull, plot.it = interactive(), dtSrc = seedSource, speciesTable = speciesTable, pixelGroupMap, verbose = TRUE, successionTimestep = 10 ) # Summarize output[, .N, by = speciesCode] ## Plot the maps if (interactive()) { library(quickPlot) clearPlot() spMap <- list() spMap$pixelGroupMap <- pixelGroupMap for (sppp in unique(output$speciesCode)) { spppChar <- paste0("Sp_", sppp) spMap[[spppChar]] <- reproducible::rasterRead(pixelGroupMap) ss <- unique(seedSource[speciesCode == sppp], on = c("pixelGroup", "speciesCode")) spMap[[spppChar]][pixelGroupMap[] %in% ss$pixelGroup] <- 1 receivable <- reproducible::rasterRead(pixelGroupMap) srf <- unique(seedReceiveFull[speciesCode == sppp], on = c("pixelGroup", "speciesCode")) receivable[pixelGroupMap[] %in% srf$pixelGroup] <- 1 forest <- which(!is.na(pixelGroupMap[])) src <- which(!is.na(spMap[[spppChar]][])) recvable <- which(!is.na(receivable[])) rcvd <- output[speciesCode == sppp][["pixelIndex"]] spMap[[spppChar]][forest] <- 0 spMap[[spppChar]][recvable] <- 2 spMap[[spppChar]][src] <- 1 spMap[[spppChar]][rcvd] <- 3 spMap[[spppChar]][intersect(src, rcvd)] <- 4 levels(spMap[[spppChar]]) <- data.frame( ID = 0:4, type = c( "OtherForest", "Source", "Didn't receive", "Received", "Src&Rcvd" ) ) } Plot(spMap, cols = "Set2") # A summary rr <- apply(rast(spMap)[[-1]][] + 1, 2, tabulate) rownames(rr) <- raster::levels(spMap[[2]])[[1]][, "type"][1:NROW(rr)] # next line only works if there are some places that are both source and potential to receive # rr <- rbind(rr, propSrcRcved = round(rr[5,]/ (rr[5,]+rr[2,]), 2)) } }if (require("googledrive")) { seed <- sample(1e6, 1) set.seed(seed) library(data.table) # keep this here for interactive testing with a larger raster rasterTemplate <- reproducible::rasterRead(terra::ext(0, 2500, 0, 2500), res = 100) # make a pixelGroupMap pgs <- 4 # make even just because of approach below requires even pixelGroupMap <- SpaDES.tools::randomPolygons(rasterTemplate, numTypes = pgs) pixelGroupMap[1:100] <- NA # emulate a mask at the start # Make a receive pixels table -- need pixelGroup and species nSpecies <- 3 maxNSpeciesPerPixel <- min(5, nSpecies) rcvSpByPG <- lapply(seq_len(pgs / 2), function(pg) { data.table(speciesCode = sample(nSpecies, size = sample(maxNSpeciesPerPixel, 1))) }) seedReceive <- rbindlist(rcvSpByPG, idcol = "pixelGroup") # Make a source pixels table -- need pixelGroup and species srcSpByPG <- lapply(seq_len(pgs / 2), function(pg) { data.table(speciesCode = sample(nSpecies, size = sample(maxNSpeciesPerPixel, 1))) }) seedSource <- rbindlist(srcSpByPG, idcol = "pixelGroup") # make source pixels not same pixelGroups as receive seedSource[, pixelGroup := pixelGroup + pgs / 2] # Get a species table -- if using in Canada, can use this destPath <- file.path(tempdir(), "ex_LANDISDisp") speciesTable <- getSpeciesTable(dPath = destPath) speciesTable <- speciesTable[Area == "BSW"] speciesTable[, speciesCode := as.factor(LandisCode)] speciesTable[, seeddistance_eff := SeedEffDist] speciesTable[, seeddistance_max := SeedMaxDist] speciesTable <- speciesTable speciesTable <- data.table(speciesTable)[, speciesCode := seq_along(LandisCode)] seedReceiveFull <- speciesTable[seedReceive, on = "speciesCode"] output <- LANDISDisp( dtRcv = seedReceiveFull, plot.it = interactive(), dtSrc = seedSource, speciesTable = speciesTable, pixelGroupMap, verbose = TRUE, successionTimestep = 10 ) # Summarize output[, .N, by = speciesCode] ## Plot the maps if (interactive()) { library(quickPlot) clearPlot() spMap <- list() spMap$pixelGroupMap <- pixelGroupMap for (sppp in unique(output$speciesCode)) { spppChar <- paste0("Sp_", sppp) spMap[[spppChar]] <- reproducible::rasterRead(pixelGroupMap) ss <- unique(seedSource[speciesCode == sppp], on = c("pixelGroup", "speciesCode")) spMap[[spppChar]][pixelGroupMap[] %in% ss$pixelGroup] <- 1 receivable <- reproducible::rasterRead(pixelGroupMap) srf <- unique(seedReceiveFull[speciesCode == sppp], on = c("pixelGroup", "speciesCode")) receivable[pixelGroupMap[] %in% srf$pixelGroup] <- 1 forest <- which(!is.na(pixelGroupMap[])) src <- which(!is.na(spMap[[spppChar]][])) recvable <- which(!is.na(receivable[])) rcvd <- output[speciesCode == sppp][["pixelIndex"]] spMap[[spppChar]][forest] <- 0 spMap[[spppChar]][recvable] <- 2 spMap[[spppChar]][src] <- 1 spMap[[spppChar]][rcvd] <- 3 spMap[[spppChar]][intersect(src, rcvd)] <- 4 levels(spMap[[spppChar]]) <- data.frame( ID = 0:4, type = c( "OtherForest", "Source", "Didn't receive", "Received", "Src&Rcvd" ) ) } Plot(spMap, cols = "Set2") # A summary rr <- apply(rast(spMap)[[-1]][] + 1, 2, tabulate) rownames(rr) <- raster::levels(spMap[[2]])[[1]][, "type"][1:NROW(rr)] # next line only works if there are some places that are both source and potential to receive # rr <- rbind(rr, propSrcRcved = round(rr[5,]/ (rr[5,]+rr[2,]), 2)) } }
Convert cohortData into landcover class based on leading species and density.
Classify each pixel as "broadleaf", "mixedwood", or "conifer";
Define the openness of each pixel as "dense", "open", or "sparse";
Combine these into cover classes for forested cells.
lccMapGenerator( cohortData, pixelGroupMap, lccTable = NULL, deciduousCoverDiscount = 0.8418911, vegLeadingProportion = 0.75, decidousSpp = NULL, rstLCC )lccMapGenerator( cohortData, pixelGroupMap, lccTable = NULL, deciduousCoverDiscount = 0.8418911, vegLeadingProportion = 0.75, decidousSpp = NULL, rstLCC )
cohortData |
A |
pixelGroupMap |
A |
lccTable |
|
deciduousCoverDiscount |
numeric between 0 and 1 that translates %% cover to %% biomass.
It assumes all hardwoods are equivalent; all softwoods are equivalent;
and that %% cover of hardwoods will be an overesimate of the %%% biomass of hardwoods.
Hardwoods in Canada have a much wider canopy than softwoods.
E.g., 30%% cover of hardwoods might translate to 20%% biomass of hardwoods.
NB: the default |
vegLeadingProportion |
Numeric between 0-1, determining the relative biomass threshold a species needs to pass to be considered "leading". |
decidousSpp |
character vector of deciduous species names. If not supplied, will
attempt to match deciduous species names in sppEquivalencies_CA to those in |
rstLCC |
landcover raster |
By default, landcover classes are coded to match the Land Cover Map of Canada 2005 at 250m (Latifovic & Pouliot, 2005).
Code modified from https://github.com/tati-micheletti/caribouRSF_NT/blob/main/R/makeLCCfromCohortData.R.
raster of the same type as pixelGroupMap, containing LCC values
Sparse classes: Even though the default LCC2005 input does not have "mixed sparse" or "broadleaf sparse", these are likely to be produced in simulations, starting from "conifer sparse" sites (i.e. broadleaf trees might grow on these sites, and eventually convert these into mixed or broadleaf sparse sites).
Tati Micheletti and Alex Chubaty
Latifovic, R. & Pouliot, D. (2005). Multitemporal land cover mapping for Canada: methodology and products. Canadian Journal of Remote Sensing, 31, 347–363.
Loads CASFRIv4 data specifically supplied for the LandWeb project
loadCASFRI( CASFRIRas, attrFile, headerFile, sppEquiv, sppEquivCol, type = c("cover", "age") )loadCASFRI( CASFRIRas, attrFile, headerFile, sppEquiv, sppEquivCol, type = c("cover", "age") )
CASFRIRas |
|
attrFile |
character string specifying a CASFRI attribute filename |
headerFile |
character string specifying a CASFRI header filename |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
type |
Character string. Either |
list with named elements: CASFRIattrLong and CASFRIdt (both data.tables)
TODO: description needed
loadkNNSpeciesLayers( dPath, rasterToMatch = NULL, studyArea = NULL, sppEquiv, year = 2001, knnNamesCol = "KNN", sppEquivCol = "Boreal", thresh = 10, url = NULL, ... )loadkNNSpeciesLayers( dPath, rasterToMatch = NULL, studyArea = NULL, sppEquiv, year = 2001, knnNamesCol = "KNN", sppEquivCol = "Boreal", thresh = 10, url = NULL, ... )
dPath |
path to the data directory |
rasterToMatch |
A |
studyArea |
A |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
year |
which year's layers should be retrieved? One of 2001 (default) or 2011. |
knnNamesCol |
character string indicating the column in |
sppEquivCol |
the column name to use from |
thresh |
the minimum percent cover a species must have (per pixel) to be considered present in the study area. Defaults to 10. |
url |
the source url for the data, default is KNN 2011 dataset (https://ftp.maps.canada.ca/pub/nrcan_rncan/Forests_Foret/canada-forests-attributes_attributs-forests-canada/2011-attributes_attributs-2011/) |
... |
Additional arguments passed to |
A raster stack of percent cover layers by species.
Load SCANFI species layers from online data repository
loadSCANFISpeciesLayers( dPath, rasterToMatch = NULL, studyArea = NULL, sppEquiv, year = 2020, dataVersion = "V2", SCANFINamesCol = "SCANFI", sppEquivCol = "SCANFI", thresh = 10, url = NULL, ... )loadSCANFISpeciesLayers( dPath, rasterToMatch = NULL, studyArea = NULL, sppEquiv, year = 2020, dataVersion = "V2", SCANFINamesCol = "SCANFI", sppEquivCol = "SCANFI", thresh = 10, url = NULL, ... )
dPath |
path to the data directory |
rasterToMatch |
A |
studyArea |
A |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
year |
data year for SCANFI data. 2000, 2010, and 2020 possible for V1. 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020 (default), 2025 possible for V2. |
dataVersion |
Character. SCANFI product version for data. Default is currently V2. V1 also available. |
SCANFINamesCol |
character string indicating the column in |
sppEquivCol |
the column name to use from |
thresh |
the minimum percent cover a species must have (per pixel) to be considered present in the study area. Defaults to 10. |
url |
a source url for the data |
... |
Additional arguments passed to |
A raster stack of percent cover layers by species.
cohortData tableTakes a single data.table input, which has the following columns in addition to
others that will be labelled with species name, and contain percent cover of each:
makeAndCleanInitialCohortData( inputDataTable, sppColumns, imputeBadAgeModel = quote(lme4::lmer(age ~ B * speciesCode + cover * speciesCode + (1 | initialEcoregionCode))), minCoverThreshold, doAssertion = getOption("LandR.assertions", TRUE), doSubset = TRUE )makeAndCleanInitialCohortData( inputDataTable, sppColumns, imputeBadAgeModel = quote(lme4::lmer(age ~ B * speciesCode + cover * speciesCode + (1 | initialEcoregionCode))), minCoverThreshold, doAssertion = getOption("LandR.assertions", TRUE), doSubset = TRUE )
inputDataTable |
A |
sppColumns |
A vector of the names of the columns in |
imputeBadAgeModel |
statistical model used to impute ages in pixels with missing data or with cover == 0. If set to NULL no imputation will be attempted, and pixels with missing age are excluded. |
minCoverThreshold |
minimum total cover percentage necessary to consider the pixel vegetated, or a cohort present in a pixel. |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
doSubset |
Turns on/off subsetting. Defaults to |
pixelIndex (integer)
age (integer)
logAge (numeric)
initialEcoregionCode (factor)
totalBiomass (integer)
lcc (integer)
rasterToMatch (integer)
speciesCode (factor)
cover (integer)
coverOrig (integer)
B (integer)
Several data correction/imputation operations are also performed. Namely, age is imputed
in pixels where age data is missing (but not cover) and where cover == 0 but age > 0,
total biomass is zeroed if age == 0, and age is zeroed if biomass == 0.
a cohortData data.table with attribute "imputedPixID"
(a vector of pixel IDs that suffered imputation).
Eliot McIntire
biomassMap
This is a function that creates the biomassMap raster used for simulations in
Biomass_core module, using estimated data based on rawBiomassMap contained in
pixelCohortData.
makeBiomassMap(pixelCohortData, rasterToMatch)makeBiomassMap(pixelCohortData, rasterToMatch)
pixelCohortData |
The full |
rasterToMatch |
A |
The biomassMap, a raster of total stand biomass per pixel.
cohortData table, while modifying the temporary
pixelCohortData that will be used to prepare other files.Takes a pixelCohortData table (see makeAndCleanInitialCohortData),
the speciesEcoregion list and returns a modified pixelCohortData and
the cohortData tables to be used in the simulation.
This function mainly removes unnecessary columns from pixelCohortData,
subsets pixels with biomass > 0, generates pixelGroups,
and adds ecoregionGroup and totalBiomass columns to pixelCohortData.
cohortData is then created by subsetting unique combinations of pixelGroup and
whatever columns are listed in columnsForPixelGroups.
The resulting cohortData table has the following columns:
speciesCode (factor)
ecoregionGroup (factor)
pixelGroup (integer)
age (integer)
B (integer)
makeCohortDataFiles( pixelCohortData, columnsForPixelGroups, speciesEcoregion, pixelGroupBiomassClass, pixelGroupAgeClass, minAgeForGrouping = 0, rmImputedPix = FALSE, imputedPixID, pixelFateDT )makeCohortDataFiles( pixelCohortData, columnsForPixelGroups, speciesEcoregion, pixelGroupBiomassClass, pixelGroupAgeClass, minAgeForGrouping = 0, rmImputedPix = FALSE, imputedPixID, pixelFateDT )
pixelCohortData |
The full |
columnsForPixelGroups |
Default columns that define pixel groups |
speciesEcoregion |
A |
pixelGroupBiomassClass |
Integer. When assigning |
pixelGroupAgeClass |
Integer. When assigning |
minAgeForGrouping |
Minimum age for regrouping. This may be because there is a source of ages for young stands/trees that is very reliable, such as a fire database. Ages below this will not be grouped together. Defaults to -1, meaning treat all ages equally. If this is related to known ages from a high quality database, then use age of the oldest trees in that database. |
rmImputedPix |
Should imputed pixels be removed |
imputedPixID |
a vector of IDs of pixels that suffered data imputation. |
pixelFateDT |
A |
A list with a modified pixelCohortData, cohortData, and pixelFateDT
data.tables.
ecoregionMapis a raster of all the unique groupings.
makeDummyEcoregionMap(rasterToMatch) makeDummyRawBiomassMap(rasterToMatch) makeDummyStandAgeMap(rawBiomassMap) makeDummyRstLCC(rasterToMatch) makeDummyEcoregionFiles(ecoregionMap, rstLCC, rasterToMatch)makeDummyEcoregionMap(rasterToMatch) makeDummyRawBiomassMap(rasterToMatch) makeDummyStandAgeMap(rawBiomassMap) makeDummyRstLCC(rasterToMatch) makeDummyEcoregionFiles(ecoregionMap, rstLCC, rasterToMatch)
rasterToMatch |
A |
rawBiomassMap |
a |
ecoregionMap |
The |
rstLCC |
raster of land-cover class, e.g., LCC2005 |
rawBiomassMap is a raster of "raw" total stand biomass per pixel,
with values between 100 and 20000 g/m^2.
standAgeMap is a raster of stand age per pixel (where biomass exists)
with values between 1 and 300 years.
rstLCC is a raster land-cover class per pixel, with values between 1 and 5 that have no
correspondence to any real land-cover classes.
ecoregionFiles uses dummy versions of ecoregionMap and rstLCC
to create a list with two objects: the ecoregionMap and a table summarizing its
information per pixelID.
See ecoregionProducer (it uses ecoregionProducer internally).
a RasterLayer object or, in the case of makeDummyEcoregionFiles, a list.
ecoregion tableThis function creates a table containing pixel-wise ecoregion codes and whether they
are "active" (have biomass > 0) or not for simulation. Unlike ecoregionProducer,
this function creates the ecoregion table from pixel information contained in
pixelCohortData
makeEcoregionDT(pixelCohortData, speciesEcoregion)makeEcoregionDT(pixelCohortData, speciesEcoregion)
pixelCohortData |
The full |
speciesEcoregion |
A |
A data.table with ecoregion codes and their active status per pixelID.
ecoregionMap rasterCreates a raster of ecoregion codes per pixel.
Unlike ecoregionProducer, this fills the raster with pixel information contained in
pixelCohortData.
makeEcoregionMap(ecoregionFiles, pixelCohortData)makeEcoregionMap(ecoregionFiles, pixelCohortData)
ecoregionFiles |
A list with two objects: the |
pixelCohortData |
The full |
A raster with ecoregion codes.
minRelativeB tableThe table contains expert-based values for minimum relative biomass of each shade tolerance class (the minimum relative biomass a cohort with a given shade tolerance should have to be able to germinate), in each unique ecoregion group. All ecoregion groups currently have the same values.
makeMinRelativeB(pixelCohortData)makeMinRelativeB(pixelCohortData)
pixelCohortData |
The full |
a data.frame of min relative biomass values per ecoregion group.
makePickellStackTODO: description and title needed
makePickellStack(PickellRaster, sppEquiv, sppEquivCol, destinationPath)makePickellStack(PickellRaster, sppEquiv, sppEquivCol, destinationPath)
PickellRaster |
TODO: description needed |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
destinationPath |
path to data directory where objects will be downloaded or saved to |
TODO: description needed
makePixelGroupMap
Create the makePixelGroupMap raster containing pixelGroups in pixelCohortData.
makePixelGroupMap(pixelCohortData, rasterToMatch)makePixelGroupMap(pixelCohortData, rasterToMatch)
pixelCohortData |
The full |
rasterToMatch |
A |
a raster with pixel groups
pixelTable from biomass, age, land-cover and species cover dataMake pixelTable from biomass, age, land-cover and species cover data
makePixelTable( speciesLayers, standAgeMap, ecoregionFiles, biomassMap, rasterToMatch, rstLCC, printSummary = TRUE, doAssertion = getOption("LandR.assertions", TRUE) )makePixelTable( speciesLayers, standAgeMap, ecoregionFiles, biomassMap, rasterToMatch, rstLCC, printSummary = TRUE, doAssertion = getOption("LandR.assertions", TRUE) )
speciesLayers |
A |
standAgeMap |
A |
ecoregionFiles |
A list with two objects: the |
biomassMap |
raster of total stand biomass in t/ha. Biomass units are converted to g/m^2. |
rasterToMatch |
A |
rstLCC |
raster of land-cover class, e.g., LCC2005 |
printSummary |
Logical. If |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
A data.table as many rows as non-NA pixels in rasterToMath and
the columns containing pixel data from the input raster layers, with
biomass in g/m^2.
speciesEcoregion
Use statistically estimated maxB, maxANPP and establishment probabilities
to generate speciesEcoregion table.
makeSpeciesEcoregion( cohortDataBiomass, cohortDataShort, cohortDataShortNoCover, species, modelCover, modelBiomass, successionTimestep, currentYear )makeSpeciesEcoregion( cohortDataBiomass, cohortDataShort, cohortDataShortNoCover, species, modelCover, modelBiomass, successionTimestep, currentYear )
cohortDataBiomass |
a subset of |
cohortDataShort |
a subset of |
cohortDataShortNoCover |
a subset of |
species |
a
|
modelCover |
statistical model of species presence/absence |
modelBiomass |
statistical model of species biomass |
successionTimestep |
The time between successive seed dispersal events. In LANDIS-II, this is called "Succession Timestep". |
currentYear |
|
See Details.
establishprobThis section takes the cover as estimated from the mature tree cover and
partitions it between resprouting and seeds Unfortunately, establishment by
seed is not independent of resprouting, i.e., some pixels would have both
Since we don't know the level of independence, we can't correctly assess how
much to discount the two. If there is resprouting > 0, then this is the
partitioning:
establishprob = f(establishprob + resproutprob + jointEstablishProbResproutProb)
If jointEstablishProbResproutProb is 0, then these are independent events
and the total cover probability can be partitioned easily between seeds and
resprout. This is unlikely ever to be the case. We are picking 50% overlap as
a number that is better than 0 (totally independent probabilities, meaning no
pixel has both seeds and resprout potential) and 100% overlap (totally
dependent probabilities, i.e., every pixel where there is seeds will also be
a pixel with resprouting) This is expressed with the "* 0.5" in the code.
#' @return
A speciesEcoregion data.table with added columns for parameters
maxB, maxANPP and establishprob
makeVegTypeMap is a wrapper around vegTypeMapGenerator
that works from a species stack of percent cover.
These do not have to sum to 100%%
Downloads the 2011 kNN species cover layers from the Canadian Forestry Service, National Inventory System, for validation.
makeVegTypeMap(speciesStack, vegLeadingProportion, mixed, ...) loadkNNSpeciesLayersValidation( dPath, rasterToMatch, studyArea, sppEquiv, knnNamesCol = "KNN", sppEquivCol, thresh = 1, url, ... ) prepSpeciesLayers_KNN2011( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... )makeVegTypeMap(speciesStack, vegLeadingProportion, mixed, ...) loadkNNSpeciesLayersValidation( dPath, rasterToMatch, studyArea, sppEquiv, knnNamesCol = "KNN", sppEquivCol, thresh = 1, url, ... ) prepSpeciesLayers_KNN2011( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... )
speciesStack |
A |
vegLeadingProportion |
Numeric between 0-1, determining the relative biomass threshold a species needs to pass to be considered "leading". |
mixed |
Deprecated. See |
... |
Additional arguments passed to |
dPath |
path to the data directory |
rasterToMatch |
A |
studyArea |
A |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
knnNamesCol |
character string indicating the column in |
sppEquivCol |
the column name to use from |
thresh |
the minimum number of pixels where the species must have
|
url |
the source url for the data, passed to |
destinationPath |
path to data directory where objects will be downloaded or saved to |
outputPath |
path to output directory |
A factor raster
A raster stack of percent cover layers by species.
minRelativeB defaults for Western Boreal Forest Canada
minRelativeBDefaults()minRelativeBDefaults()
species and speciesEcoregion tablesUpdate species and speciesEcoregion tables
modifySpeciesAndSpeciesEcoregionTable(speciesEcoregion, speciesTable)modifySpeciesAndSpeciesEcoregionTable(speciesEcoregion, speciesTable)
speciesEcoregion |
A |
speciesTable |
A species traits table, with at least the following columns:
|
a list with modified speciesEcoregion and speciesTable,
under the names "newSpeciesEcoregion" and "newSpeciesTable", respectively.
NA values in speciesLayers to zerosPixels that are NA but are inside rasterToMatch may need to be converted to 0,
as they can could still potentially be forested
NAcover2zero(speciesLayers, rasterToMatch)NAcover2zero(speciesLayers, rasterToMatch)
speciesLayers |
A |
rasterToMatch |
A |
the speciesLayers with 0 in pixels that had NA
Assess non-forested pixels based on species cover data and land-cover
nonForestedPixels( speciesLayers, omitNonTreedPixels, forestedLCCClasses, rstLCC )nonForestedPixels( speciesLayers, omitNonTreedPixels, forestedLCCClasses, rstLCC )
speciesLayers |
A |
omitNonTreedPixels |
logical. Should pixels with classes in |
forestedLCCClasses |
vector of forested land-cover classes in |
rstLCC |
raster of land-cover class, e.g., LCC2005 |
a logical vector of length ncell(rstLCC)
where TRUE indicates non-forested pixels where there is no
species cover data, or a non-forested land-cover class
Overlay different LCC data sources
overlayLCCs( LCCs, forestedList, outputLayer, NAcondition, NNcondition, remapTable = NULL, classesToReplace, availableERC_by_Sp, forestEquivalencies = NULL )overlayLCCs( LCCs, forestedList, outputLayer, NAcondition, NNcondition, remapTable = NULL, classesToReplace, availableERC_by_Sp, forestEquivalencies = NULL )
LCCs |
A named list or named |
forestedList |
A named list of same length and names as |
outputLayer |
A character string that matches one of the named elements
in |
NAcondition |
The condition when a pixel is deemed to be |
NNcondition |
The 'nearest-neighbour' condition; i.e., the condition when
a nearest-neighbour search is done to fill in the pixel with forested type.
Given as a character string of a vectorized logical statement that will be
parsed within the |
remapTable |
|
classesToReplace |
Passed to |
availableERC_by_Sp |
Passed to |
forestEquivalencies |
A |
Eliot McIntire and Alex Chubaty
Overlays rasters of different data resolution by filling in gaps in the highest resolution raster with data available in lowest resolution one. If only high or low resolution data are available, it will use it without attempting to overlay.
overlayStacks( highQualityStack, lowQualityStack, outputFilenameSuffix = "overlay", destinationPath )overlayStacks( highQualityStack, lowQualityStack, outputFilenameSuffix = "overlay", destinationPath )
highQualityStack |
high quality list/stack of rasters (will be used preferentially) |
lowQualityStack |
low quality list/stack of rasters
(will be used to fill |
outputFilenameSuffix |
file suffix to save raster if there was overlaying.
Defaults to |
destinationPath |
path to data directory where objects will be downloaded or saved to |
Plots the maximum biomass estimates along an age gradient as a function of another target covariate, with all others held at average values.
partialggplotMLL_maxB( mll, data, targetCovar = "cover", maxCover = 1, fixMaxCover = TRUE, xCovar = "age", showQuantiles = "allQuantiles", plotTitle = NULL, nonLinModelQuoted, linModelQuoted, fun = "mean", plotCIs = TRUE )partialggplotMLL_maxB( mll, data, targetCovar = "cover", maxCover = 1, fixMaxCover = TRUE, xCovar = "age", showQuantiles = "allQuantiles", plotTitle = NULL, nonLinModelQuoted, linModelQuoted, fun = "mean", plotCIs = TRUE )
mll |
a named list with outputs of an |
data |
data for estimation of maximum biomass. Should contain at least
an 'age' column. Note that other covariates will be averaged and 'cover' values
will be replaced with the maximum cover value ( |
targetCovar |
the covariate for which variation in maxB values will be shown per
age value. Defaults to showing how maxB values change with "cover" at any given age.
Age values are generated as |
maxCover |
numeric. Value indicating maximum cover/dominance. |
fixMaxCover |
logical. If |
xCovar |
the variable shown in the x axis. Defaults to "age". When |
showQuantiles |
controls whether quantile predictions will be shown. If
"allQuantiles", quantile values (5%, 25%, 50%, 75%, 95%) of B will be
plotted as blue lines, with their respective asymptote values (quantile values
at maximum age) as dashed lines. If "maximum" the 100% quantile will be plotted.
If "none", only the 50% quantile line (average prediction) is plotted.
Quantiles are always calculated at |
plotTitle |
character. Passed to |
nonLinModelQuoted |
a named list of non-linear equations as a |
linModelQuoted |
A named list of lists of linear equations/modes relating each
parameter ('A', 'p' and 'k') with a set of covariates. A |
fun |
passed to |
plotCIs |
should confidence intervals be calculated and plotted? |
Note that the original data, not the predicted values is shown.
This function will partition totalBiomass into each cohort.
It will discount deciduous cover, if x < 1.
partitionBiomass(x = 1, pixelCohortData)partitionBiomass(x = 1, pixelCohortData)
x |
The ratio for deciduous cover:biomass, where conifer cover:biomass = 1 |
pixelCohortData |
A full |
pixelFateDT objectCreate or amend data to a pixelFateDT object
pixelFate( pixelFateDT, fate = NA_character_, pixelsRemoved = 0, runningPixelTotal = NA_integer_ )pixelFate( pixelFateDT, fate = NA_character_, pixelsRemoved = 0, runningPixelTotal = NA_integer_ )
pixelFateDT |
A |
fate |
A character string (length 1) describing in words the change |
pixelsRemoved |
A numeric indicating how many pixels were removed due to the |
runningPixelTotal |
an optional numeric with new, running total. If not supplied,
it will be calculated from the last row of |
A pixelFateDT object, updated with one extra row.
pixelGroup and add to cohortData
Create new cohorts based on provenance table with unique pixelGroup and add to cohortData
plantNewCohorts( newPixelCohortData, cohortData, pixelGroupMap, initialB = 10, currentTime, successionTimestep, trackPlanting = FALSE )plantNewCohorts( newPixelCohortData, cohortData, pixelGroupMap, initialB = 10, currentTime, successionTimestep, trackPlanting = FALSE )
newPixelCohortData |
the cohorts that were harvested |
cohortData |
A |
pixelGroupMap |
A |
initialB |
the initial biomass of new cohorts. Defaults to ten. |
currentTime |
The current simulation time e.g., |
successionTimestep |
The time between successive seed dispersal events. In LANDIS-II, this is called "Succession Timestep". |
trackPlanting |
adds column that tracks planted cohorts if |
A data.table with a new cohortData
Plot raster objects using ggplot
plot_raster(x, title = NULL, subtitle = NULL)plot_raster(x, title = NULL, subtitle = NULL)
x |
A |
title |
character, the plot title |
subtitle |
character, the plot subtitle |
ggplot object
Plot effects on conifer-to-deciduous or deciduous-to-conifer conversions.
plotLeadingSpecies( studyAreaName, climateScenario, Nreps, years, outputDir, treeSpecies, defineLeading = .defineLeading, leadingPercentage = 0.8, treeType = NULL, rasterToMatch )plotLeadingSpecies( studyAreaName, climateScenario, Nreps, years, outputDir, treeSpecies, defineLeading = .defineLeading, leadingPercentage = 0.8, treeType = NULL, 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 |
Nreps |
the number of simulation replicates/run used to produce summary figures.
NOTE: |
years |
TODO |
outputDir |
Path specifying the directory to which outputs figures/objects should be saved. |
treeSpecies |
TODO |
defineLeading |
TODO |
leadingPercentage |
TODO |
treeType |
TODO |
rasterToMatch |
A |
list of file names corresponding to the figures and/or objects written to disk
list of filepaths corresponding to the images and/or objects written to disk
ggplot of a raster or sf object.Can be used with SpaDES.core::Plots.
plotSpatial(x, plotTitle, limits = NULL, field = NULL)plotSpatial(x, plotTitle, limits = NULL, field = NULL)
x |
|
plotTitle |
character. A title for the plot passed to |
limits |
TODO |
field |
character. If |
Create raster of leading vegetation types and Plot a bar chart summary
and a vegetation type map. NOTE: plot order will follow colors order.
plotVTM( speciesStack = NULL, vtm = NULL, vegLeadingProportion = 0.8, sppEquiv, sppEquivCol, colors, title = "Leading vegetation types" )plotVTM( speciesStack = NULL, vtm = NULL, vegLeadingProportion = 0.8, sppEquiv, sppEquivCol, colors, title = "Leading vegetation types" )
speciesStack |
A |
vtm |
An optional vegetation type map ( |
vegLeadingProportion |
Numeric between 0-1, determining the relative biomass threshold a species needs to pass to be considered "leading". |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
colors |
Named vector of colour codes, named using species names. NOTE: plot order will follow this order. |
title |
The title to use for the generated plots. |
Eliot McIntire
Prepare ecoregions objects
prepEcoregions( ecoregionRst = NULL, ecoregionLayer, ecoregionLayerField = NULL, rasterToMatchLarge, rstLCCAdj, pixelsToRm, cacheTags )prepEcoregions( ecoregionRst = NULL, ecoregionLayer, ecoregionLayerField = NULL, rasterToMatchLarge, rstLCCAdj, pixelsToRm, cacheTags )
ecoregionRst |
an optional raster object that could be passed to |
ecoregionLayer |
an |
ecoregionLayerField |
optional. The field in |
rasterToMatchLarge |
A |
rstLCCAdj |
|
pixelsToRm |
a vector of pixels to remove |
cacheTags |
|
Download, rasterize, crop, mask, and reproject Canadian national ecozones shapefile.
prepEcozonesRst( url = NULL, destinationPath, studyArea = NULL, rasterToMatch = NULL )prepEcozonesRst( url = NULL, destinationPath, studyArea = NULL, rasterToMatch = NULL )
url |
character. ecozones shapefile url. Default: http://sis.agr.gc.ca/cansis/nsdb/ecostrat/zone/ecozone_shp.zip. |
destinationPath |
path to data directory where objects will be downloaded or saved to |
studyArea |
A |
rasterToMatch |
A |
SpatRaster
Obtain an Dominant species layer for a given year from NTEMS
prepInputs_NTEMS_DominantSpecies( year = 2011, destinationPath, sppEquiv = LandR::sppEquivalencies_CA, sppEquivCol = "LandR", ... )prepInputs_NTEMS_DominantSpecies( year = 2011, destinationPath, sppEquiv = LandR::sppEquivalencies_CA, sppEquivCol = "LandR", ... )
year |
stack of species layers rasters |
destinationPath |
path to data directory where objects will be downloaded or saved to |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
... |
passed to |
a SpatRaster with dominant species
Obtain an LCC layer for a given year from NTEMS, with forest matching the FAO definition
prepInputs_NTEMS_LCC_FAO( year = 2010, disturbedCode = 240, resampleMethod = "near", ... )prepInputs_NTEMS_LCC_FAO( year = 2010, disturbedCode = 240, resampleMethod = "near", ... )
year |
stack of species layers rasters. 1984 to 2023 possible. |
disturbedCode |
value assigned to pixels that are forest per FAO definition but not in LCC year |
resampleMethod |
method used when resampling LCC layers to match |
... |
passed to |
a SpatRaster with corrected forest pixels
Reclassify non-flammable pixels that become flammable - herbaceous or shrubby - vegetation
prepInputs_NTEMS_Nonforest( rstLCC, endYear = 2019, lccToAdjust = 33, nonforestLCC = c(50, 100), ... )prepInputs_NTEMS_Nonforest( rstLCC, endYear = 2019, lccToAdjust = 33, nonforestLCC = c(50, 100), ... )
rstLCC |
input lcc layer with bare soil class that may become vegetated |
endYear |
NTEMS LCC year to use for correcting transition from bare to non-forest |
lccToAdjust |
lcc values of the bare class |
nonforestLCC |
allowable lcc values for bare to become |
... |
non-spatial arguments passed to |
a SpatRaster with non-flammable pixels corrected if they become flammable non-forest
Obtain an LCC layer for a given year from SCANFI, with forest matching the FAO definition
prepInputs_SCANFI_LCC_FAO( year = 2020, dataVersion = "V2", disturbedCode = 240, resampleMethod = "near", ... )prepInputs_SCANFI_LCC_FAO( year = 2020, dataVersion = "V2", disturbedCode = 240, resampleMethod = "near", ... )
year |
data year for SCANFI landcover data. 2000, 2010, and 2020 possible for V1. 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020, 2025 possible for V2. |
dataVersion |
Character. SCANFI product version for data. Default is currently V2. V1 also available. |
disturbedCode |
value assigned to pixels that are forest per FAO definition but not in LCC year |
resampleMethod |
method used when resampling LCC layers to match |
... |
passed to |
a SpatRaster with corrected forest pixels
Defaults to using 3 arcmin DEM of Canada in lonlat.
prepInputsCanDEM(studyArea, rasterToMatch, destinationPath)prepInputsCanDEM(studyArea, rasterToMatch, destinationPath)
studyArea |
A |
rasterToMatch |
A |
destinationPath |
path to data directory where objects will be downloaded or saved to |
SpatRaster
Get the dummy ecoregion table from LANDIS-II examples.
prepInputsEcoregion(url = NULL, dPath, cacheTags = NULL)prepInputsEcoregion(url = NULL, dPath, cacheTags = NULL)
url |
If NULL (the default), uses one from the LANDIS-II project: https://github.com/LANDIS-II-Foundation/Extensions-Succession/blob/master/biomass-succession-archive/trunk/tests/v6.0-2.0/ecoregion.txt"). |
dPath |
The destination path. |
cacheTags |
User tags to pass to |
A data.table
Create a raster of fire perimeters
prepInputsFireYear(..., rasterToMatch, fireField = "YEAR", earliestYear = 1950)prepInputsFireYear(..., rasterToMatch, fireField = "YEAR", earliestYear = 1950)
... |
Additional arguments passed to |
rasterToMatch |
A |
fireField |
field used to rasterize fire polys |
earliestYear |
the earliest fire date to allow |
a SpatRaster layer of fire perimeters with fire year values.
withr::local_options(list( reproducible.useTerra = TRUE, reproducible.rasterRead = "terra::rast" )) randomPoly <- LandR::randomStudyArea( size = 1e+8, seed = 5 ) ras2match <- terra::rast( randomPoly, vals = 1, res = 100, ) ras2match <- terra::mask(ras2match, randomPoly) firePerimeters <- prepInputsFireYear( url = paste0( "https://cwfis.cfs.nrcan.gc.ca/downloads/", "nfdb/fire_poly/current_version/NFDB_poly.zip" ), destinationPath = file.path(tempdir(), "ex_prepInputsFireYear"), rasterToMatch = ras2match, earliestYear = 1950 ) if (interactive()) { terra::plot(firePerimeters) terra::plot(randomPoly, add = TRUE) } withr::deferred_run()withr::local_options(list( reproducible.useTerra = TRUE, reproducible.rasterRead = "terra::rast" )) randomPoly <- LandR::randomStudyArea( size = 1e+8, seed = 5 ) ras2match <- terra::rast( randomPoly, vals = 1, res = 100, ) ras2match <- terra::mask(ras2match, randomPoly) firePerimeters <- prepInputsFireYear( url = paste0( "https://cwfis.cfs.nrcan.gc.ca/downloads/", "nfdb/fire_poly/current_version/NFDB_poly.zip" ), destinationPath = file.path(tempdir(), "ex_prepInputsFireYear"), rasterToMatch = ras2match, earliestYear = 1950 ) if (interactive()) { terra::plot(firePerimeters) terra::plot(randomPoly, add = TRUE) } withr::deferred_run()
prepInputs for Canadian LCC dataA wrapper around prepInputs for the Canadian Land Cover Classification product(s).
prepInputsLCC( year = 2010, destinationPath = asPath("."), method = c("ngb", "near"), writeTo = NULL, ... )prepInputsLCC( year = 2010, destinationPath = asPath("."), method = c("ngb", "near"), writeTo = NULL, ... )
year |
Numeric, either 2010 or 2015. See note re: backwards compatibility for 2005. |
destinationPath |
Character string of a directory in which to download
and save the file that comes from |
method |
passed to terra::intersect or raster::intersect, and reproducible::prepInputs |
writeTo |
passed to reproducible::prepInputs |
... |
Arguments passed to |
As of May 2021, NRCAN no longer provides/hosts the LCC2005 data. A privately hosted version of the data is available to maintain backwards compatibility, but new users/projects should use the 2010 (or newer) data.
Biomass_core moduleTODO: add detailed description
prepInputsSpecies(url = NULL, dPath, cacheTags = NULL) prepInputsMainInput(url = NULL, dPath = tempdir(), cacheTags = NULL)prepInputsSpecies(url = NULL, dPath, cacheTags = NULL) prepInputsMainInput(url = NULL, dPath = tempdir(), cacheTags = NULL)
url |
If NULL (the default), uses one from the LANDIS-II project: https://github.com/LANDIS-II-Foundation/Extensions-Succession/blob/master/biomass-succession-archive/trunk/tests/v6.0-2.0/biomass-succession_test.txt"). |
dPath |
The destination path. |
cacheTags |
User tags to pass to |
A data.table with columns ... TODO
This one is tailored to Canadian forests (?)
Get the dummy ecoregion table from LANDIS-II examples.
prepInputsSpeciesEcoregion(url = NULL, dPath, cacheTags = NULL)prepInputsSpeciesEcoregion(url = NULL, dPath, cacheTags = NULL)
url |
If NULL (the default), uses one from the LANDIS-II project: https://github.com/LANDIS-II-Foundation/Extensions-Succession/blob/master/biomass-succession-archive/trunk/tests/v6.0-2.0/biomass-succession-dynamic-inputs_test.txt"). |
dPath |
The destination path. |
cacheTags |
User tags to pass to |
A data.table
standAgeMap
Create the standAgeMap raster containing age estimates for pixelCohortData.
A separate reproducible::prepInputs() call will source Canadian National Fire Data Base
data to update ages of recently burned pixels. To suppress this, pass NULL/NA fireURL
prepInputsStandAgeMap( rasterToMatch = NULL, dataSource = "SCANFI", dataYear = 2020, dataVersion = "V2", ageURL = NULL, ageFun = "terra::rast", maskWithRTM = TRUE, method = "bilinear", datatype = "INT2U", destinationPath = NULL, writeTo = NULL, firePerimeters = NULL, fireURL = paste0("https://cwfis.cfs.nrcan.gc.ca/downloads/nfdb/", "fire_poly/current_version/NFDB_poly.zip"), fireFun = "terra::vect", fireField = "YEAR", ... )prepInputsStandAgeMap( rasterToMatch = NULL, dataSource = "SCANFI", dataYear = 2020, dataVersion = "V2", ageURL = NULL, ageFun = "terra::rast", maskWithRTM = TRUE, method = "bilinear", datatype = "INT2U", destinationPath = NULL, writeTo = NULL, firePerimeters = NULL, fireURL = paste0("https://cwfis.cfs.nrcan.gc.ca/downloads/nfdb/", "fire_poly/current_version/NFDB_poly.zip"), fireFun = "terra::vect", fireField = "YEAR", ... )
rasterToMatch |
A |
dataSource |
Character. One of KNN, NTEMS, or SCANFI.
Defaults to SCANFI for
|
dataYear |
Numeric. Year for which data is obtained. Can be 2001 or 2011 for KNN, 2020 for SCANFI V1, or 1985-2025 (5 year intervals) for SCANFI V2. |
dataVersion |
Character. SCANFI product version for data. Default is currently V2. V1 also available. |
ageURL |
URL for age map download. Will be supplied based on |
ageFun |
passed to 'fun' arg of |
maskWithRTM |
passed to |
method |
passed to |
datatype |
passed to |
destinationPath |
path to data directory where objects will be downloaded or saved to |
writeTo |
passed to |
firePerimeters |
fire raster layer fire year values. |
fireURL |
url to download fire polygons used to update age map. If NULL or NA age
imputation is bypassed. Requires passing |
fireFun |
passed to |
fireField |
field used to rasterize fire polys. Only used if |
... |
additional arguments passed to |
a raster layer stand age map corrected for fires, with an attribute vector of pixel IDs
for which ages were corrected. If no corrections were applied the attribute vector is integer(0).
## Not run: library(SpaDES.tools) library(terra) library(reproducible) randomPoly <- randomStudyArea(size = 1e7) randomPoly ras2match <- rast(res = 250, ext = ext(randomPoly), crs = crs(randomPoly)) ras2match <- rasterize(randomPoly, ras2match) tempDir <- file.path(tempdir(), "ex_prepInputsStandAgeMap") ## NOT USING FIRE PERIMETERS TO CORRECT STAND AGE ## rasterToMatch does not need to be provided, but can be for masking/cropping. standAge <- prepInputsStandAgeMap( destinationPath = tempDir, rasterToMatch = ras2match, fireURL = NA ) ## or NULL attr(standAge, "imputedPixID") ## USING FIRE PERIMETERS TO CORRECT STAND AGE ## ideally, get the firePerimenters layer first firePerimeters <- Cache(prepInputsFireYear, url = paste0( "https://cwfis.cfs.nrcan.gc.ca/downloads", "/nfdb/fire_poly/current_version/NFDB_poly.zip" ), destinationPath = tempDir, rasterToMatch = ras2match ) ## Example adjusting SCANFI to 2000 using NTEMS and kNN standAge2000 <- prepInputsStandAgeMap( destinationPath = tempdir(), dataSource = "SCANFI", dataYear = 2000, rasterToMatch = rast(res = 250, ext = ext(vect(randomStudyArea(size = 1e7)))) ) attr(standAge2000, "imputedPixID") ## End(Not run)## Not run: library(SpaDES.tools) library(terra) library(reproducible) randomPoly <- randomStudyArea(size = 1e7) randomPoly ras2match <- rast(res = 250, ext = ext(randomPoly), crs = crs(randomPoly)) ras2match <- rasterize(randomPoly, ras2match) tempDir <- file.path(tempdir(), "ex_prepInputsStandAgeMap") ## NOT USING FIRE PERIMETERS TO CORRECT STAND AGE ## rasterToMatch does not need to be provided, but can be for masking/cropping. standAge <- prepInputsStandAgeMap( destinationPath = tempDir, rasterToMatch = ras2match, fireURL = NA ) ## or NULL attr(standAge, "imputedPixID") ## USING FIRE PERIMETERS TO CORRECT STAND AGE ## ideally, get the firePerimenters layer first firePerimeters <- Cache(prepInputsFireYear, url = paste0( "https://cwfis.cfs.nrcan.gc.ca/downloads", "/nfdb/fire_poly/current_version/NFDB_poly.zip" ), destinationPath = tempDir, rasterToMatch = ras2match ) ## Example adjusting SCANFI to 2000 using NTEMS and kNN standAge2000 <- prepInputsStandAgeMap( destinationPath = tempdir(), dataSource = "SCANFI", dataYear = 2000, rasterToMatch = rast(res = 250, ext = ext(vect(randomStudyArea(size = 1e7)))) ) attr(standAge2000, "imputedPixID") ## End(Not run)
rasterToMatch and rasterToMatchLarge
rasterToMatch and rasterToMatchLarge raster layers are created
from studyArea and studyAreaLarge polygons (respectively)
using a template raster (often rawBiomassMap)
prepRasterToMatch( studyArea, studyAreaLarge, rasterToMatch, rasterToMatchLarge, destinationPath, templateRas, studyAreaName, cacheTags = NULL )prepRasterToMatch( studyArea, studyAreaLarge, rasterToMatch, rasterToMatchLarge, destinationPath, templateRas, studyAreaName, cacheTags = NULL )
studyArea |
A |
studyAreaLarge |
same as |
rasterToMatch |
A |
rasterToMatchLarge |
A |
destinationPath |
path to data directory where objects will be downloaded or saved to |
templateRas |
a template raster used to make |
studyAreaName |
character string giving the study area name. |
cacheTags |
a character vector of strings to pass to |
rawBiomassMap
Create the rawBiomassMap raster containing biomass estimates for pixelCohortData.
prepRawBiomassMap( dataSource = "SCANFI", dataYear = "2020", dataVersion = "V2", ... )prepRawBiomassMap( dataSource = "SCANFI", dataYear = "2020", dataVersion = "V2", ... )
dataSource |
Character. One of KNN, NTEMS, or SCANFI.
Defaults to KNN for
|
dataYear |
Numeric. Year for which data is obtained. Can be 2001 or 2011 for KNN, 2015 for NTEMS, 2000, 2010, or 2020 for SCANFI V1, or 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020 (default), 2025 possible for V2. |
dataVersion |
Character. SCANFI product version for data. Default is currently V2. V1 also available. |
... |
arguments passed to
|
a rawBiomassMap raster
Download and prepare species layers for a given study area, from one of several sources:
prepSpeciesLayers_CASFRI() uses CASFRIv4 described in Cosco (2011);
prepSpeciesLayers_ForestInventory() uses data prepared for Western Canada as part of the LandWeb project;
prepSpeciesLayers_KNN() uses the layers from Beaudoin et al. (2014, 2017);
prepSpeciesLayers_MBFRI() uses data derived from Manitoba Forest Resource Inventories;
prepSpeciesLayers_NTEMS() uses the National Terrestrial Ecosystem Monitoring System for
Canada (NTEMS) tree species data described in Hermosilla et al. (2024);
prepSpeciesLayers_ONFRI() uses data derived from Ontario Forest Resource Inventories;
prepSpeciesLayers_Pickell() uses data prepared for Western Canada by Pickell & Coops (2016)
as part of the LandWeb project;
prepSpeciesLayers_SCANFI() uses SCANFI data described in Guidon et al. (2023, 2024);
prepSpeciesLayers_KNN( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... ) prepSpeciesLayers_CASFRI( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_Pickell( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_ForestInventory( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_NTEMS( destinationPath, outputPath, url = NULL, dataYear = 2020, studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... ) prepSpeciesLayers_SCANFI( destinationPath, outputPath, url = NULL, dataYear = 2020, dataVersion = "V2", studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... ) prepSpeciesLayers_MBFRI( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_ONFRI( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... )prepSpeciesLayers_KNN( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... ) prepSpeciesLayers_CASFRI( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_Pickell( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_ForestInventory( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_NTEMS( destinationPath, outputPath, url = NULL, dataYear = 2020, studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... ) prepSpeciesLayers_SCANFI( destinationPath, outputPath, url = NULL, dataYear = 2020, dataVersion = "V2", studyArea, rasterToMatch, sppEquiv, sppEquivCol, thresh = 10, ... ) prepSpeciesLayers_MBFRI( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... ) prepSpeciesLayers_ONFRI( destinationPath, outputPath, url = NULL, studyArea, rasterToMatch, sppEquiv, sppEquivCol, ... )
destinationPath |
path to data directory where objects will be downloaded or saved to |
outputPath |
character, specifying the output directory to use |
url |
if |
studyArea |
A |
rasterToMatch |
A |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
thresh |
threshold \
If at least one pixel has |
... |
other arguments, used for compatibility with other |
dataYear |
Year for the data obtained. 2000, 2010, or 2020 (default) possible. |
dataVersion |
character. Data version for SCANFI. V2 is default. |
multilayer SpatRaster ("stack")
Beaudoin, A., Bernier, P.Y., Guindon, L., Villemaire, P., Guo, X.J., Stinson, G., et al. (2014). Mapping attributes of Canada’s forests at moderate resolution through kNN and MODIS imagery. Canadian Journal of Forest Research, 44, 521–532.
Beaudoin, A., Bernier, P.Y., Villemaire, P., Guindon, L. & Guo, X.J. (2017). Species composition, forest properties and land cover types across Canada’s forests at 250m resolution for 2001 and 2011. https://doi.org/10.23687/EC9E2659-1C29-4DDB-87A2-6ACED147A990
Cosco, J.A. (2011). Common Attribute Schema (CAS) for Forest Inventories Across Canada. Timberline Natural Resource Group for Boreal Avian Modelling Project and Canadian BEACONs Project.
Guindon L., Villemaire P., Correia D.L.P., Manka F., Lacarte S., Smiley B. (2023). SCANFI: Spatialized Canadian National Forest Inventory data product. Natural Resources Canada, Canadian Forest Service, Laurentian Forestry Centre, Quebec, Canada. https://doi.org/10.23687/18e6a919-53fd-41ce-b4e2-44a9707c52dc
Guindon L., Manka F, Correia L.P. D., Villemaire P., Smiley B., Bernier P., Gauthier S., Beaudoin A., Boucher J., Boulanger Y. (2024). A new approach for Spatializing the Canadian National Forest Inventory (SCANFI) using Landsat dense time series. Canadian Journal of Forest Research. https://doi.org/10.1139/cjfr-2023-0118
Hermosilla, T., Wulder, M.A., White, J.C., Coops, N.C., Bater, C.W., Hobart, G.W. (2024). Characterizing long-term tree species dynamics in Canada's forested ecosystems using annual time series remote sensing data. Forest Ecology and Management, 122313. https://doi.org/10.1016/j.foreco.2024.122313
Pickell, P.D. & Coops, N.C. (2016). Development of historical forest attribute layers using Landsat time series and kNN imputation for the western Canadian boreal forest. University of British Columbia.
This simply re-exports SpaDES.tools::randomStudyArea
randomStudyArea(center = NULL, size = 10000, seed = NULL)randomStudyArea(center = NULL, size = 10000, seed = NULL)
center |
|
size |
Numeric specifying the approximate size of the area in m^2.
Default |
seed |
Numeric indicating the random seed to set internally (useful for ensuring the same study area is produced each time). |
Replace stand age with time since last fire
replaceAgeInFires(standAgeMap, firePerimeters, startTime)replaceAgeInFires(standAgeMap, firePerimeters, startTime)
standAgeMap |
a raster layer stand age map |
firePerimeters |
the earliest fire date to allow |
startTime |
date of the last fire year to be considered (e.g., start of fire period counting backwards). If missing, last fire year available will be used. |
a raster layer stand age map corrected for fires, with an attribute vector of pixel IDs
for which ages were corrected. If no corrections were applied the attribute vector is integer(0).
## Not run: randomPoly <- terra::vect(SpaDES.tools::randomStudyArea(size = 1e7)) randomPoly ras2match <- terra::rast(resolution = 250, ext = terra::ext(randomPoly), crs = terra::crs(randomPoly)) ras2match <- terra::rasterize(randomPoly, ras2match) tempDir <- file.path(tempdir(), "ex_replaceAgeInFires") standAge <- reproducible::prepInputsStandAgeMap( destinationPath = tempDir, rasterToMatch = ras2match, fireURL = NA ) ## or NULL attr(standAge, "imputedPixID") firePerimeters <- reproducible::Cache(prepInputsFireYear, url = paste0( "https://cwfis.cfs.nrcan.gc.ca/downloads", "/nfdb/fire_poly/current_version/NFDB_poly.zip" ), destinationPath = tempDir, rasterToMatch = ras2match ) standAge <- replaceAgeInFires(standAge, firePerimeters) attr(standAge, "imputedPixID") ## End(Not run)## Not run: randomPoly <- terra::vect(SpaDES.tools::randomStudyArea(size = 1e7)) randomPoly ras2match <- terra::rast(resolution = 250, ext = terra::ext(randomPoly), crs = terra::crs(randomPoly)) ras2match <- terra::rasterize(randomPoly, ras2match) tempDir <- file.path(tempdir(), "ex_replaceAgeInFires") standAge <- reproducible::prepInputsStandAgeMap( destinationPath = tempDir, rasterToMatch = ras2match, fireURL = NA ) ## or NULL attr(standAge, "imputedPixID") firePerimeters <- reproducible::Cache(prepInputsFireYear, url = paste0( "https://cwfis.cfs.nrcan.gc.ca/downloads", "/nfdb/fire_poly/current_version/NFDB_poly.zip" ), destinationPath = tempDir, rasterToMatch = ras2match ) standAge <- replaceAgeInFires(standAge, firePerimeters) attr(standAge, "imputedPixID") ## End(Not run)
scales::rescale)This is a simple function copied from the scales package (almost the same).
rescale(x, to)rescale(x, to)
x |
a |
to |
a |
cohortData based on pixelGroupMap
Remove missing cohorts from cohortData based on pixelGroupMap
rmMissingCohorts( cohortData, pixelGroupMap, cohortDefinitionCols = LandR::cohortDefinitionCols(), doAssertion = getOption("LandR.assertions", TRUE) )rmMissingCohorts( cohortData, pixelGroupMap, cohortDefinitionCols = LandR::cohortDefinitionCols(), doAssertion = getOption("LandR.assertions", TRUE) )
cohortData |
A |
pixelGroupMap |
A |
cohortDefinitionCols |
the columns in |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
A list with 2 data.table objects, cohortData and pixelGroupMap,
each updated based on missing pixelGroups in the other.
Test whether disturbance should be scheduled
scheduleDisturbance(disturbanceLayer, currentYear)scheduleDisturbance(disturbanceLayer, currentYear)
disturbanceLayer |
a |
currentYear |
time of simulation |
Logical indicating whether to schedule a disturbance event
## Not run: doEvent <- scheduleDisturbance(sim$rstCurrentBurn, time(sim), disturbanceType = "Burn") ## End(Not run)## Not run: doEvent <- scheduleDisturbance(sim$rstCurrentBurn, time(sim), disturbanceType = "Burn") ## End(Not run)
speciesEcoregion table for current timePull out the values from speciesEcoregion table for current time
speciesEcoregionLatestYear(speciesEcoregion, currentTime)speciesEcoregionLatestYear(speciesEcoregion, currentTime)
speciesEcoregion |
A |
currentTime |
The current simulation time e.g., |
The speciesEcoregion input object, but with data from only one year, the year
that is less than or equal to the currentTime
speciesEcoregion contentEach RasterStack show raster maps of one of the columns listed in columns
and each RasterLayer will be one species.
speciesEcoregionStack( ecoregionMap, speciesEcoregion, columns = c("establishprob", "maxB", "maxANPP") )speciesEcoregionStack( ecoregionMap, speciesEcoregion, columns = c("establishprob", "maxB", "maxANPP") )
ecoregionMap |
The |
speciesEcoregion |
A |
columns |
The columns to use in the |
list of RasterStack or SpatRaster objects
speciesInStudyArea defaults to use a URL of a dataset uploaded to Google Drive that is
from Canadian Forests,
but a different factor raster can be passed e.g., from speciesPresentFromKNN.
speciesInStudyArea( studyArea, url = NULL, speciesPresentRas = NULL, sppEquivCol = NULL, dataSource = "SCANFI", dataYear = 2025, dPath = getOption("reproducible.destinationPath") )speciesInStudyArea( studyArea, url = NULL, speciesPresentRas = NULL, sppEquivCol = NULL, dataSource = "SCANFI", dataYear = 2025, dPath = getOption("reproducible.destinationPath") )
studyArea |
A |
url |
A url to get a |
speciesPresentRas |
A factor raster where the character string is a string of
species names, separated by 2 underscores, sorted alphabetically. Can be produced
with |
sppEquivCol |
An optional column from |
dataSource |
Character. Either KNN, NTEMS, or SCANFI. Defaults to KNN to obtain species from layer created using species cover data from KNN. Also able to obtain species from SCANFI species cover layers and NTEMS Dominant Species Layer (though less species will be included from the latter). |
dataYear |
Numeric. Different source data years are available for different data sources. 2011 for KNN, 2011 for NTEMS, and every 5 years from 1985-2025 for SCANFI V2. |
dPath |
Passed to |
A named list of length 2: speciesRas is a factor RasterLayer
and speciesList is a character string containing the unique, sorted
species on the speciesRas, for convenience.
This will download all KNN layers in Forests of Canada, and make
a factor raster at resolution provided by res (larger is faster).
speciesPresentFromKNN( year = 2011, dPath = asPath("."), res = 2000, minPctCover = 10 )speciesPresentFromKNN( year = 2011, dPath = asPath("."), res = 2000, minPctCover = 10 )
year |
Default (and only implemented) is 2011. This will download the 2011 KNN data layers |
dPath |
A character string indicating where to download all the KNN layers |
res |
The resolution (one dimension, in m) for the resulting raster |
minPctCover |
An integer indicating what percent cover a species must have in a pixel to be considered present in that pixel. |
A SpatRaster object with 2 layers: "speciesPresent" is a factor, with
a legend (i.e., it is numbers on a map, that correspond to a legend) and
"numberSpecies" which represents the number of species in each pixel.
## Not run: if (requireNamespace("googledrive", quietly = TRUE)) { ## Make the dataset speciesPresent <- speciesPresentFromKNN(dPath = file.path(tempdir(), "data_KNN")) ## To upload this: speciesPresentRas <- terra::rast(speciesPresent)[[1]] fn <- "SpeciesPresentInCanadianForests.tif" writeRaster(speciesPresentRas, file = fn) zipFn <- gsub(".tif", ".zip", fn) zip(files = dir(pattern = fn), zipFn) out <- googledrive::drive_put(zipFn) ## Note: previous file (cropped to boreal forest) ## available at "1Oj78jJBeha5L6XDBBdWDAfimgNjYc9UD" driveID <- "1J8fN7clZeqjd7yhiDWi13uoCBL8OensF" ## Get species list sa <- LandR::randomStudyArea(size = 1e11) species <- LandR::speciesInStudyArea(sa, dataSOurce = "KNN") } ## End(Not run)## Not run: if (requireNamespace("googledrive", quietly = TRUE)) { ## Make the dataset speciesPresent <- speciesPresentFromKNN(dPath = file.path(tempdir(), "data_KNN")) ## To upload this: speciesPresentRas <- terra::rast(speciesPresent)[[1]] fn <- "SpeciesPresentInCanadianForests.tif" writeRaster(speciesPresentRas, file = fn) zipFn <- gsub(".tif", ".zip", fn) zip(files = dir(pattern = fn), zipFn) out <- googledrive::drive_put(zipFn) ## Note: previous file (cropped to boreal forest) ## available at "1Oj78jJBeha5L6XDBBdWDAfimgNjYc9UD" driveID <- "1J8fN7clZeqjd7yhiDWi13uoCBL8OensF" ## Get species list sa <- LandR::randomStudyArea(size = 1e11) species <- LandR::speciesInStudyArea(sa, dataSOurce = "KNN") } ## End(Not run)
This will download NTEMS dominant species layer for 2011 for forests of Canada, and make
a factor raster at resolution provided by res (larger is faster).
speciesPresentFromNTEMS( dPath = asPath("."), res = 2400, year = 2011, rasterToMatch = NULL, studyArea = NULL, ... )speciesPresentFromNTEMS( dPath = asPath("."), res = 2400, year = 2011, rasterToMatch = NULL, studyArea = NULL, ... )
dPath |
A character string indicating where to download all the NTEMS layers |
res |
The resolution (one dimension, in m) for the resulting raster |
year |
Default (and only implemented) is 2011. This will download the 2011 NTEMS species layer |
rasterToMatch |
A |
studyArea |
A |
... |
Additional arguments passed to |
A SpatRaster object with 2 layers: "speciesPresent" is a factor, with
a legend (i.e., it is numbers on a map, that correspond to a legend) and
"numberSpecies" which represents the number of species in each pixel.
## Not run: if (requireNamespace("googledrive", quietly = TRUE)) { # Make the dataset speciesPresent <- speciesPresentFromNTEMS(dPath = "~/data/NTEMS") # To upload this: speciesPresentRas <- terra::rast(speciesPresent)[[1]] fn <- "SpeciesPresentInCanadianForests_NTEMS.tif" writeRaster(speciesPresentRas, file = fn) zipFn <- gsub(".tif", ".zip", fn) zip(files = dir(pattern = fn), zipFn) out <- googledrive::drive_put(zipFn) ## Get species list sa <- LandR::randomStudyArea(size = 1e11) species <- LandR::speciesInStudyArea(sa, dataSource = "NTEMS") } ## End(Not run)## Not run: if (requireNamespace("googledrive", quietly = TRUE)) { # Make the dataset speciesPresent <- speciesPresentFromNTEMS(dPath = "~/data/NTEMS") # To upload this: speciesPresentRas <- terra::rast(speciesPresent)[[1]] fn <- "SpeciesPresentInCanadianForests_NTEMS.tif" writeRaster(speciesPresentRas, file = fn) zipFn <- gsub(".tif", ".zip", fn) zip(files = dir(pattern = fn), zipFn) out <- googledrive::drive_put(zipFn) ## Get species list sa <- LandR::randomStudyArea(size = 1e11) species <- LandR::speciesInStudyArea(sa, dataSource = "NTEMS") } ## End(Not run)
This will download SCANFI species layer for forests of Canada, and make
a factor raster at resolution provided by res (larger is faster).
speciesPresentFromSCANFI( year = 2020, dataVersion = "V2", dPath = asPath("."), res = 2400, minPctCover = 10 )speciesPresentFromSCANFI( year = 2020, dataVersion = "V2", dPath = asPath("."), res = 2400, minPctCover = 10 )
year |
data year for SCANFI data. 2000, 2010, and 2020 possible for V1. 1985, 1990, 1995, 2000, 2005, 2010, 2015, 2020 (default), 2025 possible for V2. |
dataVersion |
Character. SCANFI product version for data. Default is currently V2. V1 also available. |
dPath |
A character string indicating where to download all the SCANFI layers |
res |
The resolution (one dimension, in m) for the resulting raster |
minPctCover |
An integer indicating what percent cover a species must have in a pixel to be considered present in that pixel. |
A SpatRaster object with 2 layers: "speciesPresent" is a factor, with
a legend (i.e., it is numbers on a map, that correspond to a legend) and
"numberSpecies" which represents the number of species in each pixel.
## Not run: if (requireNamespace("googledrive", quietly = TRUE)) { # Make the dataset speciesPresent <- speciesPresentFromSCANFI(dPath = "~/data/SCANFI") # To upload this: speciesPresentRas <- speciesPresent[[1]] fn <- "SpeciesPresentInCanadianForests_SCANFI.tif" writeRaster(speciesPresentRas, file = fn) zipFn <- gsub(".tif", ".zip", fn) zip(files = dir(pattern = fn), zipFn) out <- googledrive::drive_put(zipFn) ## Get species list sa <- LandR::randomStudyArea(size = 1e11) species <- LandR::speciesInStudyArea(sa, dataSource = "SCANFI") } ## End(Not run)## Not run: if (requireNamespace("googledrive", quietly = TRUE)) { # Make the dataset speciesPresent <- speciesPresentFromSCANFI(dPath = "~/data/SCANFI") # To upload this: speciesPresentRas <- speciesPresent[[1]] fn <- "SpeciesPresentInCanadianForests_SCANFI.tif" writeRaster(speciesPresentRas, file = fn) zipFn <- gsub(".tif", ".zip", fn) zip(files = dir(pattern = fn), zipFn) out <- googledrive::drive_put(zipFn) ## Get species list sa <- LandR::randomStudyArea(size = 1e11) species <- LandR::speciesInStudyArea(sa, dataSource = "SCANFI") } ## End(Not run)
Changes longevity and shade tolerance values in the species table. Longevity values are changed to follow Burton & Cumming (1995) for the following species:
Abies balsamea;
Abies lasiocarpa;
Betula papyrifera;
Larix laricina;
Larix occidentalis;
Picea engelmannii;
Picea glauca;
Picea mariana;
Pinus banksiana;
Pinus contorta;
Pinus resinosa;
Pinus strobus;
Populus balsamifera v. balsamifera;
Populus tremuloides;
Pseudotsuga menziesii var. glauca;
Pseudotsuga menziesii;
Thuja plicata;
Tsuga heterophylla;
Tsuga mertensiana x heterophylla;
speciesTableUpdate(species, speciesTable, sppEquiv = NULL, sppEquivCol = NULL)speciesTableUpdate(species, speciesTable, sppEquiv = NULL, sppEquivCol = NULL)
species |
a
|
speciesTable |
A species traits table, with at least the following columns:
|
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
and only for the following speciesTable$Areas:
Boreal Shield West (BSW);
Boreal Plains (BP);
Montane Cordillera (MC).
Note that BSW and BP areas correspond more closely to the region considered in Table 2 of Burton & Cumming (1995), while MC will correspond to both tables.
Of the above species, shade tolerance values are changed for Abies spp, Picea spp, and Tsuga spp to better reflect the western boreal.
When different longevity/shade tolerance trait values exist for a given species, the minimum
value across Area's (BSW, BP, MC) is kept.
ATTENTION: if none of species in species are from BSW, BP or MC area this function will not
change any values.
All other species/Area trait values follow Dominic Cyr and Yan Boulanger's trait values (https://raw.githubusercontent.com/dcyr/LANDIS-II_IA_generalUseFiles/master/speciesTraits.csv).
An updated species data.table
sppEquiv tableCreate species colour vector from a sppEquiv table
sppColors(sppEquiv, sppEquivCol, newVals = NULL, palette = "Accent")sppColors(sppEquiv, sppEquivCol, newVals = NULL, palette = "Accent")
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
newVals |
An optional character vector of extra names to use, e.g., "Mixed". |
palette |
An RColorBrewer palette, e.g., "Accent".
Can get RColorBrewer palette names from |
A named vector of colour codes, where the names are the species names
plus any extra names passed with newVals.
A table containing the different species names used across different sources (e.g., LANDIS-II test parameter files and trait tables, the LandR standard, kNN species biomass layers, etc.). Each column refers to a different source or species naming approach. Presently only containing Canadian native tree species, with name equivalencies coming from:
sppEquivalencies_CAsppEquivalencies_CA
A data.frame with 204 rows and 27 variables:
species names from LANDIS-II test parameter table; source: https://raw.githubusercontent.com/LANDIS-II-Foundation/Extensions-Succession/master/biomass-succession-archive/trunk/tests/v6.0-2.0/species.txt
species names from LANDIS-II traits parameter table; source: https://raw.githubusercontent.com/dcyr/LANDIS-II_IA_generalUseFiles/master/speciesTraits.csv
species names from LandR modules
species names from CFS kNN datasets; source: http://tree.pfc.forestry.ca/kNN-Species.tar
species names from Canadian Common Attribute Schema for Forest Resource Inventories; source http://www.borealbirds.ca/files/CAS_Document_Final_Mar_2010_ALL_APPENDICES.pdf
accepted species latin names as in http://theplantlist.org
Short version of species' common names in English
Full species common names in English
Simple common English names used for leading species
additional notes and information
Species present in the Boreal forests of Canada
logical indicating whether the species is broad leaf
Whether the species is a deciduous or conifer species
Species name from the module ianmseddy/PSP_Clean
Species groups roughly corresponding to Canadian Forest Fire Behavior Prediction (FBP) System
The fuel class used by the module PredictiveEcology/fireSense
#'
Species code adopted by the Government of British Columbia
Species code adopted by the Government of Alberta
Species code adopted by the Government of Manitoba
Species code used by the National Forest Inventory
Species code used in Québec PSP data
Species code used by Canada's Forest Inventory (CANFI)
Additional notes for CANFI species data
Species code used by the National Terrestrial Ecosystem Monitoring System (NTEMS)
Species code used by the CFS Carbon Budget Model
Species names from the Spatialized Canadian National Forest Inventory (SCANFI)
hexadecimal colour codes for use with plotting
This table is currently used as the default equivalencies table in LandR SpaDES modules, but can also serve as a template to customize species names equivalencies by the user.
sppEquiv
This will expand a sppEquiv object that is only a vector or only a one-column
data.table into a many column data.table, if the columns that are present do not
contain ensureColumns.
sppEquivCheck(sppEquiv, ensureColumns = NULL, sppEquivCol = NULL)sppEquivCheck(sppEquiv, ensureColumns = NULL, sppEquivCol = NULL)
sppEquiv |
A character vector or |
ensureColumns |
A character vector of column names that must be in |
sppEquivCol |
Optional. Column in |
A data.table with potentially all columns in sppEquivalencies_CA.
Biomass_** modulesThis function will attempt to harmonize many potential issues/conflicts that may arise under different combinations of supplied objects to the three arguments. See manual for details.
sppHarmonize( sppEquiv, sppNameVector, sppEquivCol, sppColorVect, vegLeadingProportion = 0, studyArea, dPath = getOption("reproducible.destinationPath") )sppHarmonize( sppEquiv, sppNameVector, sppEquivCol, sppColorVect, vegLeadingProportion = 0, studyArea, dPath = getOption("reproducible.destinationPath") )
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppNameVector |
A character vector of species to use. These species must all
be from one naming convention, i.e., from one column in the |
sppEquivCol |
A character string normally provided from the |
sppColorVect |
A named vector of colours to use for plotting.
The names must conform with species name convention used
(see sppEquivalencies_CA for possible naming
conventions) and should also contain a colour for 'Mixed',
when a mixed forest type is supported (see |
vegLeadingProportion |
Numeric between 0-1, determining the relative biomass threshold a species needs to pass to be considered "leading". |
studyArea |
A |
dPath |
Passed to |
Returns a named list with the same names as the arguments. These should
likely be assigned to the sim object in the module following this function call.
## not run. usage example within module # sppOuts <- sppHarmonize(sim$sppEquiv, sim$sppNameVector, P(sim)$sppEquivCol) # sim$sppEquiv <- sppOuts$sppEquiv # sim$sppNameVector <- sppOuts$sppNameVector # P(sim)$sppEquivCol <- sppOuts$sppEquivCol## not run. usage example within module # sppOuts <- sppHarmonize(sim$sppEquiv, sim$sppNameVector, P(sim)$sppEquivCol) # sim$sppEquiv <- sppOuts$sppEquiv # sim$sppNameVector <- sppOuts$sppNameVector # P(sim)$sppEquivCol <- sppOuts$sppEquivCol
cohortData
Produce stand age map based on cohortData
standAgeMapGenerator( cohortData, pixelGroupMap, weight = "biomass", doAssertion = getOption("LandR.assertions", FALSE) )standAgeMapGenerator( cohortData, pixelGroupMap, weight = "biomass", doAssertion = getOption("LandR.assertions", FALSE) )
cohortData |
A |
pixelGroupMap |
A |
weight |
variable by which to weight |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
raster of the same type as pixelGroupMap.
lmer or glmer)This does a few things including R squared, gets the fitted values.
It appears that running the models "as is" without this wrapper does not work with Cache.
The return of the model in a list solves this problem.
For Caching, the .specialData should be "omitted" via omitArgs, and
uniqueEcoregionGroups should not be omitted.
statsModel(modelFn, uniqueEcoregionGroups, sumResponse, .specialData)statsModel(modelFn, uniqueEcoregionGroups, sumResponse, .specialData)
modelFn |
A quoted expression of type |
uniqueEcoregionGroups |
Unique values of |
sumResponse |
a sum of all the response variable values.
Also to be used to optimize caching, e.g. ignore |
.specialData |
The custom dataset required for the model. |
Extend a study area boundary to include the full ecological boundary polygons intersecting it.
studyAreaEco( studyArea = NULL, destinationPath = tempdir(), type = c("ECOZONE", "ECOPROVINCE", "ECOREGION", "ECODISTRICT") )studyAreaEco( studyArea = NULL, destinationPath = tempdir(), type = c("ECOZONE", "ECOPROVINCE", "ECOREGION", "ECODISTRICT") )
studyArea |
A |
destinationPath |
path to data directory where objects will be downloaded or saved to |
type |
character. The polygon type to use: one of "ECODISTRICT", "ECOREGION", "ECOPROVINCE", or "ECOZONE". |
spatial polygons object of the same class as studyArea
## using SpatVector objects sa <- randomStudyArea(size = 1e9) sa_eco <- studyAreaEco(studyArea = sa) ## using sf objects sa_sf <- sf::st_as_sf(sa) sa_eco_sf <- studyAreaEco(studyArea = sa_sf) if (interactive()) { ggplot() + geom_sf(data = sa_eco_sf, fill = "gray") + geom_sf(data = sa_sf, fill = "violet", alpha = 0.3) }## using SpatVector objects sa <- randomStudyArea(size = 1e9) sa_eco <- studyAreaEco(studyArea = sa) ## using sf objects sa_sf <- sf::st_as_sf(sa) sa_eco_sf <- studyAreaEco(studyArea = sa_sf) if (interactive()) { ggplot() + geom_sf(data = sa_eco_sf, fill = "gray") + geom_sf(data = sa_sf, fill = "violet", alpha = 0.3) }
data.table with random subsampling within by groupsSubset a data.table with random subsampling within by groups
subsetDT(DT, by, doSubset = TRUE, indices = FALSE)subsetDT(DT, by, doSubset = TRUE, indices = FALSE)
DT |
A |
by |
Character vector of column names to use for groups |
doSubset |
Logical or numeric indicating the number of subsamples to use |
indices |
Logical. If |
library(data.table) dt <- data.table(Lett = sample(LETTERS, replace = TRUE, size = 1000), Nums = 1:100) dt1 <- subsetDT(dt, by = "Lett", doSubset = 3)library(data.table) dt <- data.table(Lett = sample(LETTERS, replace = TRUE, size = 1000), Nums = 1:100) dt1 <- subsetDT(dt, by = "Lett", doSubset = 3)
Function to sum rasters of species layers
sumRastersBySpecies(speciesLayers, layersToSum, filenameToSave, newLayerName)sumRastersBySpecies(speciesLayers, layersToSum, filenameToSave, newLayerName)
speciesLayers |
A |
layersToSum |
names/indices of layers to be summed - optional |
filenameToSave |
file path to save output raster |
newLayerName |
name of the output raster layer |
cohortData that define "unique"If two pixels have identical values in all of these columns, they are the same pixelGroup.
uniqueCohortDefinition uniqueSpeciesEcoregionDefinitionuniqueCohortDefinition uniqueSpeciesEcoregionDefinition
cohortData and pixelGroupMap
This is a wrapper for generatePixelGroups, initiateNewCohort and updates to
pixelGroupMap via assignment to new pixelIndex values in newPixelCohortData.
By running these all together, there is less chance that they will diverge.
There are some checks internally for consistency.
Calculate new values for B, add age, then rbindlist this
with cohortData.
updateCohortData( newPixelCohortData, cohortData, pixelGroupMap, currentTime, speciesEcoregion, treedFirePixelTableSinceLastDisp = NULL, successionTimestep, cohortDefinitionCols = LandR::cohortDefinitionCols(), initialB = 10, verbose = getOption("LandR.verbose", TRUE), doAssertion = getOption("LandR.assertions", TRUE) ) .initiateNewCohorts( newPixelCohortData, cohortData, pixelGroupMap, currentTime, cohortDefinitionCols = LandR::cohortDefinitionCols(), speciesEcoregion, successionTimestep, initialB = 10 )updateCohortData( newPixelCohortData, cohortData, pixelGroupMap, currentTime, speciesEcoregion, treedFirePixelTableSinceLastDisp = NULL, successionTimestep, cohortDefinitionCols = LandR::cohortDefinitionCols(), initialB = 10, verbose = getOption("LandR.verbose", TRUE), doAssertion = getOption("LandR.assertions", TRUE) ) .initiateNewCohorts( newPixelCohortData, cohortData, pixelGroupMap, currentTime, cohortDefinitionCols = LandR::cohortDefinitionCols(), speciesEcoregion, successionTimestep, initialB = 10 )
newPixelCohortData |
must be a complete |
cohortData |
A |
pixelGroupMap |
A |
currentTime |
The current simulation time e.g., |
speciesEcoregion |
A |
treedFirePixelTableSinceLastDisp |
A data.table with at least 2 columns, |
successionTimestep |
The time between successive seed dispersal events. In LANDIS-II, this is called "Succession Timestep". |
cohortDefinitionCols |
the columns in |
initialB |
the initial biomass of new cohorts. Defaults to 10.
If initialB = asInteger(pmin(maxANPP, asInteger(pmax(1, maxANPP \* exp(-1.6 \* sumB / maxB_eco))))) where |
verbose |
Controls message output. Defaults to |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
Does the following:
add new cohort (not survivor) data into cohortData;
assign initial B and age for new cohort;
assign the new pixelGroup to the pixels that have new cohort;
update the pixelGroup map.
Note that if newPixelCohortData is generated after a disturbance
it must contain a type column indicating the origin of the cohorts
(e.g. "survivor", "serotiny", "resprouting"). "Survivor" cohorts will
not be added to the output objects, as they are assumed to be accounted
for in the input cohortData and, correspondingly, pixelGroupMap.
A list of length 2, cohortData and pixelGroupMap, with
newPixelCohortData inserted.
A data.table with a new rbindlisted cohortData
cohortData and pixelGroupMap
This is a wrapper for generatePixelGroups, initiateNewCohort and updates to
pixelGroupMap via assignment to new pixelIndex values in newPixelCohortData.
By running these all together, there is less chance that they will diverge.
There are some checks internally for consistency.
updateCohortDataPostHarvest( newPixelCohortData, cohortData, pixelGroupMap, currentTime, speciesEcoregion, treedHarvestPixelTable = NULL, successionTimestep, provenanceTable, trackPlanting = FALSE, initialB = 10, cohortDefinitionCols = LandR::cohortDefinitionCols(), verbose = getOption("LandR.verbose", TRUE), doAssertion = getOption("LandR.assertions", TRUE) )updateCohortDataPostHarvest( newPixelCohortData, cohortData, pixelGroupMap, currentTime, speciesEcoregion, treedHarvestPixelTable = NULL, successionTimestep, provenanceTable, trackPlanting = FALSE, initialB = 10, cohortDefinitionCols = LandR::cohortDefinitionCols(), verbose = getOption("LandR.verbose", TRUE), doAssertion = getOption("LandR.assertions", TRUE) )
newPixelCohortData |
must be a complete |
cohortData |
A |
pixelGroupMap |
A |
currentTime |
The current simulation time e.g., |
speciesEcoregion |
A |
treedHarvestPixelTable |
A data.table with at least 2 columns, |
successionTimestep |
The time between successive seed dispersal events. In LANDIS-II, this is called "Succession Timestep". |
provenanceTable |
A |
trackPlanting |
if true, planted cohorts in |
initialB |
the initial biomass of new cohorts. Defaults to ten, even if NA/NULL is passed. |
cohortDefinitionCols |
the columns in |
verbose |
Controls message output. Defaults to |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
Does the following:
add new cohort data into cohortData;
assign initial B and age for new cohort;
assign the new pixelGroup to the pixels that have new cohort;
update the pixelGroup map.
A list of length 2, cohortData and pixelGroupMap, with
newPixelCohortData inserted.
Customize species trait table values
updateSpeciesTable(speciesTable, params)updateSpeciesTable(speciesTable, params)
speciesTable |
A species traits table, with at least the following columns:
|
params |
A named list (of parameters) of named lists (by species), with species
traits overrides (e.g., |
Alex Chubaty and Ceres Barros
cohortData
This function is a simplification of vegTypeMapGenerator and instead of generating a map,
it adds the vegetation type column to the cohortData table.
vegTypeGenerator( x, vegLeadingProportion = 0.8, mixedType = 2, sppEquiv = NULL, sppEquivCol, pixelGroupColName = "pixelGroup", doAssertion = getOption("LandR.assertions", TRUE), ... )vegTypeGenerator( x, vegLeadingProportion = 0.8, mixedType = 2, sppEquiv = NULL, sppEquivCol, pixelGroupColName = "pixelGroup", doAssertion = getOption("LandR.assertions", TRUE), ... )
x |
A |
vegLeadingProportion |
Numeric between 0-1, determining the relative biomass threshold a species needs to pass to be considered "leading". |
mixedType |
An integer defining whether mixed stands are: not differentiated (0), any kind of species admixture (1), or deciduous mixed with conifer (2; default). |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
pixelGroupColName |
Name of the column in |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
... |
Additional arguments. |
x with a new column, 'leading', coding the vegetation type
of each group defined by pixelGroupColName
Eliot McIntire, Ceres Barros, Alex Chubaty
library(data.table) x <- data.table( pixelGroup = rep(1:2, each = 2), B = c(100, 200, 20, 400), speciesCode = rep(c("Pice_Gla", "Popu_Tre"), 2) ) vegTypeGenerator(x)library(data.table) x <- data.table( pixelGroup = rep(1:2, each = 2), B = c(100, 200, 20, 400), speciesCode = rep(c("Pice_Gla", "Popu_Tre"), 2) ) vegTypeGenerator(x)
Generate vegetation type map
vegTypeMapGenerator(x, ...) ## Default S3 method: vegTypeMapGenerator(x, ..., doAssertion = getOption("LandR.assertions", FALSE)) ## S3 method for class 'data.table' vegTypeMapGenerator( x, pixelGroupMap, vegLeadingProportion = 0.8, mixedType = 2, sppEquiv = NULL, sppEquivCol, colors, pixelGroupColName = "pixelGroup", doAssertion = getOption("LandR.assertions", TRUE), ... )vegTypeMapGenerator(x, ...) ## Default S3 method: vegTypeMapGenerator(x, ..., doAssertion = getOption("LandR.assertions", FALSE)) ## S3 method for class 'data.table' vegTypeMapGenerator( x, pixelGroupMap, vegLeadingProportion = 0.8, mixedType = 2, sppEquiv = NULL, sppEquivCol, colors, pixelGroupColName = "pixelGroup", doAssertion = getOption("LandR.assertions", TRUE), ... )
x |
Either a |
... |
Additional arguments. |
doAssertion |
A logical indicating whether some internal tests should be run to
ensure the function is running correctly.
Default: |
pixelGroupMap |
A |
vegLeadingProportion |
Numeric between 0-1, determining the relative biomass threshold a species needs to pass to be considered "leading". |
mixedType |
An integer defining whether mixed stands are: not differentiated (0), any kind of species admixture (1), or deciduous mixed with conifer (2; default). |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
colors |
A named vector of colour codes. The names MUST match the names of species
in |
pixelGroupColName |
Name of the column in |
Eliot McIntire, Ceres Barros, Alex Chubaty
library(data.table) library(terra) x <- data.table( pixelGroup = rep(1:2, each = 2), B = c(100, 200, 20, 400), speciesCode = rep(c("Pice_Gla", "Popu_Tre"), 2) ) pixelGroupMap <- rast(ext(0, 3, 0, 3), res = 1) pixelGroupMap[] <- sample(1:2, size = 9, replace = TRUE) vtm <- vegTypeMapGenerator(x, pixelGroupMap = pixelGroupMap)library(data.table) library(terra) x <- data.table( pixelGroup = rep(1:2, each = 2), B = c(100, 200, 20, 400), speciesCode = rep(c("Pice_Gla", "Popu_Tre"), 2) ) pixelGroupMap <- rast(ext(0, 3, 0, 3), res = 1) pixelGroupMap[] <- sample(1:2, size = 9, replace = TRUE) vtm <- vegTypeMapGenerator(x, pixelGroupMap = pixelGroupMap)
Create a summaries of vegetation type transitions
Plot vegetation type transitions
vtm2conifdecid(vtm, sppEquiv = NULL, sppEquivCol = "LandR", zones) vegTransitions(vtm, zones, field, times, na.rm = FALSE, dest = ".") plotVegTransitions(transitions_df)vtm2conifdecid(vtm, sppEquiv = NULL, sppEquivCol = "LandR", zones) vegTransitions(vtm, zones, field, times, na.rm = FALSE, dest = ".") plotVegTransitions(transitions_df)
vtm |
character vector of file paths to vegetation type maps (see |
sppEquiv |
table with species name equivalencies between the kNN and final naming formats.
See |
sppEquivCol |
the column name to use from |
zones |
|
field |
character string of the column name in |
times |
numeric vector of years corresponding to |
na.rm |
logical. If |
dest |
character, specifying a destination directory |
transitions_df |
A data frame with columns |
vtm2conifdecid() returns a character vector of file paths to the conifer-deciduous maps.
vegTransitions() returns a arrow dataset with columns pixelID, zone, vegType,
and time.
plotVegTransitions() returns a list of ggplot objects, one for each zone.
creating these plots for large landscapes can be computationally intensive (time and memory use).
A probability distribution used in LANDIS-II.
Ward(dist, cellSize, effDist, maxDist, k, b, algo = 2)Ward(dist, cellSize, effDist, maxDist, k, b, algo = 2)
dist |
A vector of distances to evaluate kernel against |
cellSize |
A numeric, length 1, of the cell resolution (e.g., res(raster)) |
effDist |
A vector of effective distance (parameter in kernel),
with same length as |
maxDist |
A vector of maximum distance (parameter in kernel),
with same length as |
k |
A parameter in the kernel |
b |
A parameter in the kernel |
algo |
Either 1 or 2. 1 is "simpler code" as it uses |
Eliot McIntire