From 1df41dfd5e9a549a3abb751b2a78301a631c9df1 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Wed, 25 Nov 2026 14:48:14 -0700 Subject: [PATCH] Climate slope split into ignition, escape-rate and fire-size slopes (table, results rows, page table) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 + R/buildPage.R | 5 +- R/climateResponse.R | 91 ++++++++++++++++++++++++++++---- R/runWave1.R | 7 +-- fireSimulator_validation.R | 4 +- pageTemplate.html | 24 +++++++++ tests/testthat/helper-source.R | 10 ++++ tests/testthat/test-climate.R | 12 +---- tests/testthat/test-skill.R | 2 +- tests/testthat/test-slopeSplit.R | 75 ++++++++++++++++++++++++++ 10 files changed, 205 insertions(+), 27 deletions(-) create mode 100644 tests/testthat/test-slopeSplit.R diff --git a/NEWS.md b/NEWS.md index b5af703..526ce5d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # fireSimulator_validation (development version) +* New table "Climate slope by channel": which of the three parts of the climate response carries the difference between the simulated and the observed slope. log(annual area) = log(ignitions) + log(escape rate) + log(mean escaped-fire size) (escapes = fires of the escape size or more, area = `area50`), so the slope of log area on the standardised covariate is the sum of three slopes. `scoreSlopeSplit()` gives, per ELF, the observed slope and, per run, the slope of each part over the same years (the scored years with an ignition, an escape and some area; a year with no escape is left out of all three parts, so they add up exactly to the total slope on those years), reported as simulated (median of runs, single-run range), observed and the difference sim - obs with the observed rank; `slopeSplitTable()` adds the median over ELFs with its 2.5-97.5% range over ELFs (`elfRange()`). `runWave1()` returns it as `slopeSplit` and adds its rows to `results` (test `C`, `null` = `slopeIgnitions`, `slopeEscapeRate`, `slopeSize`, measure `difference`); `buildValidationPage()` has a new argument `slopeSplit` and the page a sortable table under the climate table, with a note that the three differences add up to the total slope difference. The covariate, years and slope helpers are the climate table's (`climateInputs()`, `logSlope()`, `withPooled()`). + * The climate `slope` is reported in its own units instead of as sim / obs, which is unstable when the observed slope is near 0 (on the 47-ELF national score: -3.7 to 13.4, 3 negative ELFs). Per ELF the climate table has the simulated slope (median over runs, 2.5-97.5% range of single runs: new columns `simLo`, `simHi`), the observed slope and the difference sim - obs (`ratio` column: median over runs of the per-run difference, with the single-run range); an observed slope of 0 now gives a finite difference. `obsRank` of the slope is the share of runs with a slope below the observed (`runSummary()` has a new argument `at`, the value that means the observed: 1 for ratios, 0 for the difference). The pooled slope row is the median over ELFs of the difference. In `wave1_results.csv` the slope rows of test `C` have measure `difference`; `dry10` and `wetHalf` stay ratios. The page's climate table shows Simulated slope, Observed slope, Difference (sim - obs), Driest 10%, Wetter half. * The pooled range over ELFs (bias and climate tables, `elfLo`/`elfHi`, `meanLo`/`meanHi`, and the `lo`/`hi` of pooled rows in `wave1_results.csv`) is now the 2.5-97.5% quantiles over ELFs (`elfRange()`, used by `poolRatios()`), as the page's notes say; it was the minimum and maximum, so one ELF with a wild value set it. Pooled medians are unchanged. diff --git a/R/buildPage.R b/R/buildPage.R index b645829..9676c94 100644 --- a/R/buildPage.R +++ b/R/buildPage.R @@ -13,12 +13,13 @@ ratioCell <- function(ratio, lo, hi, obsRank) round(c(ratio, lo, hi, obsRank), 3 #' @param elfs List of ELF inputs ([runWave1()]); `elf` is the id shown on the page. #' @param gates The `gates` table of [runWave1()] (its `ELF` values are the ids of `elfs`). Only G2, G4 and G6 are used. #' @param climate The `climate` table of [runWave1()], for the climate-response table of the page; `NULL`: none. +#' @param slopeSplit The `slopeSplit` table of [runWave1()], for the table of the climate slope's three parts under the climate table; `NULL`: none. #' @param bias The `bias` table of [runWave1()] (per ELF and pooled), for the bias table of the page; `NULL`: no bias table. #' @param file Where to write the page. @param template Path of `pageTemplate.html`. #' @param title The page title (browser tab and heading). @param subtitle One line under the title. @param label Name of the simulated series in the figures. @param minHa Escape size. #' @param dpi Resolution of the inlined figures (80 keeps a 16-ELF page near 9 MB). #' @return `file`, invisibly. -buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast validation", subtitle = "", label = "simulated", minHa, dpi = 80, bias = NULL, climate = NULL) { +buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast validation", subtitle = "", label = "simulated", minHa, dpi = 80, bias = NULL, climate = NULL, slopeSplit = NULL) { ids <- vapply(elfs, `[[`, "", "elf"); names(elfs) <- ids summ <- summariseGates(gates); summ$ELF <- as.character(summ$ELF) summ$burnRate <- vapply(elfs[summ$ELF], function(e) e$burnRate %||% NA_real_, 0) # for elfOrder(); an ELF input without one sorts last @@ -40,11 +41,13 @@ buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast v r }) biasRows <- biasPageRows(bias) climateRows <- climatePageRows(climate) + slopeSplitRows <- slopeSplitPageRows(slopeSplit) tpl <- paste(readLines(template, warn = FALSE), collapse = "\n") fill <- function(pat, val) tpl <<- sub(pat, val, tpl, fixed = TRUE) fill("/*ROWS*/[]", as.character(jsonlite::toJSON(rows, auto_unbox = TRUE, na = "null"))) fill("/*BIAS*/[]", as.character(jsonlite::toJSON(biasRows, auto_unbox = TRUE, na = "null"))) fill("/*CLIMATE*/[]", as.character(jsonlite::toJSON(climateRows, auto_unbox = TRUE, na = "null"))) + fill("/*SLOPESPLIT*/[]", as.character(jsonlite::toJSON(slopeSplitRows, auto_unbox = TRUE, na = "null"))) fill("/*IMG*/{}", as.character(jsonlite::toJSON(img, auto_unbox = TRUE))) tpl <- gsub("__OVERVIEW__", overview, tpl, fixed = TRUE) tpl <- gsub("__TITLE__", title, tpl, fixed = TRUE) diff --git a/R/climateResponse.R b/R/climateResponse.R index 05535fc..cbec55c 100644 --- a/R/climateResponse.R +++ b/R/climateResponse.R @@ -4,6 +4,17 @@ climateMetrics <- c(slope = "climate slope", dry10 = "driest 10% of years", wetHalf = "wetter half of years") +## 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)) +} + +## 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]) } + #' Climate response of one ELF #' #' Three comparisons of the simulated with the observed record over the scored years, each computed for every run alone. Area is `area50` (fires of the escape size or @@ -20,13 +31,11 @@ climateMetrics <- c(slope = "climate slope", dry10 = "driest 10% of years", wetH #' @return `data.frame`, one row per metric: `level` ("ELF"), `ELF`, `metric`, `observed` (the observed slope, or area in ha), `simMedian`, `simLo`, `simHi` (median, 2.5% and 97.5% over runs of the run's value), `ratio` (median over runs of the #' run's value relative to the observed: the difference sim - obs for the slope, the ratio for the areas), `runLo`, `runHi` (2.5% and 97.5% of the single runs' `ratio`), `obsRank` (share of runs below the observed), `elfLo`, `elfHi` (NA here), `nELF` (1), `nNonFinite` (0), `nRuns`, `nYears`. scoreClimateResponse <- 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) - z <- (cv - mean(cv)) / stats::sd(cv) + ci <- climateInputs(elf) + if (is.null(ci)) return(NULL) + years <- ci$years; z <- ci$z dry <- z >= stats::quantile(z, 0.9); wet <- z <= stats::median(z) - slopeOf <- function(area) { k <- !is.na(area) & area > 0; if (sum(k) < 3) NA_real_ else unname(stats::coef(stats::lm(log(area[k]) ~ z[k]))[2]) } - values <- function(area) c(slope = slopeOf(area), dry10 = sum(area[dry], na.rm = TRUE), wetHalf = sum(area[wet], na.rm = TRUE)) # area: per scored year, in `years` order + values <- function(area) c(slope = logSlope(log(area), z), dry10 = sum(area[dry], na.rm = TRUE), wetHalf = sum(area[wet], na.rm = TRUE)) # area: per scored year, in `years` order obs <- values(obsBy(elf, "area50", years)) ratioTo <- function(v) c(slope = v[["slope"]] - obs[["slope"]], dry10 = zeroSafeRatio(v[["dry10"]], obs[["dry10"]]), wetHalf = zeroSafeRatio(v[["wetHalf"]], obs[["wetHalf"]])) @@ -42,10 +51,12 @@ scoreClimateResponse <- function(elf) { #' #' @param elfs List of ELF inputs ([runWave1()]). @return The rows of [scoreClimateResponse()] of every ELF with a covariate, then per metric a pooled row (`level` "pooled", `ELF` "all") from [poolRatios()]: #' `ratio` the median over ELFs of the ELF values (the slope's difference, the area ratios), `elfLo`, `elfHi` their 2.5-97.5% range over ELFs, `nELF` the ELFs, `nNonFinite` those left out as not finite. `NULL` when no ELF has a covariate. -climateTable <- function(elfs) { - x <- do.call(rbind, lapply(elfs, scoreClimateResponse)) +climateTable <- function(elfs) withPooled(do.call(rbind, lapply(elfs, scoreClimateResponse))) + +## the rows of `x` (one per ELF and metric, as scoreClimateResponse() gives) and per metric a pooled row (`level` "pooled", `ELF` "all") from poolRatios(); NULL for NULL +withPooled <- function(x) { if (is.null(x)) return(NULL) - pooled <- do.call(rbind, lapply(names(climateMetrics), function(m) { + pooled <- do.call(rbind, lapply(unique(x$metric), function(m) { pr <- poolRatios(x[x$metric == m, ]) data.frame(level = "pooled", ELF = "all", metric = m, observed = NA_real_, simMedian = NA_real_, simLo = NA_real_, simHi = NA_real_, ratio = pr$ratio, runLo = NA_real_, runHi = NA_real_, obsRank = pr$obsRank, elfLo = pr$elfLo, elfHi = pr$elfHi, nELF = pr$nELF, nNonFinite = pr$nNonFinite, nRuns = NA_integer_, nYears = pr$nYears) @@ -75,3 +86,65 @@ climatePageRows <- function(climate) { c(list(rowOf("all: median of ELFs", climate[climate$level == "pooled", ])), lapply(unique(climate$ELF[climate$level == "ELF"]), function(id) rowOf(id, climate[climate$level == "ELF" & climate$ELF == id, ]))) } + +## Which channel is the missing climate response in? log(area) = log(ignitions) + log(escapes / ignitions) + log(area / escapes), so the slope of log annual area on the standardised covariate is the sum of three slopes. +slopeSplitMetrics <- c(slopeIgnitions = "ignitions", slopeEscapeRate = "escape rate", slopeSize = "mean escaped-fire size") + +## the three slopes of one record (`ignitions`, `escapes`, `area` per scored year, NA for a year it lacks). Only years with at least one ignition, one escape and some area enter: a year with no escape has no +## log(area / escapes), so it is left out of all three, and the three then add up exactly to the slope of log(area) on those years (least-squares slopes are linear in the response). +slopeParts <- function(ignitions, escapes, area, z) { + k <- (ignitions > 0 & escapes > 0 & area > 0) %in% TRUE + y <- function(v) ifelse(k, v, NA_real_) + c(slopeIgnitions = logSlope(y(log(ignitions)), z), slopeEscapeRate = logSlope(y(log(escapes / ignitions)), z), slopeSize = logSlope(y(log(area / escapes)), z)) +} + +#' The climate slope split into its ignition, escape-rate and fire-size parts +#' +#' The slope of log annual area burned on the covariate ([scoreClimateResponse()]) is the sum of three slopes: of log ignitions, of log escape rate (escapes / ignitions) and of log mean escaped-fire size +#' (`area50` / escapes), each on the covariate standardised over the scored years. Each is computed for the observed record and for every run, over the same years: the scored years with at least one ignition, +#' one escape and some area (a year without an escape is left out of all three parts, as it is of the total slope, so the parts add up to the total slope on those years). A slope is NA with fewer than 3 such years. +#' Each part is reported as the difference sim - obs, in log units per standard deviation of the covariate; the three differences add up to the total slope difference. +#' +#' @param elf An ELF input list ([runWave1()]); without a `covariate` of the scored years there is no result (`NULL`). +#' @return `data.frame`, one row per part (`metric` `slopeIgnitions`, `slopeEscapeRate`, `slopeSize`), with the columns of [scoreClimateResponse()]. +scoreSlopeSplit <- function(elf) { + ci <- climateInputs(elf) + if (is.null(ci)) return(NULL) + years <- ci$years + obs <- slopeParts(obsBy(elf, "ignitions", years), obsBy(elf, "escapes", years), obsBy(elf, "area50", years), ci$z) + runs <- lapply(split(elf$simYears, elf$simYears$run), function(r) { i <- match(years, r$year); slopeParts(r$ignitions[i], r$escapes[i], r$area50[i], ci$z) }) + v <- do.call(rbind, runs); single <- vapply(runs, function(s) s - obs, numeric(3)); rs <- runSummary(single, at = 0) + data.frame(level = "ELF", ELF = elf$elf, metric = names(slopeSplitMetrics), observed = unname(obs), simMedian = apply(v, 2, stats::median, na.rm = TRUE), + simLo = apply(v, 2, stats::quantile, 0.025, na.rm = TRUE, names = FALSE), simHi = apply(v, 2, stats::quantile, 0.975, na.rm = TRUE, names = FALSE), + ratio = apply(single, 1, medFinite), runLo = rs$runLo, runHi = rs$runHi, obsRank = rs$obsRank, + elfLo = NA_real_, elfHi = NA_real_, nELF = 1L, nNonFinite = 0L, nRuns = length(runs), nYears = length(years), row.names = NULL) +} + +#' The slope split of every ELF, and pooled +#' +#' @param elfs List of ELF inputs ([runWave1()]). @return The rows of [scoreSlopeSplit()] of every ELF with a covariate, then per part a pooled row from [withPooled()] (as [climateTable()]). `NULL` when no ELF has a covariate. +slopeSplitTable <- function(elfs) withPooled(do.call(rbind, lapply(elfs, scoreSlopeSplit))) + +## `slopeSplit` as rows of the long `results` table: test "C", the part in `null`, measure "difference" +slopeSplitResultRows <- function(slopeSplit) { + if (is.null(slopeSplit)) return(NULL) + p <- slopeSplit$level == "pooled" + longRows(slopeSplit, "C", slopeSplit$metric, "difference", slopeSplit$ratio, ifelse(p, slopeSplit$elfLo, slopeSplit$runLo), ifelse(p, slopeSplit$elfHi, slopeSplit$runHi)) +} + +## the rows of the page's slope-split table, as climatePageRows(): per part `` the difference cell, `sim` the simulated slope cell (no pooled one), `obs` the observed slope +slopeSplitPageRows <- function(slopeSplit) { + if (is.null(slopeSplit)) return(list()) + rowOf <- function(label, x) { + r <- list(elf = label) + for (m in names(slopeSplitMetrics)) { + z <- x[x$metric == m, ] + r[[m]] <- rangeCell(z, z$level == "pooled") + r[[paste0("sim", m)]] <- ratioCell(z$simMedian, z$simLo, z$simHi, NA_real_) + r[[paste0("obs", m)]] <- signif(z$observed, 3) + } + r + } + c(list(rowOf("all: median of ELFs", slopeSplit[slopeSplit$level == "pooled", ])), + lapply(unique(slopeSplit$ELF[slopeSplit$level == "ELF"]), function(id) rowOf(id, slopeSplit[slopeSplit$level == "ELF" & slopeSplit$ELF == id, ]))) +} diff --git a/R/runWave1.R b/R/runWave1.R index a6c7fd9..f88a1fe 100644 --- a/R/runWave1.R +++ b/R/runWave1.R @@ -27,7 +27,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`); `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`); `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") @@ -73,14 +73,15 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = rankRows$test <- "S5"; rankRows$null <- ifelse(rankRows$measure == "pPermN0", "N0", "N2") bias <- biasTable(elfs, nBoot, seed) climate <- climateTable(elfs) + slopeSplit <- slopeSplitTable(elfs) 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), ifelse(res$lo > 0, "beats null", ifelse(res$hi < 0, "worse than null", "no difference")), NA_character_) res <- res[, c("test", "null", "level", "ELF", "measure", "value", "lo", "hi", "nELF", "nUnits", "verdict")] - res <- rbind(res, biasResultRows(bias), climateResultRows(climate)) + res <- rbind(res, biasResultRows(bias), climateResultRows(climate), slopeSplitResultRows(slopeSplit)) rownames(res) <- NULL - list(results = res, gates = gates, bias = bias, climate = climate, perELF = perELF, flagged = flagged) + list(results = res, gates = gates, bias = bias, climate = climate, slopeSplit = slopeSplit, perELF = perELF, flagged = flagged) } bootRankRows <- function(rankD, nBoot, seed) { diff --git a/fireSimulator_validation.R b/fireSimulator_validation.R index 63b5fef..e46272e 100644 --- a/fireSimulator_validation.R +++ b/fireSimulator_validation.R @@ -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, 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.") ) )) @@ -191,7 +191,7 @@ doEvent.fireSimulator_validation <- function(sim, eventTime, eventType) { buildValidationPage(sim$validationELFs, sim$validationResults$gates, file.path(out, "validation.html"), template = file.path(modulePath(sim), currentModule(sim), "pageTemplate.html"), title = P(sim)$pageTitle, subtitle = P(sim)$pageSubtitle, label = P(sim)$simLabel, - minHa = scoredMinHa(P(sim)), dpi = P(sim)$pageDpi, bias = sim$validationResults$bias, climate = sim$validationResults$climate) + minHa = scoredMinHa(P(sim)), dpi = P(sim)$pageDpi, bias = sim$validationResults$bias, climate = sim$validationResults$climate, slopeSplit = sim$validationResults$slopeSplit) }, warning(paste("Undefined event type: '", current(sim)[1, "eventType", with = FALSE], "' in module '", current(sim)[1, "moduleName", with = FALSE], "'", sep = "")) diff --git a/pageTemplate.html b/pageTemplate.html index 0cacbc8..f7a1cd3 100644 --- a/pageTemplate.html +++ b/pageTemplate.html @@ -153,6 +153,28 @@

Climate response does annual area respond to climate as observed does

Slopes are in the units of the response: the change in log annual area burned per standard deviation of the ELF's climate covariate over the scored years (higher covariate is drier). Simulated slope: the median over runs. Difference: simulated minus observed, per run, then the median over runs; 0 is the observed response. Driest 10%: simulated over observed area in the years at or above the 90% quantile of the covariate; wetter half: the same for the years at or below its median; 1 is the observed response. Small numbers are the 95% range of single runs (the "all" row: the 2.5-97.5% range over ELFs; it has no simulated or observed slope); "obs N%": the share of runs below the observed. Area is the area in fires of the escape size or more, as in the area row above.

+
+

Climate slope by channel which of ignitions, escape rate and fire size carries the difference? click a column to sort

+
+ + + + + + + + + + + + + + +
+
+

The slope of log annual area burned on the climate covariate is the sum of three slopes: of log ignitions, of log escape rate (escapes per ignition) and of log mean escaped-fire size (area per escape), per standard deviation of the covariate. The three differences (simulated minus observed, per run, then the median over runs) add up to the total slope difference in the table above. Only years with an ignition, an escape and some area enter, for the observed record and for each run. Small numbers are the 95% range of single runs (the "all" row: the 2.5-97.5% range over ELFs); "obs N%": the share of runs below the observed.

+
+

Observed rank is the observed record a plausible draw from the runs?

@@ -189,6 +211,7 @@

By ELF area by year, then the four distributions

const ROWS = /*ROWS*/[]; const BIAS = /*BIAS*/[]; const CLIMATE = /*CLIMATE*/[]; +const SLOPESPLIT = /*SLOPESPLIT*/[]; const METRICS = [ ["areaByYear", "Area by year"], ["annualArea", "Annual area"], ["fireSizes", "Fire sizes"], ["ignitions", "Ignitions"], ["escapes", "Escapes"]]; @@ -290,6 +313,7 @@

By ELF area by year, then the four distributions

sortableTable("bias", "biasRows", "b", BIAS, r => ratioCells(r, ["area", "top10", "ignitions", "escapes", "areaMean", "ignitionsMean", "escapesMean"]) + ["areaDiff", "ignitionsDiff", "escapesDiff"].map(k => plainCell(r[k])).join("")); sortableTable("climate", "climateRows", "c", CLIMATE, r => ratioCells(r, ["simSlope"], NaN) + plainCell(r.obsSlope) + ratioCells(r, ["slope"], 0) + ratioCells(r, ["dry10", "wetHalf"])); +sortableTable("climateSplit", "climateSplitRows", "s", SLOPESPLIT, r => ["Ignitions", "EscapeRate", "Size"].map(m => ratioCells(r, ["simslope" + m], NaN) + plainCell(r["obsslope" + m]) + ratioCells(r, ["slope" + m], 0)).join("")); function setMetric(m) { metric = m; const src = IMG["metric_" + m]; diff --git a/tests/testthat/helper-source.R b/tests/testthat/helper-source.R index 59614fe..bed3532 100644 --- a/tests/testthat/helper-source.R +++ b/tests/testthat/helper-source.R @@ -30,6 +30,16 @@ toyElf <- function(name = "toy", perfect = FALSE, seed = 1, scored = seq(1986L, fitAreaHa = sum(area), totalAreaHa = sum(area) * 1.2)) } +## A toy ELF with a known climate response: observed area = exp(5 + b z) in each scored year; run r is `f(r)` times a response `b * s` (slope factor s) +climToy <- function(b = 0.5, s = 1, f = function(r) 1, nRuns = 5L, years = 1986:2024) { + z <- as.numeric(scale(sin(seq_along(years) * 1.7) + seq_along(years) / 40)) # distinct values: no ties at the quantiles + obs <- exp(5 + b * z) + sim <- do.call(rbind, lapply(seq_len(nRuns), function(r) data.frame(year = years, run = r, ignitions = 1, escapes = 1, area50 = f(r) * exp(5 + b * s * z)))) + list(elf = "clim", simYears = sim, simSizes = data.frame(year = years, run = 1L, ha = 100), + obsYears = data.frame(year = years, ignitions = 1, escapes = 1, area50 = obs), obsSizes = data.frame(year = years, ha = 100), + covariate = data.frame(year = years, value = 100 + 20 * z), z = z, obs = obs) +} + ## Run the module from a temporary root: `params` are its parameters, outputs go to /outputs. `.env` is where the options are undone. runModule <- function(root, params, inputPath = root, .env = parent.frame()) { mp <- file.path(root, "modules"); dir.create(mp, showWarnings = FALSE) diff --git a/tests/testthat/test-climate.R b/tests/testthat/test-climate.R index 5d3bb56..8d8e51a 100644 --- a/tests/testthat/test-climate.R +++ b/tests/testthat/test-climate.R @@ -1,15 +1,5 @@ ## scoreClimateResponse(): slope, dry10 and wetHalf of the simulated annual area over the observed. Toy ELF: see helper-source.R. -## A toy ELF with a known climate response: observed area = exp(5 + b z) in each scored year; run r is `f(r)` times a response `b * s` (slope factor s) -climToy <- function(b = 0.5, s = 1, f = function(r) 1, nRuns = 5L, years = 1986:2024) { - z <- as.numeric(scale(sin(seq_along(years) * 1.7) + seq_along(years) / 40)) # distinct values: no ties at the quantiles - obs <- exp(5 + b * z) - sim <- do.call(rbind, lapply(seq_len(nRuns), function(r) data.frame(year = years, run = r, ignitions = 1, escapes = 1, area50 = f(r) * exp(5 + b * s * z)))) - list(elf = "clim", simYears = sim, simSizes = data.frame(year = years, run = 1L, ha = 100), - obsYears = data.frame(year = years, ignitions = 1, escapes = 1, area50 = obs), obsSizes = data.frame(year = years, ha = 100), - covariate = data.frame(year = years, value = 100 + 20 * z), z = z, obs = obs) -} - test_that("a simulator with the observed response has a slope difference of 0 and area ratios of 1; a doubled slope has a difference of b", { e <- climToy() cr <- scoreClimateResponse(e) @@ -102,7 +92,7 @@ test_that("runWave1() returns the climate table and its rows in results; the pag e <- toyElf(seed = 3, name = "a-x"); e2 <- toyElf(seed = 5, name = "b-y") r <- runWave1(list(e, e2), minHa = toyMinHa, nBoot = 10, nNull = 5, nPerm = 20) expect_equal(sort(unique(r$climate$ELF)), c("a-x", "all", "b-y")) - expect_equal(sum(r$results$test == "C"), 9L); expect_equal(unique(r$results$measure[r$results$test == "C" & r$results$null == "slope"]), "difference") + expect_equal(sum(r$results$test == "C" & r$results$null %in% names(climateMetrics)), 9L); expect_equal(unique(r$results$measure[r$results$test == "C" & r$results$null == "slope"]), "difference") g <- do.call(rbind, lapply(list(e, e2), function(x) cbind(ELF = x$elf, runGates(x, nBoot = 20)))) f <- tempfile(fileext = ".html") buildValidationPage(list(e, e2), g, f, testthat::test_path("..", "..", "pageTemplate.html"), minHa = toyMinHa, dpi = 30, bias = r$bias, climate = r$climate) diff --git a/tests/testthat/test-skill.R b/tests/testthat/test-skill.R index e537a6c..49bff9b 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", "perELF", "flagged")) + expect_named(out, c("results", "gates", "bias", "climate", "slopeSplit", "perELF", "flagged")) expect_equal(out$flagged, "c") expect_equal(nrow(out$gates), 18) r <- out$results diff --git a/tests/testthat/test-slopeSplit.R b/tests/testthat/test-slopeSplit.R new file mode 100644 index 0000000..e3dca63 --- /dev/null +++ b/tests/testthat/test-slopeSplit.R @@ -0,0 +1,75 @@ +## scoreSlopeSplit(): the climate slope split into the slopes of log ignitions, log escape rate and log mean escaped-fire size. Toy ELF: climToy() of helper-source.R. + +## Observed: 100 ignitions every year, escapes = 20 exp(0.3 z), 200 ha per escape. A run has the slopes `sl = c(ignitions, escape rate, size)` (log units per sd of z). +splitToy <- function(sl = c(0, 0.3, 0), obsSl = c(0, 0.3, 0), nRuns = 3L) { + e <- climToy(nRuns = nRuns); z <- e$z + rec <- function(s) { ign <- 100 * exp(s[1] * z); esc <- ign * 0.2 * exp(s[2] * z); data.frame(ignitions = ign, escapes = esc, area50 = esc * 200 * exp(s[3] * z)) } + e$obsYears[, c("ignitions", "escapes", "area50")] <- rec(obsSl) + e$simYears[, c("ignitions", "escapes", "area50")] <- do.call(rbind, rep(list(rec(sl)), nRuns)) + e +} +parts <- c("slopeIgnitions", "slopeEscapeRate", "slopeSize") + +test_that("a toy where only the escape rate responds to climate: the escape component carries the whole difference, the others are 0", { + ss <- scoreSlopeSplit(splitToy(sl = c(0, 0.1, 0), obsSl = c(0, 0.3, 0))) + expect_equal(ss$metric, parts) + expect_equal(ss$observed, c(0, 0.3, 0)); expect_equal(ss$simMedian, c(0, 0.1, 0)); expect_equal(ss$ratio, c(0, -0.2, 0)) + expect_equal(c(ss$runLo[2], ss$runHi[2]), c(-0.2, -0.2)); expect_equal(ss$obsRank[2], 1) # every run's escape slope is below the observed + expect_equal(unique(ss$nRuns), 3L); expect_equal(unique(ss$nYears), 39L) +}) + +test_that("the three parts add up to the total slope, observed, simulated and as differences", { + e <- splitToy(sl = c(0.2, -0.1, 0.15), obsSl = c(0.05, 0.3, 0.1), nRuns = 1L) + ss <- scoreSlopeSplit(e); cr <- scoreClimateResponse(e) + expect_equal(sum(ss$observed), cr$observed[1]); expect_equal(sum(ss$simMedian), cr$simMedian[1]); expect_equal(sum(ss$ratio), cr$ratio[1]) + expect_equal(ss$ratio, c(0.15, -0.4, 0.05)) +}) + +test_that("years without an escape are left out of all three parts, and the parts still add up to the total slope on the same years", { + e <- splitToy(sl = c(0.2, -0.1, 0.15), obsSl = c(0.05, 0.3, 0.1), nRuns = 1L) + e$simYears$ignitions <- e$simYears$ignitions * exp(0.3 * sin(3 * seq_len(nrow(e$simYears)))) # noise, so that dropping a year changes the slope + before <- scoreSlopeSplit(e)$simMedian + gone <- e$simYears$year %in% c(1990, 2000, 2010) + e$simYears$escapes[gone] <- 0; e$simYears$area50[gone] <- 0 # the run has no escape (and no area) in these years + ss <- scoreSlopeSplit(e); cr <- scoreClimateResponse(e) + expect_equal(sum(ss$simMedian), cr$simMedian[1]); expect_equal(sum(ss$ratio), cr$ratio[1]) + expect_true(all(is.finite(ss$ratio))) + ## and not as if the years had been present + expect_false(isTRUE(all.equal(ss$simMedian, before))) + e$simYears$escapes[e$simYears$year > 1987] <- 0; e$simYears$area50[e$simYears$year > 1987] <- 0 # fewer than 3 years with an escape: NA, not an error + expect_true(all(is.na(scoreSlopeSplit(e)$simMedian))) +}) + +test_that("pooled: the median of the ELF differences with their 2.5-97.5% range over ELFs; the rows are in results as test C with measure difference", { + a <- splitToy(sl = c(0, 0.4, 0)); a$elf <- "a"; b <- splitToy(sl = c(0, 0.5, 0)); b$elf <- "b"; c3 <- splitToy(sl = c(0, 0.6, 0)); c3$elf <- "c" # escape differences 0.1, 0.2, 0.3 + st <- slopeSplitTable(list(a, b, c3)) + p <- st[st$level == "pooled" & st$metric == "slopeEscapeRate", ] + expect_equal(c(p$ratio, p$elfLo, p$elfHi, p$nELF), c(0.2, unname(quantile(c(0.1, 0.2, 0.3), c(0.025, 0.975))), 3)) + expect_equal(st$ratio[st$level == "pooled" & st$metric != "slopeEscapeRate"], c(0, 0)) + rr <- slopeSplitResultRows(st) + expect_equal(unique(rr$test), "C"); expect_equal(unique(rr$null), parts); expect_equal(unique(rr$measure), "difference"); expect_equal(nrow(rr), 12L) + expect_equal(rr$value[rr$level == "pooled" & rr$null == "slopeEscapeRate"], 0.2); expect_equal(rr$hi[rr$level == "pooled" & rr$null == "slopeEscapeRate"], p$elfHi) + expect_null(slopeSplitTable(list({ d <- a; d$covariate <- NULL; d }))); expect_null(slopeSplitResultRows(NULL)) + pg <- slopeSplitPageRows(st) + expect_equal(pg[[1]]$elf, "all: median of ELFs"); expect_equal(pg[[1]]$slopeEscapeRate[1], 0.2); expect_true(all(is.na(pg[[1]]$simslopeEscapeRate))) + expect_equal(pg[[2]]$obsslopeEscapeRate, 0.3); expect_equal(pg[[2]]$simslopeEscapeRate[1], 0.4); expect_equal(pg[[2]]$slopeEscapeRate[1], 0.1) +}) + +test_that("runWave1() returns the split and its rows in results; the page has the table with a note that the parts add up", { + skip_if_not_installed("jsonlite") + e <- toyElf(seed = 3, name = "a-x"); e2 <- toyElf(seed = 5, name = "b-y") + r <- runWave1(list(e, e2), minHa = toyMinHa, nBoot = 10, nNull = 5, nPerm = 20) + expect_equal(sort(unique(r$slopeSplit$ELF)), c("a-x", "all", "b-y")) + expect_equal(sum(r$results$test == "C" & r$results$null %in% parts), 9L); expect_equal(unique(r$results$measure[r$results$null %in% parts]), "difference") + d <- r$slopeSplit[r$slopeSplit$ELF == "a-x", ]; tot <- r$climate[r$climate$ELF == "a-x" & r$climate$metric == "slope", ] + expect_equal(sum(d$observed), tot$observed, tolerance = 1e-8) # toy years with area have ignitions and escapes + g <- do.call(rbind, lapply(list(e, e2), function(x) cbind(ELF = x$elf, runGates(x, nBoot = 20)))) + f <- tempfile(fileext = ".html") + buildValidationPage(list(e, e2), g, f, testthat::test_path("..", "..", "pageTemplate.html"), minHa = toyMinHa, dpi = 30, bias = r$bias, climate = r$climate, slopeSplit = r$slopeSplit) + h <- paste(readLines(f, warn = FALSE), collapse = "\n") + expect_false(grepl("/*SLOPESPLIT*/", h, fixed = TRUE)); expect_match(h, "const SLOPESPLIT = [{", fixed = TRUE) + expect_match(h, "id=\"climateSplitRows\"", fixed = TRUE); expect_match(h, "data-s=\"slopeEscapeRate\"", fixed = TRUE) + expect_match(h, "add up to the total slope difference", fixed = TRUE) + expect_lt(regexpr("id=\"climateRows\"", h), regexpr("id=\"climateSplitRows\"", h)) + expect_lt(regexpr("data-s=\"slopeIgnitions\"", h), regexpr("data-s=\"slopeEscapeRate\"", h)); expect_lt(regexpr("data-s=\"slopeEscapeRate\"", h), regexpr("data-s=\"slopeSize\"", h)) +})