Package 'CBMutils'

Title: Utilities for modelling carbon based on CBM-CFS3
Description: Implementation of several components of the Carbon Budget Model of the Canadian Forest Service (v3).
Authors: Céline Boisvenue [aut, cre], Alex M Chubaty [aut] (ORCID: <https://orcid.org/0000-0001-7146-8135>), Eliot McIntire [aut], Ian Eddy [ctb], Camille Giuliano [ctb], Susan Murray [ctb], Dominique Caron [ctb]
Maintainer: Céline Boisvenue <[email protected]>
License: GPL-3
Version: 2.5.4.9002
Built: 2026-05-25 21:11:40 UTC
Source: https://github.com/PredictiveEcology/CBMutils

Help Index


Adjust cohort ages

Description

Adjust cohort ages to represent a year before or after a given date. Optionally include disturbance events that reset ages to year 0.

Usage

adjustCohortAges(
  cohortAges,
  yearInput,
  yearOutput,
  disturbanceEvents = NULL,
  delay = NULL,
  default = NULL,
  warn = TRUE
)

Arguments

cohortAges

data.table. Table of cohort ages with an ID column and the numeric columns 'age'. Optionally include a 'delay' column with regeneration delays for each cohort. A standard delay can also be provided with the delay argument. Optionally include a 'default' column with the default age for the cohort if it cannot be otherwise calculated. A default age can also be provided with the default argument.

yearInput

integer. The year that the 'ages' column in cohortAges represents.

yearOutput

integer. The year that cohort ages must be adjusted to.

disturbanceEvents

data.table. Optional. Table of disturbance events with the ID column in cohortAges and another column 'year' of when the disturbance occurred. This can also include rows for years that cohorts were first established.

delay

integer. Optional. Regeneration delay after a disturbance event.

default

integer. A default age for cohorts is otherwise unknown. If yearOutput precedes yearInput, the age cannot be calculated for cohorts that have disturbances between yearOutput and yearInput but none before yearOutput. default will be assigned in these cases. NOTE: if a cohort has an age lesser than the difference in these years, it is assumed that a disturbance event must have occurred when age == 0. default will be assigned in these cases.

warn

logical. Warn if ages cannot be calculated or if the provided disturbances do not match the input data.

Value

cohortAges with ages adjusted to yearOutput.


Age Step Backwards

Description

Step an age raster backwards in time. Ages that are set as <0 are replaced with surrounding ages >0 with idw_replace.

Usage

ageStepBackward(
  ageRast,
  yearIn,
  yearOut,
  distEvents = NULL,
  fill = TRUE,
  fillLT0 = TRUE,
  idp = 2,
  nmax = 100,
  ...,
  agg.fact = 1,
  agg.fun = "median",
  agg.na.rm = TRUE
)

Arguments

ageRast

SpatRaster. Raster with numeric values of cohort ages.

yearIn

numeric. Year that ages in ageRast represent.

yearOut

numeric. Year that ages will be stepped backwards to.

distEvents

data.table. Optional. Table of disturbance events with columns "pixelIndex" and "year". If provided, disturbances will be reversed and the disturbed areas will be filled with idw_replace.

fill

logical. Fill disturbed areas with values interpolated from surrounding cells.

fillLT0

logical. Fill cells with ages <0 with values interpolated from surrounding cells.

idp

numeric. IDW power.

nmax

numeric. The maximum number of nearest observations to use.

...

additional arguments to idw_replace.

agg.fact

Aggregation factor for the input raster. If >1, the raster will be aggregated before cell values are extracted as input data points for interpolation. This smooths the input data and speeds up the interpolation process. See aggregate.

agg.fun

Aggregation function.

agg.na.rm

Remove NA cells when aggregating.

Value

SpatRaster


Extract alternative set of parameters to apply to convert total biomass into pool biomass.

Description

When there is no match for the given ecozone, the parameters for a different ecozone in the same province/territory is returned. If there is no match for a given province/territory, the parameters for a different province/territory in the same ecozone is returned. If there is no match for the given ecozone and province/territory, the parameters for a different location is returned.

Usage

alternativeParams(params, table, cols)

Arguments

params

data.table containing a row for each curve with all required parameters.

table

data.table of the parameters.

cols

vector of parameter column names.

Value

A single data.table containing a row for each curve with all required parameters from both table6, table7, and tableMerchantability.


Calculate stemwood biomass (per ha) of live merchantable trees

Description

Implements equation 1 of Boudewyn et al. (2007) to determines the total stemwood biomass of merchantable trees (in metric tonnes per hectare; T/haT/ha), using parameters aa and bb from Table 3 (table3).

Usage

b_m(table3, vol)

Arguments

table3

data.frame corresponding to Table 3 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table3.csv.

vol

gross merchantable volume per hectare (m3/ham^3/ha)

Value

stemwood biomass of merchantable trees (bmb_m in units T/haT/ha)

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


Proportions of total tree biomass in stemwood, bark, branches, and foliage

Description

Implements equations 4-7 of Boudewyn et al. (2007), used to determine the proportions of total tree biomass in stemwood, bark, branches, and foliage (pstemwoodp_{stemwood}, pbarkp_{bark}, pbranchesp_{branches}, pfoliagep_{foliage}, respectively), using parameters aa, bb from Table 6 (table6) and volume-proportion caps from Table 7 (table7).

Usage

biomProp(table6, table7, x, type = "volume")

Arguments

table6

data.frame corresponding to Table 6 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table6.csv. The alternative table 6 for equations using total biomass as independent variable is available from https://nfi.nfis.org/resources/biomass_models/appendix2_table6_tb.csv.

table7

data.frame corresponding to Table 7 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table7.csv. The alternative table 7 for equations using total biomass as independent variable is available from https://nfi.nfis.org/resources/biomass_models/appendix2_table7_tb.csv.

x

vector gross merchantable volume per hectare (m3/ham^3/ha) or total biomass (tonnes/hatonnes/ha)

type

character specifies if the x represents gross merchantable volume per hectare ("volume") or total biomass ("biomass").

Details

TODO: will eventually add species, ecozone

Value

four-column matrix will columns corresponding to pstemwoodp_{stemwood}, pbarkp_{bark}, pbranchesp_{branches}, and pfoliagep_{foliage}

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


Calculates proportions of total tree biomass in stemwood, bark, branches, and foliage.

Description

Implements equations 4-7 of Boudewyn et al. (2007) adapted for biomass input using parameters aa, bb, and ccfrom Table 6 (table6) and biomass-proportion caps from Table 7 (table7).

Usage

biomPropAGB(AGBwithParams)

Arguments

AGBwithParams

data.frame with both the total aboveground biomass B to split and the parameters extracted from tables 6 and 7.

Value

four-column matrix will columns corresponding to pstemwoodp_{stemwood}, pbarkp_{bark}, pbranchesp_{branches}, and pfoliagep_{foliage}

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


Subset Boudewyn tables to fit study area

Description

Subset Boudewyn tables to fit study area

Usage

boudewynSubsetTables(table, thisAdmin)

Arguments

table

Boudewyn table to subset

thisAdmin

Table defining study area with columns juris_id: jurisdiction abbreviation(s); and ecozone: ecozone ID(s).

Value

smallTable data.table


Sum carbon for totalCarbon or aboveGround or belowGround

Description

Sum carbon for totalCarbon or aboveGround or belowGround

Usage

calcC(cbmPools, poolToSum, masterRaster)

Arguments

cbmPools

DESCRIPTION NEEDED

poolToSum

DESCRIPTION NEEDED

masterRaster

SpatRaster template defining the study area.

Value

DESCRIPTION NEEDED


calcRootC

Description

calcRootC calculates the mass of carbon in roots pools from above ground pools

Usage

calcRootC(
  aboveGroundC,
  sw_hw,
  a_sw = 0.222,
  b_sw = 1,
  a_hw = 1.576,
  b_hw = 0.615,
  a_frp = 0.072,
  b_frp = 0.354,
  c_frp = -0.060212,
  biomassToCarbonRate = 0.5
)

Arguments

aboveGroundC

data.table with mass of carbon (tonnes/ha) in the Merch, Foliage and Other pools

sw_hw

a boolean vector indicating if the cohort is softwood (0) or hardwood (1)

a_sw

"a" value for softwood root biomass

b_sw

"b" value for softwood root biomass

a_hw

"a" value for hardwood root biomass

b_hw

"b" value for hardwood root biomass

a_frp

"a" value for fine root proportion

b_frp

"b" value for fine root proportion

c_frp

"c" value for fine root proportion

biomassToCarbonRate

Conversion factor of biomass to carbon

Value

data.table with mass of carbon (tonnes/ha) in coarseRoots and fineRoots pools.

References

Li, Z., Kurz, W. A., Apps, M. J., & Beukema, S. J. (2003). Belowground biomass dynamics in the Carbon Budget Model of the Canadian Forest Sector: recent improvements and implications for the estimation of NPP and NEP. Canadian journal of forest research, 33(1), 126-136.


CBM4: mapNPP

Description

Map Net Primary Productivity (NPP) across a study area.

Usage

cbm4MapNPP(cbm4_results, years = NULL, yearStart = 1)

Arguments

cbm4_results

character or SQLResultsProcessor. Path to CBM4 spatial datasets directory or a SQLResultsProcessor object created with cbm4_results_processor.

years

integer. Year(s) of simulation results.

yearStart

integer. Simulation start year.

Value

ggplot


CBM4: mapTotalCarbon

Description

Map total carbon across a study area.

Usage

cbm4MapTotalCarbon(cbm4_results, years = NULL, yearStart = 1)

Arguments

cbm4_results

character or SQLResultsProcessor. Path to CBM4 spatial datasets directory or a SQLResultsProcessor object created with cbm4_results_processor.

years

integer. Year(s) of simulation results.

yearStart

integer. Simulation start year.

Value

ggplot


CBM4: plotEmissionsProducts

Description

Map total carbon across a study area.

Usage

cbm4PlotEmissionsProducts(cbm4_results, years = NULL, yearStart = 1)

Arguments

cbm4_results

character or SQLResultsProcessor. Path to CBM4 spatial datasets directory or a SQLResultsProcessor object created with cbm4_results_processor.

years

integer. Year(s) of simulation results.

yearStart

integer. Simulation start year.

Value

ggplot


CBM4: plotPoolProportions

Description

CBM4: plotPoolProportions

Usage

cbm4PlotPoolProportions(cbm4_results, years = NULL, yearStart = 1)

Arguments

cbm4_results

character or SQLResultsProcessor. Path to CBM4 spatial datasets directory or a SQLResultsProcessor object created with cbm4_results_processor.

years

integer. Year(s) of simulation results.

yearStart

integer. Simulation start year.

Value

ggplot


CBM source: Extract to raster

Description

Prepare a data source from the CBMsources table with link[reproducible]{prepInputs}, then align the data with a template raster and extract values for each cell with link{extractToRast}.

Usage

CBMsourceExtractToRast(sourceID, templateRast, returnSource = FALSE, ...)

Arguments

sourceID

Source identifier.

templateRast

SpatRaster. Raster template.

returnSource

logical. Return the source spatial data object.

...

additional arguments to link[reproducible]{prepInputs}


CBM source: Prep inputs

Description

Prepare a data source from the CBMsources table with link[reproducible]{prepInputs}.

Usage

CBMsourcePrepInputs(
  sourceID,
  inputPath = getOption("spades.inputPath", "."),
  ...
)

Arguments

sourceID

Source identifier.

inputPath

character. Path of download destination directory. Downloads will be sorted into subdirectories by data provider and region.

...

additional arguments to link[reproducible]{prepInputs}


CBM Data Sources

Description

Data sources for CBM simulations. These can be read with CBMsourcePrepInputs.

Usage

CBMsources

Format

A data table with 8 columns and 6 rows:

sourceID

Source identifier.

provider

Data provider or inventory identifier.

year

Data year. The year that the data represents or was published.

region

Spatial domain. Defaults to all of Canada.

attr

Cohort or stand attribute defined by the source.

type

Spatial data type: 'vector' or 'raster'.

source

Data table of one or more downloadable data sources:

  • url: Download URL of target data source.

  • targetFile: File name of target data source.

  • layer: Vector or raster layer.

  • field: Vector attribute field.

  • subattr: If the source is comprised of multiple vector fields or raster layers, this secondary attribute distinguishes each one.

...


Convert total above ground biomass into 3 pools (T/haT/ha).

Description

Implements the flowchart from figure 3 of Boudewyn et al. (2007) using an alternative set of parameter to divide total above ground biomass (T/haT/ha) into total merchantable stemwood biomass (T/haT/ha), foliage biomass (T/haT/ha), and other wood biomass (T/haT/ha).

Usage

convertAGB2pools(AGB, allParams)

Arguments

AGB

data.frame with at least four following columns: canfi_species, ecozone, juris_id, and B.

allParams

data.frame containing a row for each curve with all required parameters of both table6 and table7 from Boudewyn et al. (2007) and parameters on merchantability of stemwood.

Value

three-column matrix with columns corresponding to biomass (T/haT/ha) for total merchantable, foliage, and other wood.

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


Calculate biomass from gross merchantable volume

Description

Implements the flowchart from figure 3 of Boudewyn et al. (2007) to determined the total above ground biomass (T/haT/ha) from gross merchantable volume (m3/ham^3/ha).

Usage

convertM3biom(
  meta,
  gCvalues,
  spsMatch,
  ecozones,
  params3,
  params4,
  params5,
  params6,
  params7
)

Arguments

meta

Growth curve metadata

gCvalues

Growth curve volume values for each age

spsMatch

Species associated with growth curve

ecozones

Ecozone associated with the growth curve

params3

data.frame corresponding to Table 3 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table3.csv.

params4

data.frame corresponding to Table 4 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table4.csv.

params5

data.frame corresponding to Table 5 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table5.csv.

params6

data.frame corresponding to Table 6 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table6.csv.

params7

data.frame corresponding to Table 7 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table7.csv.

Value

three-column matrix with columns corresponding to biomass (T/haT/ha) for total merchantable, foliage, and other.

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


cTransfersAlluvial

Description

Maps proportions of carbon transfers across pools during a disturbance.

Usage

cTransfersAlluvial(
  cTransfers,
  distMatrixID = NULL,
  distName = NULL,
  spuID = NULL,
  sw = NULL,
  nearMatches = TRUE,
  identical = !ask,
  ask = interactive(),
  ...
)

Arguments

cTransfers

Carbon pool transfer matrix

distMatrixID

disturbance_matrix_id of the disturbance to plot.

distName

disturbance name you wish to plot. Required only if distMatrixID is not provided.

spuID

CBM-CFS3 spatial unit ID of the disturbance to plot. Required only if distMatrixID is not provided.

sw

logical. Softwood (TRUE) or hardwood (FALSE). Required only if distMatrixID is not provided.

nearMatches

logical. Allow for near matches; e.g. "clearcut" can match "clear-cut".

identical

logical. Require identical matches.

ask

logical. If TRUE, prompt the user to choose the correct matches. If FALSE, the function will look for a single match to each input.

...

additional arguments to .matchSelect

Value

alluvialDist Alluvial plot of a disturbance in a specific spatial unit.


Create cumPools data.table

Description

Create cumPools data.table

Usage

cumPoolsCreate(
  fullSpecies,
  gcMeta,
  userGcM3,
  stable3,
  stable4,
  stable5,
  stable6,
  stable7,
  thisAdmin,
  biomassToCarbonRate = 0.5
)

Arguments

fullSpecies

Study area species' names

gcMeta

Growth curve metadata table

userGcM3

Table of growth curve volume by age

stable3

Boudewyn et al. 2007 stem wood biomass model parameters table for merchantable-sized trees

stable4

Boudewyn et al. 2007 stem wood biomass model parameters table for non-merchantable-sized trees

stable5

Boudewyn et al. 2007 stem wood biomass model parameters table for sapling-sized trees

stable6

Boudewyn et al. 2007 stem wood biomass model parameters table for proportion model parameters

stable7

Boudewyn et al. 2007 stem wood biomass model parameters table for caps on proportion models

thisAdmin

Ecozone and spatial unit information table for the study area

biomassToCarbonRate

Conversion factor of biomass to carbon

Value

cumPools data.table


Convert total above ground biomass into 3 pools (T/haT/ha).

Description

Implements the flowchart from figure 3 of Boudewyn et al. (2007) using an alternative set of parameter to divide total above ground biomass (T/haT/ha) into total merchantable stemwood biomass (T/haT/ha), foliage biomass (T/haT/ha), and other wood biomass (T/haT/ha).

Usage

cumPoolsCreateAGB(
  allInfoAGBin,
  table6,
  table7,
  tableMerchantability,
  pixGroupCol,
  biomassToCarbonRate = 0.5
)

Arguments

allInfoAGBin

data.frame with at least six following columns: canfi_species, speciesCode, ecozone, juris_id, age, B and a column for pixel group identifier.

table6

data.frame corresponding to Table 3 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table6_tb.csv.

table7

data.frame corresponding to Table 4 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table7_tb.csv.

tableMerchantability

data.frame Parameters to estimate the proportion of stemwood that is merchantable, approximates the relationship between stemwood biomass and nonmerchfactor predicted by equation 2 of Boudewyn et al., 2007.

pixGroupCol

the name of the column in allInfoAGBin serving as the pixel group identifier.

biomassToCarbonRate

Conversion factor of biomass to carbon

Value

biomass (T/haT/ha) in each above ground pool for each cohort per pixel group.

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


Smooth the cumPools data.table

Description

This uses the Chapman Richards equation to smooth the curves that are in colsToUse.

Usage

cumPoolsSmooth(
  cumPoolsRaw,
  colsToUse = c("totMerch", "fol", "other"),
  colsToUseNew = paste0(colsToUse, "_New")
)

Arguments

cumPoolsRaw

Data.table with a numeric column called ⁠age`` and columns called ⁠colsToUse'.

colsToUse

A character vector of columns to smooth.

colsToUseNew

A character vector of column names for the new smoothed columns

Value

#' A data.table with original columns plus new columns named 'colsToUseNew“.

Author(s)

Celine Boisvenue and Eliot McIntire


CBM-CFS3 Disturbance types

Description

List CBM-CFS3 disturbance types.

Usage

distList(cbm_defaults_db, localeID = 1)

Arguments

cbm_defaults_db

Path to CBM defaults SQLite database.

localeID

CBM-CFS3 locale_id

Value

data.table with 'disturbance_type_tr' columns 'disturbance_type_id', 'name', 'description'


CBM-CFS3 Disturbances Match

Description

Match disturbance names with CBM-CFS3 disturbance types.

Usage

distMatch(
  distNames,
  nearMatches = TRUE,
  identical = !ask,
  ask = interactive(),
  listDist = NULL,
  cbm_defaults_db = NULL,
  localeID = 1,
  ...
)

Arguments

distNames

character. Disturbance names to match with CBM-CFS3 database disturbance type names.

nearMatches

logical. Allow for near matches; e.g. "clearcut" can match "clear-cut".

identical

logical. Require identical matches.

ask

logical. If TRUE, prompt the user to choose the correct matches. If FALSE, the function will look for a single match to each input.

listDist

data.table. Optional. Result of a call to distList. Table of disturbance types with columns 'disturbance_type_id', 'name', 'description'.

cbm_defaults_db

Path to CBM defaults SQLite database.

localeID

CBM-CFS3 locale_id

...

additional arguments to .matchSelect

Value

data.table with columns 'disturbance_type_id', 'name', 'description'


Extract to raster

Description

Extract values from a spatial data source for each cell of a template raster. Resampling is done using "mode" resampling to preserve categorical values.

Usage

extractToRast(input, templateRast, index = 1, crop = TRUE)

Arguments

input

terra SpatRaster, one or more raster files, or sf polygons.

templateRast

SpatRaster. Raster template.

index

numeric or character. Raster layer or vector field to extract.

crop

logical. Crop input before alignment to template raster.

Value

vector with a value for each cell of templateRast. Data type matches input data type.


Standardized way to create gcids

Description

This uses the underscore delimiter between column names.

Usage

gcidsCreate(...)

Arguments

...

The data.table with ONLY the columns on which to determine unique gcids


Extract the parameters to apply to convert total biomass into pool biomass.

Description

Extract the species- and location- specific parameters for equation 4-7 of Boudewyn et al. (2007). If there is no match for the given ecozone, the parameters for a different ecozone in the same province/territory is returned. If there is no match for a given province/territory, the parameters for a different province/territory in the same ecozone is returned. If there is no match for the given ecozone and province/territory, the parameters for a different location is returned.

Usage

getParameters(table6, table7, tableMerchantability, curves)

Arguments

table6

data.frame corresponding to Table 3 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table6_tb.csv.

table7

data.frame corresponding to Table 4 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table7_tb.csv.

tableMerchantability

data.frame Parameters to estimate the proportion of stemwood that is merchantable, approximates the relationship between stemwood biomass and nonmerchfactor predicted by equation 2 of Boudewyn et al., 2007.

curves

A data.table with unique combinations of canfi_species, ecozone, juris_id.

Value

A single data.table containing a row for each curve with all required parameters from both table6, table7, and tableMerchantability.

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


Makes plots of all columns for each id_col ID

Description

Makes plots of all columns for each id_col ID

Usage

m3ToBiomPlots(inc, id_col = "gcids", title)

Arguments

inc

increment data

id_col

column by which to group plots

title

Title of plots


mapNPP

Description

Map Net Primary Productivity (NPP) across a study area.

Usage

mapNPP(rastNPP, year = NULL)

Arguments

rastNPP

SpatRaster. Pixel values represent NPP (t/ha).

year

numeric. Year that the map represents. If provided, it will be included in the plot title.

Value

ggplot


mapTotalCarbon

Description

Map total carbon across a study area.

Usage

mapTotalCarbon(rastTC, year = NULL)

Arguments

rastTC

SpatRaster. Pixel values represent total carbon (t/ha).

year

numeric. Year that the map represents. If provided, it will be included in the plot title.

Value

ggplot


Expansion factor for non-merchantable live tree biomass

Description

Implements equation 2 of Boudewyn et al. (2007), used to determine the total stem wood biomass (in metric tonnes per hectare; T/haT/ha) of non-merchantable trees (BnB_n), together with the stemwood biomass of live merchantable and non-merchantable trees (BnmB_{nm}), using parameters aa, bb, and kk from Table 4 (table4).

Usage

nmfac(table4, eq1, vol)

Arguments

table4

data.frame corresponding to Table 4 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table4.csv.

eq1

stemwood biomass of merchantable trees (T/haT/ha) from equation 1 of Boudewyn et al. (2007) (i.e., the result of b_m).

vol

gross merchantable volume per hectare (m3/ham^3/ha)

Value

two-column matrix with columns corresponding to bnb_n and bnmb_{nm}

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


plotEmissionsProducts

Description

Plot yearly emissions and products.

Usage

plotEmissionsProducts(emissionsProducts)

Arguments

emissionsProducts

Table of simlation emissions and products by cohort group by year

Value

ggplot


plotPoolProportions

Description

plotPoolProportions

Usage

plotPoolProportions(pools)

Arguments

pools

data.table. Table of pools for each cohort, pixel, or year. Must include the 'year' column.

Value

ggplot


Calculates the proportion of total stemwood considered merchantable.

Description

Calculates the proportion of total stemwood considered merchantable.

Usage

propMerch(totalStemWood, age, params)

Arguments

totalStemWood

numeric Total Stemwood vector.

age

numeric Age of the cohort.

params

data.table Parameters to calculate propotion of merchantable stemwood.

Value

numeric Vector of the proportion of stemwood that is merchantable.


Reticulate Find Python

Description

Use reticulate to find or install Python to meet version requirements. Download and use the pyenv-win Python version management tool from Github if necessary.

Usage

ReticulateFindPython(
  version,
  versionInstall = version,
  pyenvRoot = tools::R_user_dir("CBMutils"),
  pyenvOnly = FALSE,
  useGit = TRUE,
  prompt = FALSE
)

Arguments

version

character. Python version or a comma separated list of version constraints. See virtualenv_starter for more details.

versionInstall

character. Version to install if suitable version not found. Required if version is a list of version constraints.

pyenvRoot

character. Path of location for install of the pyenv-win tool. Defaults to the R user data directory.

pyenvOnly

logical. Exclude versions not within a pyenv install directory.

useGit

logical. Allow reticulate to clone pyenv-win if Git is available.

prompt

logical. Prompt user to approve download of pyenv-win tool.

Details

This function was created to bypass the requirement for Git to be installed when install_python is called on a Windows computer without pyenv-win already installed. If Git is available, reticulate will clone the pyenv-win Github repository and use the tool to install Python. If Git is not available, this function will instead download the latest version directly from the repository and make it available to reticulate.

Value

character. Path to Python interpreter.


Expansion factor for sapling-sized trees

Description

Implements equation 3 of Boudewyn et al. (2007), used to determine the total stem wood biomass (in metric tonnes per hectare; T/haT/ha) of sapling-sized trees (BsB_s), using parameters aa, bb, and kk from Table 5 (table5).

Usage

sapfac(table5, eq2, vol)

Arguments

table5

data.frame corresponding to Table 5 from Boudewyn et al. (2007), available from https://nfi.nfis.org/resources/biomass_models/appendix2_table5.csv.

eq2

two-column matrix giving stemwood biomass of non-merchantable trees (i.e., bnb_n given in units T/haT/ha), and merchantable + non-merchantable trees (i.e., bnmb_{nm} given in units T/haT/ha), from equation 2 of Boudewyn et al. (2007) (i.e., the result of nmfac).

vol

gross merchantable volume per hectare (m3/ham^3/ha)

Value

stemwood biomass of sapling-sized trees (bsb_s in units T/haT/ha)

References

Boudewyn, P., Song, X., Magnussen, S., & Gillis, M. D. (2007). Model-based, volume-to-biomass conversion for forested and vegetated land in Canada (BC-X-411). Natural Resource Canada, Pacific Forestry Centre. https://cfs.nrcan.gc.ca/pubwarehouse/pdfs/27434.pdf


See disturbances

Description

Retrieve disturbance source pools, sink pools, and the proportions transferred.

Usage

seeDist(
  EXN = TRUE,
  matrixIDs = NULL,
  cbm_defaults_db = NULL,
  cbm_exn_dir = NULL
)

Arguments

EXN

logical. Use CBM-EXN CBM-CFS3 equivalent model data.

matrixIDs

character. Optional. Subset disturbances by disturbance_matrix_id

cbm_defaults_db

Path to CBM defaults SQLite database.

cbm_exn_dir

Path to CBM-EXN parameters directory.

Value

List of data.frame named by disturbance_matrix_id


simList: Read SpaDES CBM database

Description

Read a raw data table from a simulation's CBM_core SpaDES CBM database.

Usage

simCBMdbReadRaw(simCBM, year, table, ...)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

year

numeric. Year of simulation results. Defaults to the current simulation year.

table

character. Name of database table to read. One of 'key', 'parameters', 'state', 'flux', or 'pools'.

...

not used

Value

data.table


simList: Read SpaDES CBM database summary

Description

Read a data summary from a simulation's CBM_core SpaDES CBM database.

Usage

simCBMdbReadSummary(
  simCBM,
  summary,
  by = "cohortID",
  units = "t/ha",
  year = NULL,
  years = NULL,
  useCache = TRUE
)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

summary

character. Name of summary table to collect.

by

character. Name of field to summarize results by. Data can be summarized by 'cohortID', 'pixelIndex', or 'year'

units

character. 't/ha', 't', or 'Mt'.

year

numeric. Year of simulation results. Required if ⁠by = 'cohortID' or 'pixelIndex'⁠. Defaults to the current simulation year.

years

numeric. Years of simulation results to summarize. Required if by = 'year'. Defaults to the full simulation time span.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

data.table with key matching the by argument.


simList: Read SpaDES CBM database table

Description

Read a table of cohort data from a simulation's CBM_core SpaDES CBM database.

Usage

simCBMdbReadTable(simCBM, year, table, useCache = TRUE)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

year

numeric. Year of simulation results. Defaults to the current simulation year.

table

character. Name of database table to read. One of 'key', 'parameters', 'state', 'flux', or 'pools'.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

data.table with key 'cohortID', columns 'pixelIndex' and 'row_idx' (cohort group ID), and any additional columns in the source table.


simList: Write SpaDES CBM database

Description

Write simulation CBM_core module data to the SpaDES CBM database.

Usage

simCBMdbWrite(
  simCBM,
  year,
  parameters = TRUE,
  state = TRUE,
  flux = TRUE,
  pools = TRUE
)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

year

numeric. Simulation data year. Defaults to the current simulation year.

parameters

logical. Write the 'parameters' table to file.

state

logical. Write the 'state' table to file.

flux

logical. Write the 'flux' table to file.

pools

logical. Write the 'pools' table to file.


See disturbances in simList

Description

get the descriptive name and proportions transferred for disturbances in a simulation requires a simulation list post simulations (from spades()) and returns a list of data.frames. Each data had the descriptive name of a disturbance used in the simulations, the disturbance matrix identification number from cbm_defaults, the pool from which carbon is taken (source pools) in this specific disturbance, the pools into which carbon goes, and the proportion in which the carbon-transfers are completed.

Usage

simDist(simCBM)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

Value

List of data.frame for each disturbance matrix id in the study area, named by disturbance name


simMapNPP

Description

Map Net Primary Productivity (NPP) across a study area.

Usage

simMapNPP(simCBM, year = NULL, useCache = TRUE)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

year

numeric. Year of simulation results. Defaults to the current simulation year.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


simMapTotalCarbon

Description

Map total carbon across a study area.

Usage

simMapTotalCarbon(simCBM, year = NULL, useCache = TRUE)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

year

numeric. Year of simulation results. Defaults to the current simulation year.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


simPlotEmissionsProducts

Description

Plot yearly emissions and products.

Usage

simPlotEmissionsProducts(simCBM, years = NULL, useCache = TRUE)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

years

numeric. Simulation years to include in plot. Defaults to all simulation years.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


simPlotPoolProportions

Description

simPlotPoolProportions

Usage

simPlotPoolProportions(simCBM, years = NULL, useCache = TRUE)

Arguments

simCBM

SpaDES.core simList for a CBM simulation including the CBM_core module.

years

numeric. Simulation years to include in plot. Defaults to all simulation years.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


spadesCBMdb: mapNPP

Description

Map Net Primary Productivity (NPP) across a study area.

Usage

spadesCBMdbMapNPP(spadesCBMdb, masterRaster, year, useCache = TRUE)

Arguments

spadesCBMdb

CBM_core module outputs database path.

masterRaster

SpatRaster template defining the study area.

year

numeric. Year of simulation results.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


spadesCBMdb simMapTotalCarbon

Description

Map total carbon across a study area.

Usage

spadesCBMdbMapTotalCarbon(spadesCBMdb, masterRaster, year, useCache = TRUE)

Arguments

spadesCBMdb

CBM_core module outputs database path.

masterRaster

SpatRaster template defining the study area.

year

numeric. Year of simulation results.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


spadesCBMdb plotEmissionsProducts

Description

Plot yearly emissions and products.

Usage

spadesCBMdbPlotEmissionsProducts(spadesCBMdb, years, useCache = TRUE)

Arguments

spadesCBMdb

CBM_core module outputs database path.

years

numeric. Simulation years to include in plot.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


spadesCBMdb simPlotPoolProportions

Description

spadesCBMdb simPlotPoolProportions

Usage

spadesCBMdbPlotPoolProportions(spadesCBMdb, years, useCache = TRUE)

Arguments

spadesCBMdb

CBM_core module outputs database path.

years

numeric. Simulation years to include in plot.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

ggplot


Read CBM SpaDES CBM database

Description

Read a raw data table from a CBM_core SpaDES CBM database.

Usage

spadesCBMdbReadRaw(spadesCBMdb, year, table, ...)

Arguments

spadesCBMdb

CBM_core module outputs database path.

year

numeric. Year of simulation results.

table

character. Name of database table to read. One of 'key', 'parameters', 'state', 'flux', or 'pools'.

...

not used

Value

data.table


Read CBM SpaDES CBM database summary

Description

Read a data summary from a CBM_core SpaDES CBM database.

Usage

spadesCBMdbReadSummary(
  spadesCBMdb,
  summary,
  by = "cohortID",
  units = "t/ha",
  year = NULL,
  years = NULL,
  useCache = TRUE
)

Arguments

spadesCBMdb

CBM_core module outputs database path.

summary

character. Name of summary table to collect.

by

character. Name of field to summarize results by. Data can be summarized by 'cohortID', 'pixelIndex', or 'year'

units

character. 't/ha', 't', or 'Mt'.

year

numeric. Year of simulation results. Required if ⁠by = 'cohortID' or 'pixelIndex'⁠.

years

numeric. Years of simulation results to summarize. Required if by = 'year'.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

data.table with key matching the by argument.


Read SpaDES CBM database table

Description

Read a table of cohort data from a CBM_core SpaDES CBM database.

Usage

spadesCBMdbReadTable(spadesCBMdb, year, table, useCache = TRUE)

Arguments

spadesCBMdb

CBM_core module outputs database path.

year

numeric. Year of simulation results.

table

character. Name of database table to read. One of 'key', 'parameters', 'state', 'flux', or 'pools'.

useCache

logical. Cache database query result to the database's cache directory with Cache.

Value

data.table with key 'cohortID', columns 'pixelIndex' and 'row_idx' (cohort group ID), and any additional columns in the source table.


Species match

Description

Retrieve species metadata by matching species names or other identifiers with columns in sppEquivalencies.

Usage

sppMatch(
  species,
  match = c("LandR", "Latin_full", "EN_generic_short", "EN_generic_full"),
  otherNames = NULL,
  return = NULL,
  checkNA = !is.null(return),
  sppEquivalencies = NULL
)

Arguments

species

Species identifiers.

match

character. sppEquivalencies column(s) to match species with.

otherNames

list. A list of alternative species identified to allow in matching. Item names must match species and item contents must be vectors of additional allowable matches.

return

character. sppEquivalencies columns to return. All columns will be returned by default.

checkNA

logical. Check for NA values in the returned columns. Defaults to TRUE if the return argument is used; otherwise FALSE.

sppEquivalencies

data.table. Table of species identifiers and metadata. Defaults to LandR::sppEquivalencies_CA.

Value

data.table. Subset of sppEquivalencies with 1 row per species.


CBM-CFS3 Spatial Unit Disturbances

Description

List the disturbances possible in spatial units.

Usage

spuDistList(
  EXN = TRUE,
  spuIDs = NULL,
  cbm_defaults_db = NULL,
  cbm_exn_dir = NULL,
  localeID = 1
)

Arguments

EXN

logical. Use CBM-EXN CBM-CFS3 equivalent model data.

spuIDs

Optional. Subset by spatial unit ID(s)

cbm_defaults_db

Path to CBM defaults SQLite database.

cbm_exn_dir

Path to CBM-EXN parameters directory.

localeID

CBM-CFS3 locale_id

Value

data.table with 'disturbance_type_tr' columns 'disturbance_type_id', 'name', 'description' and 'disturbance_matrix_association' columns 'spatial_unit_id' and 'disturbance_matrix_id'


CBM-CFS3 Spatial Unit Disturbances Match

Description

Match disturbance names with CBM-CFS3 spatial unit disturbances.

Usage

spuDistMatch(
  distTable,
  nearMatches = TRUE,
  identical = !ask,
  ask = interactive(),
  listDist = NULL,
  ...
)

Arguments

distTable

data.table with columns 'spatial_unit_id' and 'name' (or 'distName'). The name column will be matched with disturbance names and descriptions in the CBM-CFS3 database.

nearMatches

logical. Allow for near matches; e.g. "clearcut" can match "clear-cut".

identical

logical. Require identical matches.

ask

logical. If TRUE, prompt the user to choose the correct matches. If FALSE, the function will look for a single match to each input.

listDist

data.table. Optional. Result of a call to spuDistList. A list of possible disturbances in the spatial unit(s) with columns 'spatial_unit_id', 'disturbance_type_id', 'disturbance_matrix_id', 'name', 'description'.

...

arguments to spuDistList for listing the possible disturbances in the spatial units.

Value

data.table with columns 'spatial_unit_id', 'disturbance_type_id', 'disturbance_matrix_id', 'name', 'description'


CBM-CFS3 Historical Disturbances

Description

Identifies the stand-replacing wildfire disturbance in each spatial unit.

Usage

spuHistDist(spuIDs, localeID = 1, ask = FALSE, ...)

Arguments

spuIDs

Spatial unit ID(s)

localeID

CBM-CFS3 locale_id

ask

logical. If TRUE, prompt the user to choose the correct disturbance matches. If FALSE, the function will look for exact name matches.

...

arguments to spuDistMatch

Details

In all spatial units in Canada, the historical disturbance is set to fire. Historical disturbances in CBM-CFS3 are used for "filling-up" the soil-related carbon pools. Boudewyn et al. (2007) translate the m3/ha curves into biomass per ha in each of four pools: total biomass for stem wood, total biomass for bark, total biomass for branches and total biomass for foliage. Biomass in coarse and fine roots, in aboveground- and belowground- very-fast, -fast, -slow, in medium-soil, and in snags still needs to be estimated. A stand-replacing fire disturbance is used in a disturb-grow cycle, where stands are disturbed and regrown with turnover, overmature, decay, functioning until the dead organic matter pools biomass values stabilize (+/- 10%) (TODO: check this).


Write raster with values

Description

Replace the values in a SpatRaster before writing it to file.

Usage

writeRasterWithValues(templateRast, filename, cells = NULL, values = NULL, ...)

Arguments

templateRast

terra SpatRaster template defining raster geometry.

filename

character. Output filename.

cells

integer. Raster cell index.

values

numeric or character. New raster values.

...

arguments to writeRaster