diff --git a/NEWS.md b/NEWS.md index f2be75a..3a38e3c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fireSimulator_validation (development version) +* New residual climate signal: does what the simulation gets wrong (log(simulated / observed) of annual area burned, mean and median fire size, per ELF and scored year) still trend with the year's climate? `residualClimateTables()` regresses each residual on the within-ELF z-score of every annual climate covariate the hindcast has (CMD, CMDsm, CMDsp, cumMDC, Tmaxsm, PPTsm; `readHindcastCovariates()`) and on the ELF's own spread-fit climate variable, with the slope after the own variable in the model, and pools the slopes over ELFs (median and a random-effects summary). A year with no observed fire has no area or size residual (the offset area residual, `minHa` added to both, keeps it). `spreadClimateSD()` gives the year-to-year SD of the fitted spread climate term (coefficient x scaled covariate) next to `yearSpreadSD`; it is NA without spread coefficients, so other simulators are scored too. `runWave1()` returns `residualClimate`; the module writes `residualClimate_years.csv`, `residualClimate_slopes.csv`, `residualClimate_pooled.csv` and `residualClimate_spreadSD.csv` to `outputPath`. `readLedgerRow()` also returns the kept sets' coefficients (`params`) and `covMinMax`; the ELF inputs gain `covariates`. Needs fireSenseUtils >= 0.2.3.9196. + * In-sample hindcasts (they spread the observed escapes from their real starts and years, `FS_HC_IGNITIONS=observedEscapes`): S7 is no longer scored, because its whole-ELF AUC (about 0.9) only shows that the fires start where the observed ones did. New tests S8 and S9 score what a fire does once it has escaped (`R/escapeTests.R`). S8, size given escape: for each seeded observed escape, the median over runs of the final size of the fire that grew from it against the fire's observed size; per ELF the Spearman correlation `rho` (single-run range), the median `log2ratio` of simulated over observed size and `nFires`. S9, shape given escape: for each seeded fire with N observed cells, the circle around its start that holds 2N burnable core cells; the AUC of the share of runs that burned each cell for the cells the fire burned against the others (`aucOf()`), reported as the median over fires with a single-run range, beside a distance-only baseline `aucDist` (each cell of the circle scored by its closeness to the start) and the headline `aucDiff` (model AUC minus baseline AUC), `shareInside` (the share of the fire's cells inside the circle, since cells outside are not counted) and `nFires`. Both are pooled over ELFs with `bootstrapPooled()` and are rows of `wave1_results.csv` (tests `S8`, `S9`); the page has a "Given an escape" table, shown only when there are such rows. A run is in-sample when every run of every year with a fire started the same fires from the same cells (`hindcastInSample()`, read from `fireSense_burnSummary.csv`: the hindcast files record no setting, only the folder name does); `readFireSenseHindcast()` has a new argument `inSample` (default `NA`: detect) and puts `inSample` and `location$seeded` in the ELF input. A fire is tied to its observed escape by its start cell (`igLoc` of `fireSense_burnSummary.csv`, in the order of `hindcast_sizes.csv`), and the start to the observed polygon that holds it. S8 and S9 are not scored for normal runs: their fires do not start where the observed ones did. * Fix: the per-ELF `auc` rows of S7 were NA whenever one scored year had no observed burn (that year's AUC is undefined, and the ELF's median was taken over it). The ELF row is now the median over the years with an AUC, as the pooled row already was. diff --git a/R/climateResponse.R b/R/climateResponse.R index 8af49b2..80f691b 100644 --- a/R/climateResponse.R +++ b/R/climateResponse.R @@ -11,13 +11,33 @@ climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- na ## the scored years and the covariate standardised over them (`list(years, z)`), or NULL when the ELF has no usable covariate climateInputs <- function(elf) { years <- scoredYears(elf) - cv <- covariateOf(elf, years) - if (is.null(elf$covariate) || anyNA(cv) || length(years) < 3 || stats::sd(cv) == 0) return(NULL) - list(years = years, z = (cv - mean(cv)) / stats::sd(cv)) + z <- zScore(covariateOf(elf, years)) + if (is.null(elf$covariate) || anyNA(z)) return(NULL) + list(years = years, z = z) +} + +## `v` standardised over its years (mean 0, SD 1); all NA with a missing value, fewer than 3 years or a constant +zScore <- function(v) if (anyNA(v) || length(v) < 3 || stats::sd(v) == 0) rep(NA_real_, length(v)) else (v - mean(v)) / stats::sd(v) + +## log(sim / obs) with an offset added to both (0: none); NA where it is not finite (a quantity of 0 without offset) +logRatio <- function(sim, obs, offset = 0) { r <- log((sim + offset) / (obs + offset)); r[!is.finite(r)] <- NA_real_; r } + +## the median over runs of the area of each of `years` (0 for a year without runs) +medianAreaBy <- function(elf, years) vapply(years, function(y) { a <- elf$simYears$area50[elf$simYears$year == y]; if (length(a)) stats::median(a) else 0 }, 0) + +## the slope of `y` on `z` (and its standard error and the n of years), with `z2` also in the model when given; NA with fewer than `minN` finite years or a constant covariate +olsSlope <- function(y, z, z2 = NULL, minN = 8L) { + d <- data.frame(y = y, z = z); if (!is.null(z2)) d$z2 <- z2 + d <- d[stats::complete.cases(d) & is.finite(d$y), , drop = FALSE] + out <- c(slope = NA_real_, se = NA_real_, n = nrow(d)) + if (nrow(d) < minN || any(vapply(d[-1], stats::sd, 0) == 0)) return(out) + f <- stats::coef(suppressWarnings(summary(stats::lm(if (is.null(z2)) y ~ z else y ~ z + z2, d)))) # a perfect fit (toy data) warns about its SE + if ("z" %in% rownames(f)) out[c("slope", "se")] <- f["z", 1:2] + out } ## the slope of `y` (a log value; years with a non-finite value are left out) on `z`: NA with fewer than 3 years -logSlope <- function(y, z) { k <- is.finite(y); if (sum(k) < 3) NA_real_ else unname(stats::coef(stats::lm(y[k] ~ z[k]))[2]) } +logSlope <- function(y, z) unname(olsSlope(y, z, minN = 3L)[["slope"]]) ## The scored years of an ELF split by its own climate, from [climateInputs()]: `z` (covariate standardised over the scored years), `dry` (z at or above its 90% quantile: the driest 10%), `wet` (z at or below its median: the wetter half). ## NULL as climateInputs(). The one place the dry and wet years are chosen (the ELF's own climate and threshold). @@ -184,11 +204,10 @@ climatePooledYears <- function(elfs, nBoot = 999, seed = 1) { yrs <- do.call(rbind, lapply(elfs, function(e) { g <- climateYears(e) if (is.null(g)) return(NULL) - sim <- vapply(g$years, function(y) { a <- e$simYears$area50[e$simYears$year == y]; if (length(a)) stats::median(a) else 0 }, 0) - data.frame(ELF = e$elf, year = g$years, sim = sim, obs = obsBy(e, "area50", g$years), dry = g$dry, wet = g$wet) + data.frame(ELF = e$elf, year = g$years, sim = medianAreaBy(e, g$years), obs = obsBy(e, "area50", g$years), dry = g$dry, wet = g$wet) })) if (is.null(yrs)) return(NULL) - stat <- function(d) c(ratio = if (sum(d$obs) > 0) sum(d$sim) / sum(d$obs) else NA_real_, medianRatio = exp(stats::median(log((d$sim + 1) / (d$obs + 1))))) + stat <- function(d) c(ratio = if (sum(d$obs) > 0) sum(d$sim) / sum(d$obs) else NA_real_, medianRatio = exp(stats::median(logRatio(d$sim, d$obs, 1)))) do.call(rbind, lapply(names(climateGroups), function(m) { d <- yrs[yrs[[climateGroups[[m]]]], ] if (!nrow(d)) return(NULL) diff --git a/R/readFireSenseHindcast.R b/R/readFireSenseHindcast.R index c2b73f1..68d5be3 100644 --- a/R/readFireSenseHindcast.R +++ b/R/readFireSenseHindcast.R @@ -255,16 +255,26 @@ readHindcastCovariate <- function(hindcastDir, elf, core, variable = "CMD") { data.frame(year = as.integer(sub(".*_(\\d{4})$", "\\1", names(r))), value = v) } -#' The ledger row of an ELF: what the gates need +#' ELF medians of every annual climate covariate the fit can use +#' +#' [readHindcastCovariate()] for each variable of `fireSenseUtils::climateCovRanges` the hindcast has the file of; a variable without one is left out. +#' @param hindcastDir,elf,core As [readHindcastCovariate()]. @param variables Climate variables. +#' @return Named list of `data.frame(year, value)`. +readHindcastCovariates <- function(hindcastDir, elf, core, variables = names(fireSenseUtils::climateCovRanges)) + Filter(Negate(is.null), stats::setNames(lapply(variables, function(v) tryCatch(readHindcastCovariate(hindcastDir, elf, core, v), error = function(e) NULL)), variables)) + +#' The ledger row of an ELF: what the gates and the residual climate signal need #' #' @param ledgerFile A spread-fit ledger `.rds` (`fireSenseParams_*.rds`; the caller downloads it). @param elf ELF (`polygonID`). -#' @return List: `objective` (`objFunVal` of the kept sets), `pc` (`maxAsymptote` of each kept set) and `p50` -#' (`NULL` when the ledger has no power-law columns). +#' @return List: `objective` (`objFunVal` of the kept sets), `pc` (`maxAsymptote` of each kept set), `p50` +#' (`NULL` when the ledger has no power-law columns), `params` (the kept sets' coefficients, one row per set) and `covMinMax` +#' (`covMinMax_spread`, the ranges the covariates were scaled with; `NULL` when the ledger has none). readLedgerRow <- function(ledgerFile, elf) { sp <- readRDS(ledgerFile); i <- which(sp$polygonID == elf)[1] p <- sp$params[[i]] list(objective = as.numeric(unlist(sp$objFunVal[[i]])), pc = as.numeric(p[["maxAsymptote"]]), - p50 = if ("powerLawPc50_spread" %in% names(sp)) sp$powerLawPc50_spread[[i]] else NULL) + p50 = if ("powerLawPc50_spread" %in% names(sp)) sp$powerLawPc50_spread[[i]] else NULL, + params = as.data.frame(p), covMinMax = if ("covMinMax_spread" %in% names(sp)) as.data.frame(sp$covMinMax_spread[[i]])) } #' Burnable area and burn rate of an ELF @@ -306,10 +316,12 @@ readFireSenseHindcast <- function(elf, hindcastDir, ledgerFile = NULL, nfdbPath, starts <- readHindcastStarts(hindcastDir, elf, done, sets) if (is.na(inSample)) inSample <- hindcastInSample(starts, sim$simYears) if (inSample && !is.null(location) && !is.null(starts)) location$seeded <- readHindcastSeeded(starts, hindcastDir, elf, done, sets, hindcastFlammable(burnMap), location$burn$gridCell) + covariates <- readHindcastCovariates(covariateDir, elf, core) + if (is.null(covariates$CMD)) readHindcastCovariate(covariateDir, elf, core) # the fit's covariate: stops, naming the missing file fit <- if (is.null(ledgerFile)) list() else readLedgerRow(ledgerFile, elf) fit$fitAreaHa <- obs$fitAreaHa; fit$totalAreaHa <- obs$nbacAreaHa c(list(elf = elf), sim, obs[c("obsYears", "obsSizes", "escapeSizeHa", "fireCauses")], burnRate(core, obs$obsYears), - list(covariate = readHindcastCovariate(covariateDir, elf, core), fit = fit, location = location, inSample = inSample)) + list(covariate = covariates$CMD, covariates = covariates, fit = fit, location = location, inSample = inSample)) } #' The files [readFireSenseHindcast()] reads for one ELF @@ -326,7 +338,7 @@ hindcastReadFiles <- function(elf, hindcastDir, inputsDir, covariateDir, ledgerF ## the inner functions readFireSenseHindcast() calls: Cache() sees the body of the function it is given, not of these readerCallees <- c("hindcastFinishedYears", "readHindcastSim", "hindcastBurnMap", "hindcastCore", "hindcastFlammable", "observedRecord", - "buildObservedRecord", "readHindcastObserved", "readLedgerRow", "burnRate", "readHindcastCovariate", "fread0", + "buildObservedRecord", "readHindcastObserved", "readLedgerRow", "burnRate", "readHindcastCovariate", "readHindcastCovariates", "fread0", "readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastSetFiles", "rasterizedValues", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded") #' Read every finished ELF's hindcast, each read cached diff --git a/R/residualClimate.R b/R/residualClimate.R new file mode 100644 index 0000000..078f99f --- /dev/null +++ b/R/residualClimate.R @@ -0,0 +1,153 @@ +## Residual climate signal: do the simulation-vs-observation residuals still trend with the year's climate? If a climate variable the +## simulator uses is still related to what it gets wrong, the simulator is missing something. +## Per ELF and scored year the residual is log(simulated / observed), the simulated value being the median over runs, for the annual area burned, +## the mean fire size and the median fire size (fires of `minHa` or more). It is regressed on the within-ELF z-score of each annual climate covariate +## in `elf$covariates` (`data.frame(year, value)` each, named by variable; `elf$covariate` alone is read as one covariate) and on the ELF's own spread-fit climate variable. +## Everything fireSense-specific (the spread coefficients of `elf$fit$params`, their `yearSpreadSD`) is optional: without it those columns are NA. + +residualResponses <- c(area = "annual area burned", areaOffset = "annual area burned, offset by minHa", meanSize = "mean fire size", medianSize = "median fire size") + +## the covariates of an ELF: `covariates`, else the single `covariate` (named "covariate"), else NULL +covariatesOf <- function(elf) if (!is.null(elf$covariates)) elf$covariates else if (!is.null(elf$covariate)) list(covariate = elf$covariate) + +## The climate variable the spread fit uses (the first of `elf$fit$params` that is a climate term, plain or `_yr`/`_dev`/`_curve`); NA without a fit +ownClimate <- function(elf) { + p <- elf$fit$params + if (is.null(p)) return(NA_character_) + b <- fireSenseUtils::climateTermBase(names(p), fireSenseUtils::climateTermSuffixes) + b <- b[b %in% names(fireSenseUtils::climateCovRanges)] + if (length(b)) b[1] else NA_character_ +} + +#' Residuals of the simulation against the observation, per scored year +#' +#' The residual of a response is `log(simulated / observed)`, the simulated value being the median over runs of the year. Responses: `area` (annual area of the fires of `minHa` or more), +#' `areaOffset` (the same with `minHa` added to both, defined in a year without fire too), `meanSize` and `medianSize` (per run over its fires of `minHa` or more, then the median over runs). +#' Rule for years without fire: a year with observed area 0 has no `area` residual, and no `meanSize` or `medianSize` residual (no observed fire to size); it keeps its `areaOffset`. +#' A simulated size is the median over the runs that have a fire, and is NA with fewer than `minReps` of them. Columns `z_` are the covariates standardised over the scored years, +#' `z_own` the one of the spread-fit climate variable ([ownClimate()]). +#' @param elf ELF input list ([runWave1()]). @param minHa Smallest fire (ha) scored. @param minReps Fewest runs with a fire a simulated size is taken from. +#' @return `data.frame(ELF, year, obsArea, simArea, obsMeanSize, simMeanSize, obsMedianSize, simMedianSize, r_, z_, z_own)`, one row per scored year; attribute `own` the spread-fit climate variable. +residualYears <- function(elf, minHa, minReps = 10L) { + yrs <- scoredYears(elf) + at <- function(v, y) { x <- v[match(as.character(yrs), as.character(y))]; as.numeric(x) } # a value per scored year, NA for a year without + ss <- elf$simSizes[elf$simSizes$ha >= minHa, ]; os <- elf$obsSizes[elf$obsSizes$ha >= minHa, ] + simSize <- function(f) { + if (!NROW(ss)) return(rep(NA_real_, length(yrs))) + run <- tapply(ss$ha, list(ss$year, ss$run), f) # year x run, NA where the run has no fire + at(apply(run, 1, function(x) if (sum(!is.na(x)) >= minReps) stats::median(x, na.rm = TRUE) else NA_real_), rownames(run)) + } + obsSize <- function(f) if (NROW(os)) at(tapply(os$ha, os$year, f), sort(unique(os$year))) else rep(NA_real_, length(yrs)) + d <- data.frame(ELF = elf$elf, year = yrs, obsArea = obsBy(elf, "area50", yrs), simArea = medianAreaBy(elf, yrs), + obsMeanSize = obsSize(mean), simMeanSize = simSize(mean), obsMedianSize = obsSize(stats::median), simMedianSize = simSize(stats::median)) + d$r_area <- logRatio(d$simArea, d$obsArea) + d$r_areaOffset <- logRatio(d$simArea, d$obsArea, offset = minHa) + d$r_meanSize <- logRatio(d$simMeanSize, d$obsMeanSize) + d$r_medianSize <- logRatio(d$simMedianSize, d$obsMedianSize) + cv <- covariatesOf(elf) + for (v in names(cv)) d[[paste0("z_", v)]] <- zScore(cv[[v]]$value[match(yrs, cv[[v]]$year)]) + own <- ownClimate(elf) + d$z_own <- if (!is.na(own) && !is.null(d[[paste0("z_", own)]])) d[[paste0("z_", own)]] else NA_real_ + attr(d, "own") <- own + d +} + +#' Slope of the residuals on each climate covariate, per ELF +#' +#' For each response of [residualYears()] and each covariate (and `own`, the spread-fit climate variable, for an ELF that has one): the slope of the residual on the within-ELF z-score, its standard error and the number of years; +#' `slopeAfterOwn` and `seAfterOwn` are the slope of the covariate with the ELF's own variable also in the model (NA for the own variable itself and for an ELF without one). +#' @param ry [residualYears()]. @param minN Fewest finite years a slope is fitted on. +#' @return `data.frame(ELF, response, covariate, ownVariable, slope, se, n, slopeAfterOwn, seAfterOwn)`; NULL without a covariate. +residualSlopes <- function(ry, minN = 8L) { + own <- attr(ry, "own"); zs <- grep("^z_", names(ry), value = TRUE) + if (is.na(own)) zs <- setdiff(zs, "z_own") # no spread-fit climate variable: no own-variable rows + if (!length(zs)) return(NULL) + do.call(rbind, lapply(names(residualResponses), function(r) do.call(rbind, lapply(zs, function(zc) { + v <- sub("^z_", "", zc) + s <- olsSlope(ry[[paste0("r_", r)]], ry[[zc]], minN = minN) + a <- if (is.na(own) || v %in% c("own", own)) c(slope = NA_real_, se = NA_real_) else olsSlope(ry[[paste0("r_", r)]], ry[[zc]], ry$z_own, minN = minN) + data.frame(ELF = ry$ELF[1], response = r, covariate = v, ownVariable = own, slope = s[["slope"]], se = s[["se"]], n = as.integer(s[["n"]]), + slopeAfterOwn = a[["slope"]], seAfterOwn = a[["se"]], row.names = NULL) + })))) +} + +## random-effects (DerSimonian-Laird) summary of slopes `b` with standard errors `se`: c(estimate, se, tau); NAs with none +metaSlope <- function(b, se) { + k <- length(b) + if (!k) return(c(est = NA_real_, se = NA_real_, tau = NA_real_)) + w <- 1 / se^2; fixed <- sum(w * b) / sum(w) + tau2 <- if (k > 1) max(0, (sum(w * (b - fixed)^2) - (k - 1)) / (sum(w) - sum(w^2) / sum(w))) else 0 + wr <- 1 / (se^2 + tau2) + c(est = sum(wr * b) / sum(wr), se = sqrt(1 / sum(wr)), tau = sqrt(tau2)) +} + +#' Pooled residual slope over ELFs +#' +#' Per response and covariate, the median of the ELFs' slopes and the random-effects summary of them (weights from the ELFs' standard errors; [metaSlope()]) with its 95% interval and the between-ELF SD `tau`. +#' `afterOwn` TRUE pools the slopes with the ELF's own variable in the model. The covariate `own` is each ELF's own spread-fit variable. +#' @param slopes [residualSlopes()] of every ELF. +#' @return `data.frame(response, covariate, afterOwn, nELF, medianSlope, metaSlope, metaSE, metaLo, metaHi, tau, nNegative)`; NULL for NULL. +poolResidualSlopes <- function(slopes) { + if (is.null(slopes)) return(NULL) + do.call(rbind, lapply(split(slopes, list(slopes$response, slopes$covariate), drop = TRUE), function(x) do.call(rbind, lapply(c(FALSE, TRUE), function(after) { + b <- if (after) x$slopeAfterOwn else x$slope; se <- if (after) x$seAfterOwn else x$se + k <- is.finite(b) & is.finite(se) & se > 0 + m <- metaSlope(b[k], se[k]) + data.frame(response = x$response[1], covariate = x$covariate[1], afterOwn = after, nELF = sum(k), medianSlope = if (any(k)) stats::median(b[k]) else NA_real_, + metaSlope = m[["est"]], metaSE = m[["se"]], metaLo = m[["est"]] - 1.96 * m[["se"]], metaHi = m[["est"]] + 1.96 * m[["se"]], tau = m[["tau"]], nNegative = sum(b[k] < 0), row.names = NULL) + })))) +} + +#' The fitted spread climate term against the fitted year effect +#' +#' For each parameter set of the spread fit (`elf$fit$params`, one row per set) and each climate term that is the year's ELF-median value (``, `_yr`): the SD over the scored years of +#' `coefficient * (value - min) / (max - min)`, the term on the linear-predictor scale as the spread fit uses it (the range from `elf$fit$covMinMax`, else `fireSenseUtils::climateCovRanges`), +#' next to the set's `yearSpreadSD`. `_dev` and `_curve` terms need the pixels' values, which the ELF input does not hold, and are left out. Rows with `level` "ELF" are the medians over the sets. +#' @param elf ELF input list. @return `data.frame(level, ELF, set, term, coefficient, climateSD, yearSpreadSD, ratio)`; NULL for an ELF without spread coefficients or climate terms. +spreadClimateSD <- function(elf) { + p <- elf$fit$params + if (is.null(p) || !NROW(p)) return(NULL) + terms <- names(p)[fireSenseUtils::climateTermBase(names(p), fireSenseUtils::climateSplitYrSuffix) %in% names(fireSenseUtils::climateCovRanges)] + if (!length(terms)) return(NULL) + yrs <- scoredYears(elf); cv <- covariatesOf(elf); cmm <- elf$fit$covMinMax + ysd <- if ("yearSpreadSD" %in% names(p)) p$yearSpreadSD else rep(NA_real_, NROW(p)) + sets <- do.call(rbind, lapply(terms, function(tm) { + v <- fireSenseUtils::climateTermBase(tm, fireSenseUtils::climateSplitYrSuffix); d <- cv[[v]] + rg <- if (!is.null(cmm) && tm %in% names(cmm)) range(cmm[[tm]]) else fireSenseUtils::climateCovRanges[[v]] + x <- if (!is.null(d)) d$value[match(yrs, d$year)] else rep(NA_real_, length(yrs)) + data.frame(level = "set", ELF = elf$elf, set = seq_len(NROW(p)), term = tm, coefficient = p[[tm]], + climateSD = vapply(p[[tm]], function(b) stats::sd(b * (x - rg[1]) / diff(rg)), 0), yearSpreadSD = ysd, row.names = NULL) + })) + sets$ratio <- sets$climateSD / sets$yearSpreadSD + med <- do.call(rbind, lapply(split(sets, sets$term), function(x) + data.frame(level = "ELF", ELF = x$ELF[1], set = NA_integer_, term = x$term[1], coefficient = stats::median(x$coefficient), climateSD = stats::median(x$climateSD), + yearSpreadSD = stats::median(x$yearSpreadSD), ratio = stats::median(x$ratio), row.names = NULL))) + rbind(sets, med) +} + +#' Residual climate signal of a set of ELFs +#' +#' @param elfs List of ELF inputs ([runWave1()]). @param minHa Smallest fire (ha) scored. +#' @return List: `years` ([residualYears()] of every ELF; a covariate an ELF lacks is NA), `slopes` ([residualSlopes()]), `pooled` ([poolResidualSlopes()]), +#' `spreadSD` ([spreadClimateSD()]); each NULL when no ELF has what it needs. +residualClimateTables <- function(elfs, minHa) { + ry <- lapply(elfs, residualYears, minHa = minHa) + slopes <- do.call(rbind, lapply(ry, residualSlopes)) + list(years = as.data.frame(data.table::rbindlist(ry, fill = TRUE)), slopes = slopes, pooled = poolResidualSlopes(slopes), + spreadSD = do.call(rbind, lapply(elfs, spreadClimateSD))) +} + +#' Write the tables of [residualClimateTables()] +#' +#' Each is written to a temporary file in `outDir` and renamed, so a reader never sees a half-written csv. A NULL table is not written. +#' @param res A [residualClimateTables()] list. @param outDir Folder of the csv files. +#' @return `res`, invisibly. Written: `residualClimate_years.csv`, `residualClimate_slopes.csv`, `residualClimate_pooled.csv`, `residualClimate_spreadSD.csv`. +writeResidualClimate <- function(res, outDir) { + dir.create(outDir, recursive = TRUE, showWarnings = FALSE) + for (n in names(res)) if (!is.null(res[[n]])) { + tmp <- tempfile(paste0("residualClimate_", n, "_"), outDir, ".csv") + utils::write.csv(res[[n]], tmp, row.names = FALSE) + file.rename(tmp, file.path(outDir, paste0("residualClimate_", n, ".csv"))) + } + invisible(res) +} diff --git a/R/runWave1.R b/R/runWave1.R index 9c2d535..4800ae8 100644 --- a/R/runWave1.R +++ b/R/runWave1.R @@ -18,9 +18,10 @@ #' \item `burnableHa`, `burnRate`: burnable area (ha) and mean annual observed area burned over it (% per year, [burnRate()]); optional (NA = ordered last on the page). #' \item `location`, `inSample`: optional; where fire happens (S6, S7, see `R/spatialTests.R`). `inSample = TRUE` marks a hindcast that spreads the observed escapes: S7 is not scored, and `location$seeded` gives S8 and S9 (see `R/escapeTests.R`). #' \item `covariate`: `data.frame(year, value)`, the ELF median of the fit's climate covariate, every year. +#' \item `covariates`: optional; a named list of such tables, one per annual climate variable (the residual climate signal, [residualClimateTables()]). Without it `covariate` is the only one. #' \item `fit`: list with `objective` (ledger objective values), `pipelineObjective` (the same objective recomputed by the #' pipeline, per replicate; `NULL` if not available), `pc` (`p_c` of each kept set) and `p50`, `fitAreaHa` (area of the -#' fires the fit used) and `totalAreaHa` (observed area). +#' fires the fit used) and `totalAreaHa` (observed area); optional `params` (the kept sets' spread coefficients, one row per set) and `covMinMax` ([readLedgerRow()]). #' } #' #' @param elfs List of ELF inputs. @param minHa Smallest fire (ha) scored in the size tests: the escape size the inputs were built with. @param nBoot Bootstrap resamples. @param nNull Draws per year of the AD null. @@ -28,7 +29,7 @@ #' @param adFun The Anderson-Darling statistic (default fireSenseUtils'). #' @return A list. `results`: tidy table `(test, null, level, ELF, measure, value, lo, hi, nELF, nUnits, verdict)`, `level` #' being `"pooled"` or `"ELF"`; `gates`: `(ELF, gate, pass, value, detail, lo, hi, runLo, runHi, obsRank, nRuns, share100kha)` (`lo`, `hi`: bootstrap interval of `value` over runs; `runLo`, `runHi`: 2.5% and 97.5% of `value` over single runs; G2, G4, G6; `obsRank`: where the observed ranks among the single runs, `nRuns`: runs; G2, G4); `perELF`: named list (S1, S2, S3, -#' S4ad, S4largest, S5) of per-ELF-year tables; `bias`: the median run over the observation for area, the 10 largest fires, ignitions and escapes, per ELF and pooled ([biasTable()]; its rows are also in `results`, test `B`, the quantity in `null`); `climate`: the climate response of annual area burned, simulated over observed per ELF and pooled ([climateTable()]; its ratios are also in `results`, test `C`, the metric in `null`); `slopeSplit`: the climate slope split into the slopes of log ignitions, log escape rate and log mean escaped-fire size, simulated over observed as a difference, per ELF and pooled ([slopeSplitTable()]; its differences are also in `results`, test `C`, the part in `null`); `flagged`: ELFs for which G2 or G3 failed, whose skill tests are not meaningful. +#' S4ad, S4largest, S5) of per-ELF-year tables; `bias`: the median run over the observation for area, the 10 largest fires, ignitions and escapes, per ELF and pooled ([biasTable()]; its rows are also in `results`, test `B`, the quantity in `null`); `climate`: the climate response of annual area burned, simulated over observed per ELF and pooled ([climateTable()]; its ratios are also in `results`, test `C`, the metric in `null`); `slopeSplit`: the climate slope split into the slopes of log ignitions, log escape rate and log mean escaped-fire size, simulated over observed as a difference, per ELF and pooled ([slopeSplitTable()]; its differences are also in `results`, test `C`, the part in `null`); `residualClimate`: whether the log(sim / obs) residuals of area, mean and median fire size still trend with annual climate, per ELF and pooled ([residualClimateTables()]; written as `residualClimate_*.csv`); `flagged`: ELFs for which G2 or G3 failed, whose skill tests are not meaningful. runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = 1, adFun = fireSenseUtils:::adStatistic) { if (!length(elfs)) stop("runWave1(): no ELFs to score") names(elfs) <- vapply(elfs, `[[`, "", "elf") @@ -86,6 +87,7 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = climate <- climateTable(elfs) slopeSplit <- slopeSplitTable(elfs) climatePooled <- climatePooledYears(elfs, nBoot, seed) + residualClimate <- residualClimateTables(elfs, minHa) res <- rbind(skillRows, calRows, rankRows) judged <- res$level == "pooled" & res$measure %in% c("skill", "rhoDiff") & res$null %in% c("N1", "N2") # N0 is a floor, not judged res$verdict <- ifelse(judged & is.finite(res$lo), @@ -93,7 +95,7 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = res <- res[, c("test", "null", "level", "ELF", "measure", "value", "lo", "hi", "nELF", "nUnits", "verdict")] res <- rbind(res, biasResultRows(bias), climateResultRows(climate), slopeSplitResultRows(slopeSplit), climatePooledResultRows(climatePooled), escapeResultRows(perELF[c("S8", "S9")], runs[c("S8", "S9")], nBoot, seed)) rownames(res) <- NULL - list(results = res, gates = gates, bias = bias, climate = climate, slopeSplit = slopeSplit, climatePooled = climatePooled, perELF = perELF, flagged = flagged) + list(results = res, gates = gates, bias = bias, climate = climate, slopeSplit = slopeSplit, climatePooled = climatePooled, residualClimate = residualClimate, perELF = perELF, flagged = flagged) } bootRankRows <- function(rankD, nBoot, seed) { diff --git a/fireSimulator_validation.R b/fireSimulator_validation.R index c059cb1..6b7a785 100644 --- a/fireSimulator_validation.R +++ b/fireSimulator_validation.R @@ -15,7 +15,7 @@ defineModule(sim, list( documentation = list("README.md"), reqdPkgs = list("data.table", "reproducible", "MASS", "withr", "ggplot2", "patchwork", "scales", "jsonlite", "terra", "PredictiveEcology/SpaDES.core@development (>= 3.2.1.9047)", # 9037: reads `.neverCache`; 9047: defineParameter(cacheKey = FALSE) - "FOR-CAST/fireregimetools@main (>= 0.1.0.9001)", "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9158)"), + "FOR-CAST/fireregimetools@main (>= 0.1.0.9001)", "PredictiveEcology/fireSenseUtils@development (>= 0.2.3.9196)"), parameters = bindrows( defineParameter("nBoot", "integer", 999L, 1L, NA, "Bootstrap resamples of ELFs and years for the pooled verdicts."), defineParameter("nNull", "integer", 199L, 1L, NA, "Draws per year of the Anderson-Darling null."), @@ -110,7 +110,7 @@ defineModule(sim, list( createsOutput("anovaResults", "list", "Mode 'anova': `terms` (per metric and term: df, pctSS, dropOnePctSS, F, p, note), `cells` and `long`, from computeAnova(); the first two are also written to /anova_terms.csv and anova_cells.csv."), createsOutput("weightsResults", "list", "Mode 'weights': `report`, `tuning` and `losses`, from tuneWeights(); also written to /weights_report.csv, weights_tuning.csv and weights_losses.csv."), createsOutput("bySetResults", "data.frame", "Mode 'score' with bySet: scoreBySet() of every ELF, written to /wave1_bySet.csv. NULL otherwise."), - createsOutput("validationResults", "list", "runWave1() result: results, gates, bias, climate, slopeSplit, perELF, flagged. Also saved to /wave1.rds, its results table to wave1_results.csv, and the page to validation.html.") + createsOutput("validationResults", "list", "runWave1() result: results, gates, bias, climate, slopeSplit, perELF, flagged. Also saved to /wave1.rds, its results table to wave1_results.csv, and the page to validation.html; `residualClimate` also to residualClimate_years.csv, _slopes.csv, _pooled.csv and _spreadSD.csv.") ) )) @@ -187,6 +187,7 @@ doEvent.fireSimulator_validation <- function(sim, eventTime, eventType) { out <- outputPath(sim); dir.create(out, recursive = TRUE, showWarnings = FALSE) saveRDS(sim$validationResults, file.path(out, "wave1.rds")) utils::write.csv(sim$validationResults$results, file.path(out, "wave1_results.csv"), row.names = FALSE) + writeResidualClimate(sim$validationResults$residualClimate, out) if (P(sim)$bySet) utils::write.csv(sim$bySetResults, file.path(out, "wave1_bySet.csv"), row.names = FALSE) buildValidationPage(sim$validationELFs, sim$validationResults$gates, file.path(out, "validation.html"), template = file.path(modulePath(sim), currentModule(sim), "pageTemplate.html"), diff --git a/tests/testthat/test-byset.R b/tests/testthat/test-byset.R index 9cb909d..d955f7c 100644 --- a/tests/testthat/test-byset.R +++ b/tests/testthat/test-byset.R @@ -26,6 +26,14 @@ test_that("readHindcastCovariate finds the climate in one shared folder per ELF expect_equal(readHindcastCovariate(root, "9.9", terra::setValues(g, 1))$value, c(5, 7)) }) +test_that("readHindcastCovariates reads every annual climate variable the hindcast has and leaves the others out", { + root <- withr::local_tempdir() + g <- writeToyClimate(file.path(root, "9.9", "climate"), "9.9", 1986:1987, c(5, 7)) + writeToyClimate(file.path(root, "9.9", "climate"), "9.9", 1986:1987, c(1, 3), variable = "Tmaxsm") + r <- readHindcastCovariates(root, "9.9", terra::setValues(g, 1)) + expect_equal(names(r), c("CMD", "Tmaxsm")); expect_equal(r$Tmaxsm$value, c(1, 3)); expect_equal(r$CMD$year, 1986:1987) +}) + ## One year, two parameter sets in one folder (paramSet column), 3 reps each; set 2 has twice the area of set 1 mkTwoSets <- function(root, elf, years = c(1986L, 1991L)) { for (y in years) { diff --git a/tests/testthat/test-residualClimate.R b/tests/testthat/test-residualClimate.R new file mode 100644 index 0000000..2f2d8c6 --- /dev/null +++ b/tests/testthat/test-residualClimate.R @@ -0,0 +1,129 @@ +## Residual climate signal: log(sim / obs) of area and fire sizes against the year's climate. Synthetic ELFs with a known climate response of the observation. + +## An ELF over the years 1986-2024 whose observed fires respond to `zObs` with slope `b` (log scale) and whose runs do not. Two observed fires a year (100 and 200 ha times the response), +## so the observed mean and median size are 150 times it. `noFire` years have no observed fire. `cov` are the covariates (named list of z-score-like values). +residToy <- function(b = 0.5, noFire = integer(0), nRuns = 12L, cov = NULL, own = NULL, seed = 1, years = 1986:2024) { + set.seed(seed) + z <- as.numeric(scale(sin(seq_along(years) * 1.7) + seq_along(years) / 40 + rnorm(length(years), sd = 0.3))) + f <- exp(b * z + rnorm(length(years), sd = 0.05)); has <- !years %in% noFire + obsSizes <- do.call(rbind, lapply(which(has), function(i) data.frame(year = years[i], ha = c(100, 200) * f[i]))) + obsYears <- data.frame(year = years, ignitions = 2, escapes = 2L * has, area50 = ifelse(has, 300 * f, 0)) + g <- expand.grid(year = years, run = seq_len(nRuns)) + simSizes <- do.call(rbind, lapply(1:2, function(k) data.frame(g, ha = c(100, 200)[k] * exp(rnorm(nrow(g), sd = 0.05))))) + simYears <- data.frame(g, ignitions = 2, escapes = 2L, area50 = tapply(simSizes$ha, paste(simSizes$year, simSizes$run), sum)[paste(g$year, g$run)]) + cv <- if (is.null(cov)) list(CMDsm = data.frame(year = years, value = 100 + 20 * z)) else lapply(cov(z), function(v) data.frame(year = years, value = v)) + list(elf = "resid", simYears = simYears, simSizes = simSizes, obsYears = obsYears, obsSizes = obsSizes, covariate = cv[[1]], covariates = cv, + fit = if (!is.null(own)) own, z = z) +} +slopeOf <- function(sl, response, covariate) sl[sl$response == response & sl$covariate == covariate, ] + +test_that("the injected climate slope is recovered for area and both sizes (the residual is sim over obs, so the slope is minus the response)", { + e <- residToy(b = 0.5); ry <- residualYears(e, minHa = toyMinHa); sl <- residualSlopes(ry) + for (r in c("area", "meanSize", "medianSize")) { + s <- slopeOf(sl, r, "CMDsm") + expect_equal(s$slope, -0.5, tolerance = 0.06); expect_gt(s$se, 0); expect_equal(s$n, 39L) + } + so <- slopeOf(sl, "areaOffset", "CMDsm"); expect_equal(so$n, 39L); expect_true(so$slope < -0.35 && so$slope > -0.5) # the offset (50 ha on ~300 ha) dilutes it + expect_equal(slopeOf(sl, "area", "CMDsm")$slope / slopeOf(sl, "area", "CMDsm")$se < -10, TRUE) + e0 <- residToy(b = 0); expect_lt(abs(slopeOf(residualSlopes(residualYears(e0, toyMinHa)), "area", "CMDsm")$slope), 0.06) +}) + +test_that("years with no observed fire: no area or size residual, but the offset area residual is defined; they are left out of n", { + nf <- c(1990L, 2000L, 2010L) + e <- residToy(noFire = nf); ry <- residualYears(e, toyMinHa) + expect_true(all(is.na(ry$r_area[ry$year %in% nf]))); expect_true(all(is.na(ry$r_meanSize[ry$year %in% nf]))); expect_true(all(is.na(ry$r_medianSize[ry$year %in% nf]))) + expect_true(all(is.finite(ry$r_areaOffset))) + expect_equal(ry$r_areaOffset[ry$year == 1990L], log((ry$simArea[ry$year == 1990L] + toyMinHa) / toyMinHa)) + sl <- residualSlopes(ry) + expect_equal(slopeOf(sl, "area", "CMDsm")$n, 36L); expect_equal(slopeOf(sl, "areaOffset", "CMDsm")$n, 39L) + expect_equal(slopeOf(sl, "meanSize", "CMDsm")$slope, -0.5, tolerance = 0.07) +}) + +test_that("a simulated size from fewer than minReps runs with a fire is NA; fires under minHa are ignored", { + e <- residToy(nRuns = 5L) + expect_true(all(is.na(residualYears(e, toyMinHa)$r_meanSize))); expect_true(all(is.finite(residualYears(e, toyMinHa, minReps = 5L)$r_meanSize))) + big <- residualYears(e, 150, minReps = 5L) # only the 200 ha fires count: observed size is 200 times the response + expect_equal(big$obsMeanSize[1], 200 * residToy(nRuns = 5L)$obsSizes$ha[2] / 200, tolerance = 1e-8) +}) + +test_that("the slope after the ELF's own variable: a covariate that only follows the own one has none left, the own one has no after-own row", { + own <- list(params = data.frame(CMDsm = c(1, 2), yearSpreadSD = c(0.1, 0.2))) + set.seed(2) + e <- residToy(b = 0.5, cov = function(z) list(CMDsm = 100 + 20 * z, CMD = 500 + 40 * (0.8 * z + 0.6 * rnorm(length(z))), PPTsm = 50 + 10 * rnorm(length(z))), own = own) + sl <- residualSlopes(residualYears(e, toyMinHa)) + expect_equal(slopeOf(sl, "area", "own")$slope, slopeOf(sl, "area", "CMDsm")$slope) + expect_equal(unique(sl$ownVariable), "CMDsm") + cmd <- slopeOf(sl, "area", "CMD") + expect_lt(cmd$slope, -0.2) # CMD follows the own variable, so the residual trends with it too ... + expect_lt(abs(cmd$slopeAfterOwn), 0.2); expect_lt(abs(cmd$slopeAfterOwn), abs(cmd$slope)) # ... and does not once the own variable is in the model + expect_true(is.na(slopeOf(sl, "area", "CMDsm")$slopeAfterOwn)); expect_true(is.na(slopeOf(sl, "area", "own")$slopeAfterOwn)) +}) + +test_that("a model without spread coefficients (or one covariate only) gives NA own-variable columns and no spread table", { + e <- residToy(); e$covariates <- NULL; e$covariate <- data.frame(year = 1986:2024, value = e$z) + ry <- residualYears(e, toyMinHa); sl <- residualSlopes(ry) + expect_true(is.na(attr(ry, "own"))); expect_equal(unique(sl$covariate), "covariate") + expect_true(all(is.na(sl$slopeAfterOwn))) + expect_equal(slopeOf(sl, "area", "covariate")$slope, -0.5, tolerance = 0.06) + expect_null(spreadClimateSD(e)) + expect_null(residualSlopes(residualYears({ x <- residToy(); x$covariates <- NULL; x$covariate <- NULL; x }, toyMinHa))) +}) + +test_that("a constant covariate or too few years give an NA slope, not an error", { + e <- residToy(cov = function(z) list(CMDsm = rep(3, length(z)), PPTsm = z)) + sl <- residualSlopes(residualYears(e, toyMinHa)) + expect_true(is.na(slopeOf(sl, "area", "CMDsm")$slope)); expect_equal(slopeOf(sl, "area", "PPTsm")$slope, -0.5, tolerance = 0.06) + expect_true(is.na(olsSlope(1:5, c(1, 3, 2, 5, 4))[["slope"]])) # 5 years < minN +}) + +test_that("spreadClimateSD: SD of coefficient x scaled covariate next to yearSpreadSD, medians over sets; _dev and _curve terms are left out", { + p <- data.frame(CMDsm = c(2, 4, 6), CMDsm_dev = 1, yearSpreadSD = c(0.2, 0.5, 1)) + e <- residToy(own = list(params = p, covMinMax = data.frame(CMDsm = c(0, 200)))) + x <- 100 + 20 * e$z; sd1 <- stats::sd(x) / 200 + s <- spreadClimateSD(e) + expect_equal(unique(s$term), "CMDsm"); expect_equal(s$climateSD[s$level == "set"], c(2, 4, 6) * sd1) + expect_equal(s$ratio[s$level == "set"], c(2, 4, 6) * sd1 / c(0.2, 0.5, 1)) + m <- s[s$level == "ELF", ]; expect_equal(m$climateSD, 4 * sd1); expect_equal(m$yearSpreadSD, 0.5); expect_equal(m$ratio, median(c(2, 4, 6) * sd1 / c(0.2, 0.5, 1))) + e$fit$covMinMax <- NULL # fixed range of fireSenseUtils::climateCovRanges (0-100) + expect_equal(spreadClimateSD(e)$climateSD[1], 2 * stats::sd(x) / 100) + e$fit$params$yearSpreadSD <- NULL; expect_true(all(is.na(spreadClimateSD(e)$yearSpreadSD))) + e$fit$params <- data.frame(PPT = 1); expect_null(spreadClimateSD(e)) +}) + +test_that("poolResidualSlopes: median and random-effects slope over ELFs; an ELF without a slope is left out", { + sl <- data.frame(ELF = LETTERS[1:5], response = "area", covariate = "CMD", ownVariable = NA, slope = c(-0.4, -0.5, -0.6, -0.5, NA), se = c(0.1, 0.1, 0.2, 0.1, NA), n = 30L, + slopeAfterOwn = c(0.1, NA, NA, NA, NA), seAfterOwn = c(0.1, NA, NA, NA, NA)) + p <- poolResidualSlopes(sl); a <- p[!p$afterOwn, ] + expect_equal(a$nELF, 4L); expect_equal(a$medianSlope, -0.5); expect_equal(a$nNegative, 4L) + expect_equal(a$metaSlope, -155 / 325) # inverse-variance weighted, no heterogeneity beyond chance (tau 0) + expect_equal(a$tau, 0); expect_lt(a$metaLo, a$metaSlope); expect_gt(a$metaHi, a$metaSlope) + expect_equal(p$nELF[p$afterOwn], 1L) + het <- metaSlope(c(-1, 0, 1, 2), rep(0.1, 4)); expect_equal(het[["est"]], 0.5); expect_equal(het[["tau"]], sqrt(var(c(-1, 0, 1, 2)) - 0.01), tolerance = 1e-8) + expect_null(poolResidualSlopes(NULL)) +}) + +test_that("residualClimateTables and the writer: four csv tables, written whole; a NULL table is not written", { + es <- list(residToy(seed = 1, own = list(params = data.frame(CMDsm = 2, yearSpreadSD = 0.3))), { x <- residToy(seed = 2, b = 0.3); x$elf <- "resid2"; x }) + res <- residualClimateTables(es, toyMinHa) + expect_equal(names(res), c("years", "slopes", "pooled", "spreadSD")) + expect_equal(sort(unique(res$years$ELF)), c("resid", "resid2")); expect_equal(unique(res$slopes$ELF), c("resid", "resid2")) + expect_equal(unique(res$spreadSD$ELF), "resid"); expect_equal(res$pooled$nELF[res$pooled$response == "area" & res$pooled$covariate == "CMDsm" & !res$pooled$afterOwn], 2L) + out <- file.path(withr::local_tempdir(), "o") + writeResidualClimate(res, out) + expect_setequal(list.files(out), paste0("residualClimate_", c("years", "slopes", "pooled", "spreadSD"), ".csv")) + expect_equal(nrow(utils::read.csv(file.path(out, "residualClimate_slopes.csv"))), nrow(res$slopes)) + out2 <- withr::local_tempdir(); res$spreadSD <- NULL; writeResidualClimate(res, out2) + expect_false(file.exists(file.path(out2, "residualClimate_spreadSD.csv"))); expect_length(list.files(out2), 3L) +}) + +test_that("readLedgerRow returns the kept sets' coefficients and the covariate ranges; runWave1 returns the residual climate tables", { + f <- withr::local_tempfile(fileext = ".rds") + sp <- data.frame(polygonID = "9.9"); sp$params <- list(data.frame(maxAsymptote = c(0.2, 0.21), CMDsm = c(1, 2), yearSpreadSD = c(0.1, 0.2))) + sp$objFunVal <- list(c(100, 101)); sp$covMinMax_spread <- list(data.frame(CMDsm = c(0, 200))) + saveRDS(sp, f) + r <- readLedgerRow(f, "9.9"); expect_equal(r$params$CMDsm, c(1, 2)); expect_equal(r$covMinMax$CMDsm, c(0, 200)) + sp$covMinMax_spread <- NULL; saveRDS(sp, f); expect_null(readLedgerRow(f, "9.9")$covMinMax) + w <- runWave1(list(toyElf("a", seed = 1), toyElf("b", seed = 2)), toyMinHa, nBoot = 5, nNull = 5, nPerm = 20) + expect_equal(names(w$residualClimate), c("years", "slopes", "pooled", "spreadSD")); expect_null(w$residualClimate$spreadSD) + expect_equal(unique(w$residualClimate$slopes$covariate), "covariate") +}) diff --git a/tests/testthat/test-skill.R b/tests/testthat/test-skill.R index ba67303..be66f19 100644 --- a/tests/testthat/test-skill.R +++ b/tests/testthat/test-skill.R @@ -61,7 +61,7 @@ test_that("the runner returns the tidy table, gates, per-ELF tables and the flag elfs <- list(toyElf("a", perfect = TRUE, seed = 1), toyElf("b", perfect = TRUE, seed = 2), toyElf("c", perfect = FALSE, seed = 3)) elfs[[3]]$fit$fitAreaHa <- 0 # fails G3 out <- runWave1(elfs, toyMinHa, nBoot = 49, nNull = 29, nPerm = 99) - expect_named(out, c("results", "gates", "bias", "climate", "slopeSplit", "climatePooled", "perELF", "flagged")) + expect_named(out, c("results", "gates", "bias", "climate", "slopeSplit", "climatePooled", "residualClimate", "perELF", "flagged")) expect_equal(out$flagged, "c") expect_equal(nrow(out$gates), 18) r <- out$results