diff --git a/NEWS.md b/NEWS.md index f62d92b..cc36f51 100644 --- a/NEWS.md +++ b/NEWS.md @@ -10,6 +10,9 @@ - A ledger row with an interaction coefficient (`a:b`, e.g. `CMD:dom_agb_Pice_mar`, from a `fireSense_spreadFit` fitted with `fireSense_dataPrepFit`'s `spreadInteractions = "climate:fuel"`) predicts with it: `spreadProbOneELF()` needs the covariates `a` and `b` (and their ranges in `covMinMax_spread`), and `fireSenseUtils::spreadProbFromIntegerCovs()` forms their product after each is rescaled and centred with the row's `covCentre_spread` entry for it (0 where `youngAge` cleared the fuel), and multiplies it by the coefficient, as the fit does. A row without interactions predicts exactly as before. Needs fireSenseUtils >= 0.2.3.9177 (#242). +- A split fit with fuel in the linear range (every fit with `spreadClimateSplit` and fuel) predicted nothing: `spreadProbOneELF()` turned the logged fuel to linear with `covs[[cn]] <-`, which copies the table, so `fireSenseUtils::splitSpreadClimate()` then could not add `CMD_yr` and `CMD_dev` and the prediction stopped with "fitted coefficients CMD_yr, CMD_dev have no covariate". It now sets the fuel by reference. A test covers a `CMD_yr:fuel` interaction with an intercept, centres and `youngAge`. +* A ledger row fitted with the split climate covariate (`fireSense_dataPrepFit`'s `spreadClimateSplit`: parameters `_yr` and `_dev`) is predicted with the same two terms: `spreadProbOneELF()` makes them from the year's climate with `fireSenseUtils::splitSpreadClimate()`, the median being over the ELF's own burnable pixels (`elfPixels`: every row with one fitted ELF, the ELF's own pixels of `rasterToMatchLargeELF` with several, not the blend zone), and only its flammable pixels (`fireSenseUtils::climateSplitRefPixels()`, the choice the fit makes). `ELFblendWeights()` reads the cells' ELF labels with `fireSenseUtils::elfCellLabels()`. A row without split terms predicts as before. Needs fireSenseUtils with `splitSpreadClimate()` (Depends-on PredictiveEcology/fireSenseUtils); the `reqdPkgs` floor is set after that merges. + - With `paramSets`: the cache of a parameter set's surface no longer reads all the values of `flammableRTM` and `rasterToMatchLargeELF` every replicate (a new raster object or a change at 1000 sampled cells is a change) and returns the stored surface without copying it (a changed stored surface is recomputed). On a 20-million-cell raster a replicate that reuses a surface takes 0.35 s instead of 0.9 s, most of it SpaDES. `paramSets` stops if the ledger rows have the simulated ELF twice, or if a file of ledger rows has none for it. - New parameters `paramSets` (path to an `.rds` or `.csv` of spread parameter vectors for the simulated ELF; default `NA`, behaviour unchanged) and `repsPerSet`. The sets replace the simulated ELF's ledger rows (neighbour ELFs keep theirs); replicate r uses set `ceiling(r / repsPerSet)`, calls `set.seed(k)` with k its number within the set (common random numbers across sets), and the surface is recomputed only when the set changes. The link, lower asymptote, `gamma` and covariate centres come from the ledger row; a set lacking a coefficient of the row stops. The set index is output in `fireSense_SpreadParamSet`. New input `.ELFind`, as in `fireSense_dataPrepPredict`. diff --git a/fireSense_spreadPredict.R b/fireSense_spreadPredict.R index a1ba3ed..83d81dc 100644 --- a/fireSense_spreadPredict.R +++ b/fireSense_spreadPredict.R @@ -17,7 +17,7 @@ defineModule(sim, list( documentation = list("README.txt", "fireSense_spreadPredict.Rmd"), reqdPkgs = list("data.table", "magrittr", "Matrix", "methods", "terra", "SpaDES.core (>=3.0.4)", "stats", "ggplot2", "viridis", - "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9183)"), # 9183: spreadLinkInputs(activationIntercept =), spreadClimateTxt (fireSenseUtils#255); 9181: spreadLinkInputs(), powerLawPc50 (fireSenseUtils#250); 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape + "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9186)"), # 9186: splitSpreadClimate(), climateSplitRefPixels(), elfCellLabels() (fireSenseUtils#244); 9183: spreadLinkInputs(activationIntercept =), spreadClimateTxt (fireSenseUtils#255); 9181: spreadLinkInputs(), powerLawPc50 (fireSenseUtils#250); 9165: lowerAsymptote minimum (#230); 9162: smooth links, checkLinkParams() (#229); 9138: powerLawShape parameters = bindrows( defineParameter(name = "lowerSpreadProb", class = "numeric", default = fireSenseUtils::spreadProbFloor, desc = paste("Lower asymptote of the 2- and 3-parameter logistic. Default", @@ -256,7 +256,7 @@ spreadPredictRun <- function(sim) { if (NROW(sa) == 1L) { params1 <- paramSetForRep(sa$params[[1]], rep) lk1 <- ledgerLinkArgs(sa, 1L, floor = P(sim)$lowerSpreadProb) - pred <- do.call(spreadProbOneELF, c(list(covs, params = params1, covMinMax = ledgerCovMinMax(sa, 1L, sim$covMinMax_spread), + pred <- do.call(spreadProbOneELF, c(list(covs, params = params1, flammableRTM = sim$flammableRTM, covMinMax = ledgerCovMinMax(sa, 1L, sim$covMinMax_spread), yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, lowerSpreadProb = P(sim)$lowerSpreadProb, covCentre = ledgerCovCentre(sa, 1L), climateRef = ledgerClimateRef(sa, 1L), @@ -295,13 +295,19 @@ spreadPredictRun <- function(sim) { accPL <- matrix(0, NROW(covs), length(linkParNames), dimnames = list(NULL, linkParNames)) accX <- numeric(NROW(covs)) wsumPL <- numeric(NROW(covs)) ## weight of the ELFs with a linear-predictor link only + ## the ELF label of every cell (a whole-raster read): once, and only if a fit has split climate terms + isSplit <- vapply(seq_along(ids), function(i) + any(fireSenseUtils::isClimateSplitCol(fireSenseUtils::spreadSourceCols(names(paramSetForRep(sa$params[[i]], rep))))), + logical(1)) + elfLab <- if (any(isSplit)) fireSenseUtils::elfCellLabels(sim$rasterToMatchLargeELF[[1]]) for (i in seq_along(ids)) { these <- which(w[, i] > 0) if (!length(these)) next parsI <- paramSetForRep(sa$params[[i]], rep) p <- do.call(spreadProbOneELF, c(list(covs[these], params = parsI, covMinMax = sa$covMinMax_spread[[i]], - yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, + yr = time(sim), maxFireSpread = P(sim)$maxFireSpread, flammableRTM = sim$flammableRTM, lowerSpreadProb = P(sim)$lowerSpreadProb, + elfPixels = if (isSplit[i]) which(elfLab %in% ids[i]), covCentre = ledgerCovCentre(sa, i), climateRef = ledgerClimateRef(sa, i), powerLawPc50 = ledgerPowerLawPc50(sa, i)), lks[[i]])) rows <- these[match(p$pixelID, covs$pixelID[these])] @@ -465,9 +471,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { stop("fireSense_spreadPredict: sim$rasterToMatchLargeELF is not on the grid of sim$flammableRTM", call. = FALSE) r <- elfRas[[1]] - v <- terra::values(r, mat = FALSE) - lv <- terra::levels(r)[[1]] - lab <- if (is.data.frame(lv) && NCOL(lv) >= 2) as.character(lv[[2]][match(v, lv[[1]])]) else as.character(v) + lab <- fireSenseUtils::elfCellLabels(r) w <- vapply(ids, function(id) { core <- r; terra::values(core) <- ifelse(lab %in% id, 1, NA) if (all(is.na(terra::values(core, mat = FALSE)))) return(numeric(length(pixelID))) @@ -489,6 +493,10 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' @param params one-row `data.frame`: the ELF's parameter set for this replicate (`paramSetForRep()`). #' @param covMinMax the ELF's `covMinMax_spread` (`ledgerCovMinMax()`): the ranges the fit rescaled its #' covariates with. Every fitted covariate must be a column of it, or it is left unscaled. +#' @param elfPixels integer; the `pixelID`s of the ELF's own burnable pixels, the pixels the year's median of a split +#' climate covariate (`_yr`, `_dev`; `fireSenseUtils::splitSpreadClimate()`) is taken over, as in the fit. +#' `NULL` (one fitted ELF) is every row of `covs` that is flammable. Not used by a fit without split terms. +#' @param flammableRTM `sim$flammableRTM`; with `elfPixels` it limits the median to the ELF's flammable pixels (`fireSenseUtils::climateSplitRefPixels()`, the fit's choice). #' @param yr,maxFireSpread,lowerSpreadProb as for `fireSenseUtils::spreadProbFromIntegerCovs()` and #' `fireSenseUtils::logisticAll()`. #' @param covCentre the ELF's `covCentre_spread` (`ledgerCovCentre()`): the covariate means the fit subtracted @@ -525,7 +533,7 @@ ELFblendWeights <- function(elfRas, template, pixelID, ids, width) { #' also `linearPredictor`, the `x` that `spreadProb` is the link of (the fuels' only with climate in the ceiling), and #' the attribute `linkPars`, the link's parameters (`fireSenseUtils::linearLinkPars()`): a vector, or with climate in #' the ceiling a matrix with one row per pixel. -spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, +spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSpreadProb, elfPixels = NULL, flammableRTM = NULL, covCentre = NULL, climateRef = NULL, powerLawPc50 = NULL, powerLawGamma = NULL, powerLawShape = fireSenseUtils::spreadPowerLawShape, link = if (!is.null(powerLawGamma)) "powerLaw", @@ -561,7 +569,7 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp fuelCols <- character() for (cn in intersect(names(covMinMax), names(covs))) { if (fireSenseUtils::isLinearFuelRange(covMinMax[[cn]])) { - covs[[cn]] <- fireSenseUtils::fuelLogToLinear(covs[[cn]]) + data.table::set(covs, NULL, cn, fireSenseUtils::fuelLogToLinear(covs[[cn]])) # by reference: `[[<-` copies, and splitSpreadClimate() below then cannot add columns fuelCols <- c(fuelCols, cn) } } @@ -573,6 +581,14 @@ spreadProbOneELF <- function(covs, params, covMinMax, yr, maxFireSpread, lowerSp fitted <- setdiff(names(params), c(unlist(fireSenseUtils::logisticParamNames), fireSenseUtils::spreadInterceptTxt)) ## an interaction (`CMD:fuel`) is made from its two covariates by spreadProbFromIntegerCovs(), as in the fit needed <- fireSenseUtils::spreadSourceCols(fitted) + ## a fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as `_yr` and `_dev` (also in an + ## interaction, `CMD_yr:fuel`): the year's median of the variable over this ELF's burnable pixels, and the departure + ## from it, made as the fit made them + splitVars <- unique(fireSenseUtils::climateSplitBase(needed[fireSenseUtils::isClimateSplitCol(needed)])) + if (length(splitVars) && all(splitVars %in% names(covs))) { + ref <- covs[covs$pixelID %in% fireSenseUtils::climateSplitRefPixels(covs$pixelID, flammableRTM, elfPixels), splitVars, with = FALSE] + fireSenseUtils::splitSpreadClimate(covs, splitVars, ref) + } noCov <- setdiff(needed, names(covs)) if (length(noCov)) { stop( diff --git a/tests/testthat/test-climateSplit.R b/tests/testthat/test-climateSplit.R new file mode 100644 index 0000000..53d35e9 --- /dev/null +++ b/tests/testthat/test-climateSplit.R @@ -0,0 +1,134 @@ +## A fit made with fireSense_dataPrepFit's spreadClimateSplit has the climate as two terms, `MDC_yr` (the year's +## median over the ELF's burnable pixels) and `MDC_dev` (MDC minus it). Prediction builds them from the year's +## climate with fireSenseUtils::splitSpreadClimate(), as the fit did, over the ELF's own pixels. +## +## Rescaling: MDC_yr with c(0, 200), MDC_dev with c(-100, 100) (fireSenseUtils::climateSplitRanges()). + +splitParams <- function(yr = 1.5, dev = 0.8, fuel = 1, name = "fuelA") { + d <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = yr, MDC_dev = dev, x = fuel) + names(d)[6] <- name + d +} +cmmSplit <- function(fuel = "fuelA") { + d <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), f = c(0, 8)) + data.table::setnames(d, "f", fuel) + d +} + +test_that("a split fit predicts from the year's median over the burnable pixels and each pixel's departure from it", { + covs <- toyCovariates() + ins <- toyInputs(covs = covs, params = splitParams(), formula = "~ MDC_yr + MDC_dev + fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + v <- predVals(toyRun(ins)) + o <- order(covs$pixelID) + mdc <- covs$MDC[o]; fuel <- covs$fuelA[o] + med <- stats::median(covs$MDC) # 100: over the 7 burnable pixels of the covariate table + x <- 1.5 * (med / 200) + 0.8 * ((mdc - med + 100) / 200) + 1 * (fuel / 8) + expect_equal(v[cells <- c(1, 2, 3, 4, 6, 7, 8)], handLogistic3(x), tolerance = 1e-7) +}) + +test_that("a non-flammable row in the covariate table is left out of the median, as the fit's burnable pixels are", { + covs <- toyCovariates() + extra <- data.table::data.table(pixelID = 5L, MDC = 5000, youngAge = 0, fuelA = 0) # cell 5 of the toy flammableRTM is 0 + withExtra <- data.table::rbindlist(list(covs, extra)) + run <- function(cv) { + ins <- toyInputs(covs = cv, params = splitParams(), formula = "~ MDC_yr + MDC_dev + fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + predVals(toyRun(ins)) + } + a <- run(covs); b <- run(withExtra) + cellsB <- c(1, 2, 3, 4, 6, 7, 8) + expect_equal(b[cellsB], a[cellsB], tolerance = 1e-12) # median 100 with and without the extra row +}) + +test_that("the between term is the same for every pixel: only the within term moves with the pixel", { + covs <- toyCovariates() + both <- function(yr, dev) { + ins <- toyInputs(covs = data.table::copy(covs), params = splitParams(yr, dev, fuel = 0), formula = "~ MDC_yr + MDC_dev + fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + predVals(toyRun(ins)) + } + yrOnly <- both(1.5, 0) + expect_equal(yrOnly[c(1, 2, 3, 4, 6, 7, 8)], rep(handLogistic3(1.5 * 0.5), 7), tolerance = 1e-7) # median 100 / 200 everywhere + devOnly <- both(0, 0.8) + expect_gt(length(unique(round(devOnly[c(1, 2, 3, 4, 6, 7, 8)], 8))), 1L) +}) + +test_that("with several ELFs each takes the median over its own pixels", { + ins <- multiInputs() + covs <- data.table::data.table(pixelID = 1:10, MDC = c(10, 20, 30, 40, 50, 100, 110, 120, 130, 140), fuelA = 2, fuelB = 3) + ins$fireSense_SpreadCovariates <- covs + d <- function(fuel) { x <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, f = 1) + names(x)[6] <- fuel; x } + ins$studyAreaWithSpreadParams$params <- list(d("fuelA"), d("fuelB")) + ins$studyAreaWithSpreadParams$covMinMax_spread <- list(cmmSplit("fuelA"), cmmSplit("fuelB")) + ins$fireSense_spreadFormula <- "~ MDC_yr + MDC_dev + fuelA - 1" + v <- predVals(toyRun(ins, params = list(ELFblendWidth = 20000))) + ## pixel 1 is only A's (25 km from B): A's median of pixels 1:5 is 30 + xA <- 1.5 * (30 / 200) + 0.8 * ((10 - 30 + 100) / 200) + 1 * (2 / 8) + expect_equal(v[1], handLogistic3(xA), tolerance = 1e-7) + ## pixel 10 is only B's: B's median of pixels 6:10 is 120 + xB <- 1.5 * (120 / 200) + 0.8 * ((140 - 120 + 100) / 200) + 1 * (3 / 8) + expect_equal(v[10], handLogistic3(xB, upper = 0.25), tolerance = 1e-7) +}) + +test_that("a fit without split terms predicts as before: no median is taken", { + expect_identical(predVals(toyRun()), predVals(toyRun(toyInputs()))) + expect_false(any(fireSenseUtils::isClimateSplitCol(names(toyParams())))) +}) + +test_that("a split fit with climate in the ceiling moves pc with both terms, and x holds the fuels only", { + covs <- toyCovariates() + p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, + youngAge = -0.5, fuelA = 1) + ins <- toyInputs(covs = covs, params = p, formula = "~ MDC_yr + MDC_dev + youngAge + fuelA - 1") + ins$covMinMax_spread <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), youngAge = c(0, 1), fuelA = c(0, 8)) + ins$studyAreaWithSpreadParams[[linkColPL]] <- "powerLaw" + ins$studyAreaWithSpreadParams[[gammaColPL]] <- 1.9 + ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitClimateRefTxt]] <- list(list(MDC_yr = 0.4, MDC_dev = 0.5)) + ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitPowerLawPc50Txt]] <- 0.3 + sim <- toyRun(ins) + o <- order(covs$pixelID) + med <- stats::median(covs$MDC) + shift <- 1.5 * (med / 200 - 0.4) + 0.8 * ((covs$MDC[o] - med + 100) / 200 - 0.5) + x <- -0.5 * covs$youngAge[o] + covs$fuelA[o] / 8 + pc <- pmax(0.3 - (0.3 - 0.25) * exp(-shift), 0.13) + expect_equal(predVals(sim)[cellsPL], pmax(pc - (pc - 0.13) * exp(-sign(x) * abs(x / 1.9)), 0), tolerance = 1e-9) + expect_equal(terra::values(sim$fireSense_SpreadLinear, mat = FALSE)[cellsPL], x, tolerance = 1e-9) +}) + +test_that("an interaction of a split term is made from the split term, so the fit's interaction names work", { + covs <- toyCovariates() + p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, MDC_yr = 1.5, MDC_dev = 0.8, + fuelA = 1, `MDC_yr:fuelA` = -2, check.names = FALSE) + ins <- toyInputs(covs = covs, params = p, formula = "~ MDC_yr + MDC_dev + fuelA + MDC_yr:fuelA - 1") + ins$covMinMax_spread <- cmmSplit() + o <- order(covs$pixelID) + med <- stats::median(covs$MDC) + yr <- med / 200; dev <- (covs$MDC[o] - med + 100) / 200; fuel <- covs$fuelA[o] / 8 + x <- 1.5 * yr + 0.8 * dev + fuel - 2 * yr * fuel + expect_equal(predVals(toyRun(ins))[cellsPL], handLogistic3(x), tolerance = 1e-7) +}) + +test_that("a fit with an intercept, centres and a _yr:fuel interaction predicts the product of the centred terms, 0 where youngAge cleared the fuel, and no _dev interaction", { + covs <- toyCovariates() + p <- data.frame(maxAsymptote = 0.25, hillSlope1 = 2, inflectionPoint1 = 1, icpt = 0.4, MDC_yr = 1.5, MDC_dev = 0.8, + youngAge = -0.5, fuelA = 1, `MDC_yr:fuelA` = -2, check.names = FALSE) + names(p)[4] <- fireSenseUtils::spreadInterceptTxt + ## fuel arrives logged, with the fit's linear range (only then is it cleared where youngAge is 1) + biomass <- c(0, 0, 4000, 0, 8000, 8000, 2000) + data.table::set(covs, j = "fuelA", value = fireSenseUtils::logMinB(biomass)) + ins <- toyInputs(covs = covs, params = p, formula = "~ 1 + MDC_yr + MDC_dev + youngAge + fuelA + MDC_yr:fuelA") + ins$covMinMax_spread <- data.table::data.table(MDC_yr = c(0, 200), MDC_dev = c(-100, 100), youngAge = c(0, 1), + fuelA = fireSenseUtils::fuelLinearRange) + centre <- list(MDC_yr = 0.4, MDC_dev = 0.5, youngAge = 0.2, fuelA = 0.3) + ins$studyAreaWithSpreadParams[[fireSenseUtils::spreadFitCovCentreTxt]] <- list(centre) + o <- order(covs$pixelID) + med <- stats::median(covs$MDC) + yr <- med / 200 - 0.4; dev <- (covs$MDC[o] - med + 100) / 200 - 0.5 + ya <- covs$youngAge[o]; fuel <- biomass[o] / fireSenseUtils::fuelLinearRange[2] + fuelC <- ifelse(ya > 0, 0, fuel) - 0.3 # fuel is cleared where youngAge is non-zero, then centred + inter <- ifelse(ya > 0, 0, yr * fuelC) # the interaction is 0 there, and is not centred again + x <- 0.4 + 1.5 * yr + 0.8 * dev - 0.5 * (ya - 0.2) + 1 * fuelC - 2 * inter + expect_equal(predVals(toyRun(ins))[cellsPL], handLogistic3(x), tolerance = 1e-7) +})