Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Description: Builds landscape inputs for Canadian forest models from national
disturbances.
URL: https://github.com/PredictiveEcology/forestInputs
BugReports: https://github.com/PredictiveEcology/forestInputs/issues
Version: 0.0.1
Version: 0.0.1.9000
Authors@R: c(
person("Eliot J B", "McIntire", email = "eliot.mcintire@nrcan-rncan.gc.ca",
role = c("aut", "cre"), comment = c(ORCID = "0000-0002-6914-8316")),
Expand Down
9 changes: 9 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# forestInputs (development version)

* `prepInputsDisturbanceYear()` takes regional settings, each defaulting to the current rule, so results do not
change unless they are set (from Julie Turner's test in the southern interior BC mountains):
`polygonsBefore` (before it an NFDB polygon counts without Pre-CanLaD; `1950` counts Pre-CanLaD alone),
`prescribed` (keep prescribed burns), `harvest` (which Landsat records give harvest, or a layer of harvest
years such as BC cutblocks that replaces them), `unknownYear` (Pre-CanLaD's year 999) and `withType` (a
second layer, the type of the last disturbance: 1 fire, 2 harvest). A 30 m `rasterToMatch` gives 30 m output.

# forestInputs 0.0.1

* First version. Moved from LandR 1.2.0.9069, unchanged unless noted: `prepInputsDisturbanceYear()`,
Expand Down
157 changes: 133 additions & 24 deletions R/disturbanceYear.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,31 @@
#' alone do not count: 3-10 years after a 1972-1984 fire that NFDB and NBAC both mapped but Pre-CanLaD did
#' not, SCANFI biomass was 38 t/ha, against 17 t/ha where Pre-CanLaD agreed (58 t/ha in unburned forest).
#' Pre-CanLaD keeps one disturbance per cell, the last before 1985;
#' * before `agreeFrom`: Pre-CanLaD or an NFDB polygon. No record does well here (against provincial inventory
#' stand origins of 1950-1971, every rule found 14% or fewer), so both are used.
#' * before `polygonsBefore` (default `agreeFrom`, 1972): Pre-CanLaD or an NFDB polygon. No record does well
#' here (against provincial inventory stand origins of 1950-1971, every rule found 14% or fewer), so both are
#' used. In the southern interior BC mountains, 1950-1971 NFDB outlines that Pre-CanLaD does not see were
#' mostly older forest by VRI age (41% fitted the fire, against 81% where Pre-CanLaD saw it), so a region
#' can count Pre-CanLaD alone from 1950 with `polygonsBefore = 1950`; polygons before it still count.
#'
#' Without `"PreCanLaD"`, the polygons decide before `canladStart`: before `agreeFrom` (1972) an NFDB
#' polygon, then NFDB and NBAC polygons of the same year (or the one polygon source given). Without
#' `"CanLaD"` and `"NTEMS"`, the polygons decide from `canladStart` the same way.
#'
#' Prescribed burns are not stand-replacing and are dropped from NFDB and NBAC.
#' Prescribed burns are dropped from NFDB and NBAC unless `prescribed = TRUE`. Kept, they count where the
#' rule counts any polygon: from `canladStart` only where a Landsat record sees the fire (or, with
#' `polygonAgreement`, where both polygon sets map it).
#'
#' Harvest comes from the Landsat records in `harvest` (default all of CanLaD, NTEMS and Pre-CanLaD that are
#' in `sources`), or from a layer of harvest years such as provincial cutblocks, which then replaces them
#' and counts as it is.
#'
#' Regions differ. The rule tested in the southern interior BC mountains (Turner, 2026, for the caribou
#' cumulative effects tool) is `sources = "all", polygonAgreement = FALSE, polygonsBefore = 1950,
#' prescribed = TRUE`, with BC cutblocks as `harvest`: there NFDB and NBAC share BC's own perimeters, and fire
#' only the two polygon sets map was 75% unburned or low severity.
#'
#' For 30 m output, as a finer step before coarsening, pass a 30 m `rasterToMatch`; `minFraction` then
#' has no effect for the 30 m records.
#'
#' @template rasterToMatch
#' @param latestYear the year ages are for (`dataYear`): later disturbances are ignored.
Expand All @@ -59,9 +76,20 @@
#' @param minFraction share of a pixel's CanLaD, NTEMS or Pre-CanLaD cells that must be disturbed.
#' @param byYear `TRUE` returns every disturbance, not only the last (for a time since disturbance that ages
#' between data years, e.g. fireSense's `youngAge`).
#' @param polygonsBefore before this year an NFDB polygon counts even where Pre-CanLaD sees no disturbance.
#' `1950` (or `earliestYear`) counts Pre-CanLaD alone from 1950.
#' @param prescribed keep prescribed burns in NFDB and NBAC (`FALSE`: drop them).
#' @param harvest where harvest comes from: `NULL` (all of `"CanLaD"`, `"NTEMS"` and `"PreCanLaD"` that are in
#' `sources`), any of those three (`character(0)` for none), or a layer of harvest years that replaces them:
#' polygons (`SpatVector` or `sf`, e.g. BC's consolidated cutblocks) with the year in `harvestField`, or a
#' `SpatRaster` of harvest years.
#' @param harvestField the year field of `harvest` polygons.
#' @param unknownYear the year given to Pre-CanLaD disturbances of unknown year (999); its readme says 1955.
#' @param withType `TRUE` also returns the type of the last disturbance: a second layer, `type`, 1 fire and 2
#' harvest (fire when both happened in that year).
#'
#' @return A `SpatRaster` on `rasterToMatch` of the year of each pixel's last stand-replacing disturbance at
#' or before `latestYear`, `NA` where there was none. With `byYear = TRUE`, a list named by year of the
#' or before `latestYear`, `NA` where there was none; with `withType = TRUE`, two layers, `year` and `type`. With `byYear = TRUE`, a list named by year of the
#' disturbed pixels (cell numbers of `rasterToMatch`), as [disturbancesByYear()] gives.
#'
#' @export
Expand All @@ -77,16 +105,30 @@ prepInputsDisturbanceYear <- function(
ntemsURL = dirname(.input("ntems_fire")),
ntemsFiles = c(fire = sub("\\.tif$", "", .input("ntems_fire", "target_file")),
harvest = sub("\\.tif$", "", .input("ntems_harvest", "target_file"))),
polygonAgreement = TRUE, minFraction = 0.5, byYear = FALSE) {
polygonAgreement = TRUE, minFraction = 0.5, byYear = FALSE, polygonsBefore = agreeFrom,
prescribed = FALSE, harvest = NULL, harvestField = "HARVEST_YEAR", unknownYear = 1955L, withType = FALSE) {
latestYear <- as.integer(latestYear)
landsatHarvest <- c("CanLaD", "NTEMS", "PreCanLaD")
if (inherits(harvest, "sf")) harvest <- terra::vect(harvest)
if (is.null(harvest)) {
harvestFrom <- landsatHarvest
} else if (is.character(harvest)) {
bad <- setdiff(harvest, landsatHarvest)
if (length(bad)) stop("harvest must be NULL, any of \"CanLaD\", \"NTEMS\", \"PreCanLaD\", or a harvest layer; got ",
paste0("\"", bad, "\"", collapse = ", "))
harvestFrom <- harvest
} else if (inherits(harvest, c("SpatVector", "SpatRaster"))) {
harvestFrom <- character(0)
} else {
stop("harvest must be NULL, a character vector, a SpatVector (or sf) or a SpatRaster")
}
sources <- .disturbanceSources(sources)
polyYears <- function(url, src) {
if (is.null(url) || !src %in% sources) return(list())
fires <- .readFirePolys(url = url, destinationPath = destinationPath, rasterToMatch = rasterToMatch,
latestYear = latestYear, urlPre1972 = .nfdbPre1972URL(url, earliestYear))$fires
d <- as.data.frame(fires)
keep <- d$YEAR >= earliestYear
if ("PRESCRIBED" %in% names(d)) keep <- keep & !.isPrescribed(d$PRESCRIBED)
keep <- .keepFires(d, earliestYear, prescribed)
fires <- fires[which(keep), ]
if (!identical(terra::crs(fires), terra::crs(rasterToMatch))) fires <- terra::project(fires, rasterToMatch)
yrs <- sort(unique(as.integer(fires$YEAR)))
Expand Down Expand Up @@ -119,7 +161,7 @@ prepInputsDisturbanceYear <- function(
yr <- rd(preCanladFiles[["year"]])
yv <- terra::values(yr, mat = FALSE)
tv <- terra::values(rd(preCanladFiles[["type"]]), mat = FALSE)
yv[yv %in% 999L] <- 1955L # Pre-CanLaD's "unknown" year; its readme says to use 1955
yv[yv %in% 999L] <- as.integer(unknownYear) # Pre-CanLaD's "unknown" year; its readme says to use 1955
for (k in c("fire", "harvest")) {
types <- if (k == "fire") preCanladFireTypes else preCanladHarvestTypes
w <- which(yv >= earliestYear & yv < canladStart & yv <= latestYear & tv %in% types)
Expand All @@ -139,38 +181,63 @@ prepInputsDisturbanceYear <- function(
ntems[[k]] <- .yearFractions(v[w], w, r, rasterToMatch, minFraction)
}
}
userHarvest <- .harvestYears(harvest, harvestField, rasterToMatch, earliestYear, latestYear, minFraction)
byYr <- disturbancesByYear(
latestYear = latestYear, nfdb = polyYears(nfdbURL, "NFDB"), nbac = polyYears(nbacURL, "NBAC"),
canladFire = lapply(canlad, `[[`, "fire"), canladHarvest = lapply(canlad, `[[`, "harvest"),
preCanladFire = preCanlad$fire, preCanladHarvest = preCanlad$harvest,
ntemsFire = ntems$fire, ntemsHarvest = ntems$harvest, sources = sources, polygonAgreement = polygonAgreement,
canladStart = canladStart, agreeFrom = agreeFrom, earliestYear = earliestYear)
canladFire = lapply(canlad, `[[`, "fire"),
canladHarvest = if ("CanLaD" %in% harvestFrom) lapply(canlad, `[[`, "harvest") else list(),
preCanladFire = preCanlad$fire,
preCanladHarvest = if ("PreCanLaD" %in% harvestFrom) preCanlad$harvest else list(),
ntemsFire = ntems$fire, ntemsHarvest = if ("NTEMS" %in% harvestFrom) ntems$harvest else list(),
harvest = userHarvest, sources = sources, polygonAgreement = polygonAgreement,
canladStart = canladStart, agreeFrom = agreeFrom, earliestYear = earliestYear,
polygonsBefore = polygonsBefore, withType = withType)
if (isTRUE(byYear)) {
inRTM <- which(!is.na(terra::values(rasterToMatch, mat = FALSE)))
return(lapply(byYr, intersect, inRTM))
}
out <- lastDisturbanceYear(terra::ncell(rasterToMatch), latestYear, byYr)
terra::mask(terra::rast(rasterToMatch, vals = out), rasterToMatch)
r <- terra::mask(terra::rast(rasterToMatch, vals = out), rasterToMatch)
if (!isTRUE(withType)) return(r)
typ <- attr(byYr, "type")
tv <- rep(NA_integer_, length(out))
for (y in sort(as.integer(names(byYr)))) {
k <- as.character(y)
for (t in c(harvest = 2L, fire = 1L)) { # fire wins when a pixel has both in its last year
pix <- typ[[if (t == 1L) "fire" else "harvest"]][[k]]
pix <- pix[out[pix] %in% y]
tv[pix] <- t
}
}
r <- c(r, terra::mask(terra::rast(rasterToMatch, vals = tv), rasterToMatch))
names(r) <- c("year", "type")
r
}

#' @describeIn prepInputsDisturbanceYear the rule, on pixel indices: `nfdb`, `nbac`, `canladFire`,
#' `canladHarvest`, `ntemsFire`, `ntemsHarvest`, `preCanladFire` and `preCanladHarvest` are lists named by
#' year of the pixels each source flags that year. Returns a list named by year of the pixels the rule counts as disturbed that year (at or
#' before `latestYear`).
#' @param nfdb,nbac,canladFire,canladHarvest,ntemsFire,ntemsHarvest,preCanladFire,preCanladHarvest see the
#' description of `disturbancesByYear()`.
#' description of `disturbancesByYear()`. `harvest` (here) is a list named by year of pixels from a harvest
#' layer, which count as they are. With `withType = TRUE` the result has an attribute `type`, a list of two
#' such lists, `fire` and `harvest`.
#' @export
disturbancesByYear <- function(latestYear, nfdb = list(), nbac = list(), canladFire = list(),
canladHarvest = list(), preCanladFire = list(), preCanladHarvest = list(),
ntemsFire = list(), ntemsHarvest = list(), sources = "all", polygonAgreement = TRUE, canladStart = 1985L, agreeFrom = 1972L, earliestYear = 1950L) {
ntemsFire = list(), ntemsHarvest = list(), sources = "all", polygonAgreement = TRUE, canladStart = 1985L, agreeFrom = 1972L, earliestYear = 1950L,
harvest = list(), polygonsBefore = agreeFrom, withType = FALSE) {
sources <- .disturbanceSources(sources)
out <- list()
add <- function(pix, y) {
typ <- list(fire = list(), harvest = list())
add <- function(pix, y, type = "fire") {
y <- rep_len(as.integer(y), length(pix))
keep <- y <= latestYear & y >= earliestYear
for (yy in unique(y[keep])) {
k <- as.character(yy)
out[[k]] <<- sort(union(out[[k]], pix[keep & y == yy]))
p <- pix[keep & y == yy]
out[[k]] <<- sort(union(out[[k]], p))
if (isTRUE(withType)) typ[[type]][[k]] <<- sort(union(typ[[type]][[k]], p))
}
}
get <- function(l, y) { x <- l[[as.character(y)]]; if (is.null(x)) integer(0) else x }
Expand All @@ -189,8 +256,10 @@ disturbancesByYear <- function(latestYear, nfdb = list(), nbac = list(), canladF
if (length(pix)) add(pix, y)
}
if ("PreCanLaD" %in% sources) {
for (l in list(preCanladFire, preCanladHarvest))
for (t in as.integer(names(l))) if (t < canladStart) add(get(l, t), t)
for (k in c("fire", "harvest")) {
l <- if (k == "fire") preCanladFire else preCanladHarvest
for (t in as.integer(names(l))) if (t < canladStart) add(get(l, t), t, k)
}
}
## an NTEMS event within a year of a CanLaD one on the same pixel is the same event
nearIn <- function(pix, l, y) pix %in% c(get(l, y - 1L), get(l, y), get(l, y + 1L))
Expand All @@ -199,7 +268,7 @@ disturbancesByYear <- function(latestYear, nfdb = list(), nbac = list(), canladF
## origins), so NFDB polygons count as well as Pre-CanLaD; one within a year of a Pre-CanLaD event is the same
if ("PreCanLaD" %in% sources && "NFDB" %in% sources) {
for (y in sort(as.integer(names(nfdb)))) {
if (y >= agreeFrom || y >= canladStart) next
if (y >= polygonsBefore || y >= canladStart) next
pix <- get(nfdb, y)
pix <- pix[!nearIn(pix, out, y)]
if (length(pix)) add(pix, y)
Expand All @@ -220,16 +289,16 @@ disturbancesByYear <- function(latestYear, nfdb = list(), nbac = list(), canladF
}
for (t in as.integer(names(canladHarvest))) {
pix <- get(canladHarvest, t)
if (length(pix)) add(pix, t)
if (length(pix)) add(pix, t, "harvest")
}
}
if (useNtems) {
withCanlad <- "CanLaD" %in% sources
for (k in list(list(ntemsFire, canladFire), list(ntemsHarvest, canladHarvest))) {
for (k in list(list(ntemsFire, canladFire, "fire"), list(ntemsHarvest, canladHarvest, "harvest"))) {
for (y in as.integer(names(k[[1]]))) {
pix <- get(k[[1]], y)
if (withCanlad) pix <- pix[!nearIn(pix, k[[2]], y)]
if (y >= canladStart && length(pix)) add(pix, y)
if (y >= canladStart && length(pix)) add(pix, y, k[[3]])
}
}
}
Expand All @@ -242,7 +311,15 @@ disturbancesByYear <- function(latestYear, nfdb = list(), nbac = list(), canladF
if (length(pix)) add(pix, y)
}
}
out[order(as.integer(names(out)))]
## a harvest layer supplied by the user (e.g. provincial cutblocks) counts as it is
for (y in as.integer(names(harvest))) {
pix <- get(harvest, y)
if (length(pix)) add(pix, y, "harvest")
}
ord <- order(as.integer(names(out)))
out <- out[ord]
if (isTRUE(withType)) attr(out, "type") <- lapply(typ, function(l) l[order(as.integer(names(l)))])
out
}

#' @describeIn prepInputsDisturbanceYear each pixel's last year in `byYear` (from `disturbancesByYear()`) at or
Expand Down Expand Up @@ -273,6 +350,31 @@ lastDisturbanceYear <- function(n, latestYear, byYear) {
lapply(split(d$pix, d$year), as.integer)
}

## A harvest layer given to prepInputsDisturbanceYear(harvest = ): the pixels of rasterToMatch harvested each
## year, as a list named by year. Polygons (e.g. BC cutblocks): pixels whose centre is in a polygon of that
## year, as for NFDB and NBAC. A raster of harvest years: pixels with at least minFraction of their cells
## harvested that year. Anything else (NULL, a character vector of Landsat records): an empty list.
.harvestYears <- function(harvest, harvestField, rasterToMatch, earliestYear, latestYear, minFraction) {
if (inherits(harvest, "SpatVector")) {
if (!harvestField %in% names(harvest)) stop("the harvest polygons have no field \"", harvestField, "\"")
if (!terra::same.crs(harvest, rasterToMatch)) harvest <- terra::project(harvest, rasterToMatch)
harvest <- terra::crop(harvest, rasterToMatch)
yr <- suppressWarnings(as.integer(as.data.frame(harvest)[[harvestField]]))
yrs <- sort(unique(yr[!is.na(yr) & yr >= earliestYear & yr <= latestYear]))
return(stats::setNames(lapply(yrs, function(y)
which(!is.na(terra::values(terra::rasterize(harvest[which(yr == y), ], rasterToMatch, field = 1),
mat = FALSE)))), yrs))
}
if (inherits(harvest, "SpatRaster")) {
harvest <- terra::crop(harvest, terra::project(terra::ext(rasterToMatch), terra::crs(rasterToMatch),
terra::crs(harvest)), snap = "out")
v <- terra::values(harvest, mat = FALSE)
w <- which(!is.na(v) & v >= earliestYear & v <= latestYear)
return(.yearFractions(v[w], w, harvest, rasterToMatch, minFraction))
}
list()
}

## the records prepInputsDisturbanceYear() can use; "all" is every one
.disturbanceSourcesAll <- c("NFDB", "NBAC", "CanLaD", "NTEMS", "PreCanLaD")
.disturbanceSources <- function(sources) {
Expand All @@ -284,6 +386,13 @@ lastDisturbanceYear <- function(n, latestYear, byYear) {
unique(sources)
}

## The NFDB or NBAC records (a data.frame) to keep: from earliestYear, and prescribed burns only if asked.
.keepFires <- function(d, earliestYear, prescribed = FALSE) {
keep <- d$YEAR >= earliestYear
if (!isTRUE(prescribed) && "PRESCRIBED" %in% names(d)) keep <- keep & !.isPrescribed(d$PRESCRIBED)
keep
}

## NFDB and NBAC mark prescribed burns differently (NFDB "PB"/"Y"/"TRUE", NBAC "true"); empty means not prescribed
.isPrescribed <- function(x) {
x <- toupper(trimws(as.character(x)))
Expand Down
Loading
Loading