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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
5 changes: 4 additions & 1 deletion R/buildPage.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
93 changes: 84 additions & 9 deletions R/climateResponse.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ climateMetrics <- c(slope = "climate slope", dry10 = "driest 10% of years", wetH
climateKind <- c(slope = "difference", dry10 = "ratio", wetHalf = "ratio")
climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- names(climateKind)

## 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
Expand All @@ -24,13 +35,11 @@ climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- na
#' @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) vapply(names(climateKind), function(m) if (climateKind[[m]] == "difference") v[[m]] - obs[[m]] else zeroSafeRatio(v[[m]], obs[[m]]), 0)
runs <- lapply(split(elf$simYears, elf$simYears$run), function(r) values(r$area50[match(years, r$year)]))
Expand All @@ -45,10 +54,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)
Expand Down Expand Up @@ -79,3 +90,67 @@ 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 `<m>` the difference cell, `sim<m>` the simulated slope cell (no pooled one), `obs<m>` 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$ref <- as.list(c(stats::setNames(rep(0, length(slopeSplitMetrics)), names(slopeSplitMetrics)), # what each cell is compared with, for the page's shading: differences with 0, simulated slopes with nothing
stats::setNames(rep(NA_real_, length(slopeSplitMetrics)), paste0("sim", names(slopeSplitMetrics)))))
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, ])))
}
7 changes: 4 additions & 3 deletions R/runWave1.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading