From 8f5726af2a5b1100660468a094ca83530612745d Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 2 Dec 2026 12:26:20 -0700 Subject: [PATCH] prepInputsDisturbanceYear(): regional settings (polygonsBefore, prescribed, harvest, unknownYear, withType) From Julie Turner's test of the LandR#301 rule in the southern interior BC mountains, where NFDB-NBAC agreement adds back mostly unburned forest and 1950-1971 NFDB outlines without Pre-CanLaD are mostly older forest. Each defaults to the current rule. Her BC rule: sources = "all", polygonAgreement = FALSE, polygonsBefore = 1950, prescribed = TRUE, harvest = BC cutblocks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXfVqAugcusGHygZGJ3 --- DESCRIPTION | 2 +- NEWS.md | 9 ++ R/disturbanceYear.R | 157 ++++++++++++++++++++++---- man/prepInputsDisturbanceYear.Rd | 58 ++++++++-- tests/testthat/test-disturbanceYear.R | 83 ++++++++++++++ 5 files changed, 277 insertions(+), 32 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 6e29fbf..5a3af1e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -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")), diff --git a/NEWS.md b/NEWS.md index b644110..e5d2f49 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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()`, diff --git a/R/disturbanceYear.R b/R/disturbanceYear.R index 2150689..1c86ba3 100644 --- a/R/disturbanceYear.R +++ b/R/disturbanceYear.R @@ -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. @@ -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 @@ -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))) @@ -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) @@ -139,18 +181,37 @@ 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`, @@ -158,19 +219,25 @@ prepInputsDisturbanceYear <- function( #' 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 } @@ -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)) @@ -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) @@ -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]]) } } } @@ -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 @@ -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) { @@ -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))) diff --git a/man/prepInputsDisturbanceYear.Rd b/man/prepInputsDisturbanceYear.Rd index 8854396..87e14ac 100644 --- a/man/prepInputsDisturbanceYear.Rd +++ b/man/prepInputsDisturbanceYear.Rd @@ -30,7 +30,13 @@ prepInputsDisturbanceYear( harvest = sub("\\\\.tif$", "", .input("ntems_harvest", "target_file"))), polygonAgreement = TRUE, minFraction = 0.5, - byYear = FALSE + byYear = FALSE, + polygonsBefore = agreeFrom, + prescribed = FALSE, + harvest = NULL, + harvestField = "HARVEST_YEAR", + unknownYear = 1955L, + withType = FALSE ) disturbancesByYear( @@ -47,7 +53,10 @@ disturbancesByYear( polygonAgreement = TRUE, canladStart = 1985L, agreeFrom = 1972L, - earliestYear = 1950L + earliestYear = 1950L, + harvest = list(), + polygonsBefore = agreeFrom, + withType = FALSE ) lastDisturbanceYear(n, latestYear, byYear) @@ -97,14 +106,33 @@ with \code{sources = c("NFDB", "NBAC", "CanLaD")} gives the rule of LandR 1.2.0. \item{byYear}{for \code{lastDisturbanceYear()}: a list named by year of pixels.} +\item{polygonsBefore}{before this year an NFDB polygon counts even where Pre-CanLaD sees no disturbance. +\code{1950} (or \code{earliestYear}) counts Pre-CanLaD alone from 1950.} + +\item{prescribed}{keep prescribed burns in NFDB and NBAC (\code{FALSE}: drop them).} + +\item{harvest}{where harvest comes from: \code{NULL} (all of \code{"CanLaD"}, \code{"NTEMS"} and \code{"PreCanLaD"} that are in +\code{sources}), any of those three (\code{character(0)} for none), or a layer of harvest years that replaces them: +polygons (\code{SpatVector} or \code{sf}, e.g. BC's consolidated cutblocks) with the year in \code{harvestField}, or a +\code{SpatRaster} of harvest years.} + +\item{harvestField}{the year field of \code{harvest} polygons.} + +\item{unknownYear}{the year given to Pre-CanLaD disturbances of unknown year (999); its readme says 1955.} + +\item{withType}{\code{TRUE} also returns the type of the last disturbance: a second layer, \code{type}, 1 fire and 2 +harvest (fire when both happened in that year).} + \item{nfdb, nbac, canladFire, canladHarvest, ntemsFire, ntemsHarvest, preCanladFire, preCanladHarvest}{see the -description of \code{disturbancesByYear()}.} +description of \code{disturbancesByYear()}. \code{harvest} (here) is a list named by year of pixels from a harvest +layer, which count as they are. With \code{withType = TRUE} the result has an attribute \code{type}, a list of two +such lists, \code{fire} and \code{harvest}.} \item{n}{number of pixels.} } \value{ A \code{SpatRaster} on \code{rasterToMatch} of the year of each pixel's last stand-replacing disturbance at -or before \code{latestYear}, \code{NA} where there was none. With \code{byYear = TRUE}, a list named by year of the +or before \code{latestYear}, \code{NA} where there was none; with \code{withType = TRUE}, two layers, \code{year} and \code{type}. With \code{byYear = TRUE}, a list named by year of the disturbed pixels (cell numbers of \code{rasterToMatch}), as \code{\link[=disturbancesByYear]{disturbancesByYear()}} gives. } \description{ @@ -135,15 +163,31 @@ v2), the same way: at least \code{minFraction} of the pixel's cells are fire (\c 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; -\item before \code{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. +\item before \code{polygonsBefore} (default \code{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 \code{polygonsBefore = 1950}; polygons before it still count. } Without \code{"PreCanLaD"}, the polygons decide before \code{canladStart}: before \code{agreeFrom} (1972) an NFDB polygon, then NFDB and NBAC polygons of the same year (or the one polygon source given). Without \code{"CanLaD"} and \code{"NTEMS"}, the polygons decide from \code{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 \code{prescribed = TRUE}. Kept, they count where the +rule counts any polygon: from \code{canladStart} only where a Landsat record sees the fire (or, with +\code{polygonAgreement}, where both polygon sets map it). + +Harvest comes from the Landsat records in \code{harvest} (default all of CanLaD, NTEMS and Pre-CanLaD that are +in \code{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 \verb{sources = "all", polygonAgreement = FALSE, polygonsBefore = 1950, prescribed = TRUE}, with BC cutblocks as \code{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 \code{rasterToMatch}; \code{minFraction} then +has no effect for the 30 m records. } \section{Functions}{ \itemize{ diff --git a/tests/testthat/test-disturbanceYear.R b/tests/testthat/test-disturbanceYear.R index 5988f85..2338665 100644 --- a/tests/testthat/test-disturbanceYear.R +++ b/tests/testthat/test-disturbanceYear.R @@ -163,3 +163,86 @@ test_that("from 1985, NFDB and NBAC agreeing count where no Landsat record saw a test_that("prescribed burns are recognised in NFDB and NBAC spellings", { expect_identical(.isPrescribed(c("yes", "true", NA, "", "no")), c(TRUE, TRUE, FALSE, FALSE, FALSE)) }) + +## Regional settings (Turner 2026, southern interior BC): polygonsBefore, prescribed, harvest, unknownYear, withType + +test_that("polygonsBefore: before it an NFDB polygon counts without Pre-CanLaD; from it Pre-CanLaD alone", { + args <- list(latestYear = 2020L, earliestYear = 1940L, nfdb = list(`1945` = 3L, `1960` = 1L), + preCanladFire = list(`1965` = 2L)) + y <- lastDisturbanceYear(3, 2020L, do.call(disturbancesByYear, args)) + expect_identical(y, c(1960L, 1965L, 1945L)) # default 1972: NFDB counts before 1972 + y <- lastDisturbanceYear(3, 2020L, do.call(disturbancesByYear, c(args, polygonsBefore = 1950L))) + expect_identical(y, c(NA, 1965L, 1945L)) # 1960 NFDB alone no longer counts; 1945 does + expect_identical(do.call(disturbancesByYear, c(args, polygonsBefore = 1972L)), do.call(disturbancesByYear, args)) +}) + +test_that("prescribed burns are dropped unless prescribed = TRUE", { + d <- data.frame(YEAR = c(1940, 1990, 1990), PRESCRIBED = c(NA, "PB", "")) + expect_identical(.keepFires(d, 1950), c(FALSE, FALSE, TRUE)) + expect_identical(.keepFires(d, 1950, prescribed = TRUE), c(FALSE, TRUE, TRUE)) + expect_identical(.keepFires(d[, "YEAR", drop = FALSE], 1950), c(FALSE, TRUE, TRUE)) +}) + +## the CanLaD fixture of "counts a pixel when enough of its CanLaD cells are disturbed": pixel 1 50% fire in +## 1990, pixel 2 25% fire, pixel 4 all harvest in 1995 +canladFixture <- function(td) { + rtm <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 480, ymin = 0, ymax = 480, crs = "EPSG:3978", vals = 1) + fine <- terra::rast(terra::ext(rtm), resolution = 30, crs = terra::crs(rtm)) + v <- matrix(0L, 16, 16); v[1:8, 1:4] <- 1L; v[1:8, 9:10] <- 1L + for (y in 1985:1996) { + vy <- if (y == 1990L) v else matrix(0L, 16, 16) + if (y == 1995L) vy[9:16, 9:16] <- 2L + terra::writeRaster(terra::rast(fine, vals = as.vector(t(vy))), file.path(td, sprintf("canlad_%d.tif", y))) + } + list(rtm = rtm, fine = fine, + run = function(...) prepInputsDisturbanceYear(rtm, latestYear = 1995L, destinationPath = td, nfdbURL = NULL, + nbacURL = NULL, canladURL = NULL, canladFile = "canlad_%d.tif", + sources = "CanLaD", ...)) +} +vals <- function(r) as.integer(terra::values(r, mat = FALSE)) + +test_that("harvest picks the Landsat harvest records, or a harvest layer replaces them", { + fx <- canladFixture(withr::local_tempdir()) + expect_identical(vals(fx$run()), c(1990L, NA, NA, 1995L)) + expect_identical(vals(fx$run(harvest = "CanLaD")), c(1990L, NA, NA, 1995L)) + expect_identical(vals(fx$run(harvest = character(0))), c(1990L, NA, NA, NA)) + expect_error(fx$run(harvest = "cutblocks"), "harvest must be") + ## cutblock polygons: one over pixel 3 (bottom left) cut in 1993, one over pixel 1 cut in 1980 (before its fire), + ## one cut after latestYear + cb <- terra::vect(c("POLYGON ((0 0, 240 0, 240 240, 0 240, 0 0))", "POLYGON ((0 240, 240 240, 240 480, 0 480, 0 240))", + "POLYGON ((240 240, 480 240, 480 480, 240 480, 240 240))"), crs = "EPSG:3978") + cb$HARVEST_YEAR <- c(1993L, 1980L, 2010L) + expect_identical(vals(fx$run(harvest = cb)), c(1990L, NA, 1993L, NA)) + names(cb)[1] <- "YR" + expect_identical(vals(fx$run(harvest = cb, harvestField = "YR")), c(1990L, NA, 1993L, NA)) + expect_error(fx$run(harvest = cb), "no field") + ## a raster of harvest years at 30 m: all of pixel 2 cut in 1992, a quarter of pixel 3 in 1994 + hy <- matrix(NA_integer_, 16, 16); hy[1:8, 9:16] <- 1992L; hy[9:16, 1:2] <- 1994L + expect_identical(vals(fx$run(harvest = terra::rast(fx$fine, vals = as.vector(t(hy))))), c(1990L, 1992L, NA, NA)) +}) + +test_that("withType adds the type of the last disturbance: 1 fire, 2 harvest", { + fx <- canladFixture(withr::local_tempdir()) + r <- fx$run(withType = TRUE) + expect_identical(names(r), c("year", "type")) + expect_identical(vals(r$year), c(1990L, NA, NA, 1995L)) + expect_identical(vals(r$type), c(1L, NA, NA, 2L)) + expect_identical(vals(fx$run()), vals(r$year)) + ## fire wins when a pixel was burned and cut in its last year; an earlier harvest does not set the type + byYr <- disturbancesByYear(2020L, canladFire = list(`2000` = 1:2), canladHarvest = list(`2000` = 2L, `1990` = 1L), + sources = "CanLaD", withType = TRUE) + expect_identical(attr(byYr, "type"), list(fire = list(`2000` = 1:2), harvest = list(`1990` = 1L, `2000` = 2L))) + expect_null(attr(disturbancesByYear(2020L, canladFire = list(`2000` = 1:2), sources = "CanLaD"), "type")) +}) + +test_that("unknownYear sets the year of Pre-CanLaD's unknown-year (999) disturbances", { + td <- withr::local_tempdir() + rtm <- terra::rast(nrows = 1, ncols = 1, xmin = 0, xmax = 240, ymin = 0, ymax = 240, crs = "EPSG:3978", vals = 1) + fine <- terra::rast(terra::ext(rtm), resolution = 30, crs = terra::crs(rtm)) + terra::writeRaster(terra::rast(fine, vals = 999L), file.path(td, "pre_year.tif")) + terra::writeRaster(terra::rast(fine, vals = 2L), file.path(td, "pre_type.tif")) + run <- function(...) vals(prepInputsDisturbanceYear(rtm, latestYear = 2000L, destinationPath = td, sources = "PreCanLaD", + preCanladURL = NULL, preCanladFiles = c(year = "pre_year.tif", type = "pre_type.tif"), ...)) + expect_identical(run(), 1955L) + expect_identical(run(unknownYear = 1962L), 1962L) +})