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)

* 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.

* 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()`).
Expand Down
9 changes: 7 additions & 2 deletions R/bootstrap.R
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ bootstrapMean <- function(d, nBoot = 999, seed = 1) {
data.frame(value = b$est, lo = b$lo, hi = b$hi, nELF = length(unique(d$ELF)), nUnits = nrow(d))
}

## Spearman correlation of two vectors; NA with fewer than 3 pairs or no spread in either (the pairs with an NA are left out)
rankCor <- function(a, b) {
ok <- is.finite(a) & is.finite(b); a <- a[ok]; b <- b[ok]
if (length(a) > 2 && stats::sd(a) > 0 && stats::sd(b) > 0) stats::cor(a, b, method = "spearman") else NA_real_
}

#' Pooled Spearman of the model and of an index, and the paired difference, with a bootstrap interval
#'
#' The statistic is the median over ELFs of the ELF's Spearman correlations. Model and index are resampled on the same
Expand All @@ -55,9 +61,8 @@ bootstrapMean <- function(d, nBoot = 999, seed = 1) {
#' @param d `data.frame(ELF, year, obs, simMedian, ref)`. @inheritParams bootstrapPooled
#' @return `data.frame(measure = c("rhoModel", "rhoIndex", "rhoDiff"), value, lo, hi)`.
bootstrapRankDiff <- function(d, nBoot = 999, seed = 1) {
rho <- function(a, b) if (length(a) > 2 && stats::sd(a) > 0 && stats::sd(b) > 0) stats::cor(a, b, method = "spearman") else NA_real_
stat <- function(df) {
r <- do.call(rbind, lapply(split(df, df$ELF), function(x) c(rho(x$obs, x$simMedian), rho(x$obs, x$ref))))
r <- do.call(rbind, lapply(split(df, df$ELF), function(x) c(rankCor(x$obs, x$simMedian), rankCor(x$obs, x$ref))))
c(stats::median(r[, 1], na.rm = TRUE), stats::median(r[, 2], na.rm = TRUE), stats::median(r[, 1] - r[, 2], na.rm = TRUE))
}
b <- bootstrapPooled(d[is.finite(d$ref), , drop = FALSE], stat, nBoot, seed)
Expand Down
4 changes: 3 additions & 1 deletion R/buildPage.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ ratioCell <- function(ratio, lo, hi, obsRank) round(c(ratio, lo, hi, obsRank), 3
#' @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 climatePooled The `climatePooled` table of [runWave1()] ([climatePooledYears()]): the pooled ELF-years row of the climate table; `NULL`: none.
#' @param results The `results` table of [runWave1()], for the table of S6 and S7 (where ignitions and burns occur); `NULL` or without S6/S7 rows: no such table.
#' @param results The `results` table of [runWave1()], for the table of S6 and S7 (where ignitions and burns occur) and the table of S8 and S9 (what a fire does once it has escaped, in-sample runs); `NULL` or without such rows: no such table.
#' @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`.
Expand Down Expand Up @@ -45,12 +45,14 @@ buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast v
climateRows <- climatePageRows(climate, climatePooled)
slopeSplitRows <- slopeSplitPageRows(slopeSplit)
locationRows <- if (!is.null(results)) locationPageRows(results) else list()
escapeRows <- if (!is.null(results)) escapePageRows(results) else list()
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("/*LOCATION*/[]", as.character(jsonlite::toJSON(locationRows, auto_unbox = TRUE, na = "null")))
fill("/*ESCAPE*/[]", as.character(jsonlite::toJSON(escapeRows, 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)
Expand Down
107 changes: 107 additions & 0 deletions R/escapeTests.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
## Tests S8 and S9, for in-sample hindcasts: what a fire does once it has escaped.
## An in-sample run spreads the OBSERVED escapes from their real start points and years, so S7's whole-ELF AUC is high only because the fires start where the observed ones did (S7 is not scored there).
## S8 asks how big each seeded fire gets, S9 what shape it takes. Nothing here knows a simulator: the adapter (readFireSenseHindcast.R) builds the plain tables below.
## An ELF input carries `inSample = TRUE` and, in `location`, `burn$grid` and `burn$gridCell` (the grid and the grid cell of each scored cell 1..nCells; see the top of spatialTests.R) and
## seeded: `fires` (`data.frame(year, start, obsHa)`: one row per observed escape that the run seeded, `start` its start as a grid cell, `obsHa` the observed size of the whole fire),
## `sizes` (`data.frame(year, run, start, ha)`: the final size of the fire that grew from each seeded start, in every run),
## `obsCells` (`data.frame(year, start, cell)`: the scored cells the observed fire burned).

## Squared distance of each cell of `xy` (list x, y) to `centre` (c(x, y))
sqDist <- function(xy, centre) (xy$x - centre[1])^2 + (xy$y - centre[2])^2

#' The `k` cells nearest to a centre: the circle that holds `k` cells
#'
#' @param xy `list(x, y)`, the coordinates of the candidate cells ([gridXY()]). @param centre `c(x, y)`. @param k Cells wanted.
#' @return Indices into `xy` of the `k` nearest cells (fewer if there are fewer); ties at the edge go to the lower index, so the circle always holds exactly `k`.
circleCells <- function(xy, centre, k) {
d <- sqDist(xy, centre)
k <- min(k, length(d))
cand <- which(d <= sort.int(d, partial = k)[k])
if (length(cand) > k) cand <- cand[order(d[cand], cand)][seq_len(k)]
cand
}

#' S8: size given escape
#'
#' For each observed escape the run seeded: the final size of the fire that grew from it, the median over runs, against the fire's observed size. Per fire `log2ratio` is `log2(simMedian / obsHa)`.
#' `runs` has each run's own Spearman correlation (`rho`) and median `log2ratio` over the fires, for the single-run range.
#' @param elf ELF input list with `location$seeded` (see the top of this file). @return `NULL` without it, else `list(scores, runs)`: `scores` has `year, start, obsHa, simMedian, log2ratio`, `runs` has `run, rho, log2ratio`.
scoreS8 <- function(elf) {
sd <- elf$location$seeded
if (is.null(sd)) return(NULL)
f <- sd$fires[sd$fires$year %in% scoredYears(elf), c("year", "start", "obsHa"), drop = FALSE]
key <- paste(f$year, f$start); z <- sd$sizes; zkey <- paste(z$year, z$start)
f$simMedian <- as.numeric(tapply(z$ha, zkey, stats::median)[key])
f$log2ratio <- log2(f$simMedian / f$obsHa)
f <- f[is.finite(f$log2ratio), , drop = FALSE]; key <- paste(f$year, f$start)
runs <- do.call(rbind, lapply(split(z, z$run), function(r) {
ha <- r$ha[match(key, paste(r$year, r$start))]
data.frame(run = r$run[1], rho = rankCor(f$obsHa, ha), log2ratio = stats::median(log2(ha / f$obsHa), na.rm = TRUE)) }))
list(scores = f, runs = runs)
}

#' S9: shape given escape
#'
#' For each seeded observed fire with `N` observed cells: the circle centred on its start that holds `2N` scored cells ([circleCells()]). In the circle the positives are the cells the fire burned, the negatives the others;
#' each cell is scored by the share of runs that burned it, and the fire's AUC is [aucOf()] (ties count half). Observed cells outside the circle (an elongated fire) are not counted; `shareInside` is the share of the fire's cells that are inside.
#' The baseline, `aucDist`, scores each cell of the circle by its closeness to the start (minus its distance) and takes the same AUC: how much of the model's AUC is just "near the start". The headline is the model's AUC minus the baseline's (`aucDiff`).
#' `runs` has each run's AUC per fire (the cell is the run's 0/1 map), summarised as the median over fires per run, `auc` and `aucDiff`, for the single-run range.
#' @param elf ELF input list with `location$seeded` and `location$burn` (see the top of this file). @return `NULL` without them, else `list(scores, runs)`: `scores` has `year, start, nObs, nCircle, shareInside, auc, aucDist`, `runs` has `run, auc, aucDiff`.
scoreS9 <- function(elf) {
sd <- elf$location$seeded; b <- elf$location$burn
if (is.null(sd) || is.null(b)) return(NULL)
xy <- gridXY(b$grid, b$gridCell); nRuns <- b$nRuns
f <- sd$fires[sd$fires$year %in% intersect(scoredYears(elf), as.integer(names(b$sim))), c("year", "start"), drop = FALSE]
burned <- lapply(stats::setNames(unique(f$year), unique(f$year)), function(y) { s <- b$sim[[as.character(y)]]; list(p = tabulate(s$cell, b$nCells) / nRuns, byRun = split(s$cell, factor(s$run, seq_len(nRuns)))) })
one <- lapply(seq_len(nrow(f)), function(i) {
oc <- sd$obsCells$cell[sd$obsCells$year == f$year[i] & sd$obsCells$start == f$start[i]]
if (!length(oc)) return(NULL)
s0 <- gridXY(b$grid, f$start[i]); circ <- circleCells(xy, c(s0$x, s0$y), 2L * length(oc)); o <- as.integer(circ %in% oc); by <- burned[[as.character(f$year[i])]]
aucDist <- aucOf(-sqDist(list(x = xy$x[circ], y = xy$y[circ]), c(s0$x, s0$y)), o) # the baseline: closer to the start is more likely burned
list(row = data.frame(year = f$year[i], start = f$start[i], nObs = length(oc), nCircle = length(circ), shareInside = sum(o) / length(oc), auc = aucOf(by$p[circ], o), aucDist = aucDist),
runAuc = vapply(by$byRun, function(cells) aucOf(as.integer(circ %in% cells), o), 0), dist = aucDist)
})
one <- Filter(Negate(is.null), one)
runAuc <- do.call(cbind, lapply(one, `[[`, "runAuc")); runDiff <- sweep(runAuc, 2, vapply(one, `[[`, 0, "dist"))
list(scores = do.call(rbind, lapply(one, `[[`, "row")),
runs = data.frame(run = seq_len(nRuns), auc = apply(runAuc, 1, stats::median, na.rm = TRUE), aucDiff = apply(runDiff, 1, stats::median, na.rm = TRUE)))
}

## What each measure of S8 and S9 is on one ELF's fires (a table of `scores`)
escapeStats <- list(S8 = list(rho = function(x) rankCor(x$obsHa, x$simMedian), log2ratio = function(x) stats::median(x$log2ratio)),
S9 = list(aucDiff = function(x) stats::median(x$auc - x$aucDist, na.rm = TRUE), auc = function(x) stats::median(x$auc, na.rm = TRUE),
aucDist = function(x) stats::median(x$aucDist, na.rm = TRUE), shareInside = function(x) stats::median(x$shareInside)))

#' The `results` rows of S8 and S9
#'
#' Per ELF the measure on its fires, with the 2.5-97.5% range over single runs (`rho`, `log2ratio`, `auc`; the single runs' own values of `runs`), and `nFires`; pooled, the median over ELFs of the ELF values with a
#' bootstrap over ELFs and, within each, over fires ([bootstrapPooled()]).
#' @param scores,runs Named lists (`S8`, `S9`) of the tables of [scoreS8()] and [scoreS9()], each bound over ELFs with an `ELF` column; a test that is `NULL` has no rows. @param nBoot,seed Bootstrap.
#' @return `data.frame(test, null, level, ELF, measure, value, lo, hi, nELF, nUnits, verdict)`, `NULL` without either test.
escapeResultRows <- function(scores, runs, nBoot, seed) {
rows <- lapply(names(Filter(Negate(is.null), scores)), function(tst) {
d <- scores[[tst]]; st <- escapeStats[[tst]]; g <- split(d, d$ELF)
fin <- function(x) x[is.finite(x[[if (tst == "S8") "log2ratio" else "auc"]]), , drop = FALSE] # a fire with no AUC (no observed cell in its circle) is left out, as it has no score
g <- lapply(g, fin); d <- do.call(rbind, g)
p <- bootstrapPooled(d, function(df) vapply(st, function(f) stats::median(vapply(split(df, df$ELF), f, 0), na.rm = TRUE), 0), nBoot, seed)
pooled <- data.frame(level = "pooled", ELF = "all", measure = names(st), value = p$est, lo = p$lo, hi = p$hi, nELF = length(g), nUnits = nrow(d))
range <- function(r, m, i) if (m %in% names(r)) quantRange(r[[m]])[i] else NA_real_ # the single runs' range, where the measure has one
perE <- do.call(rbind, lapply(names(g), function(id) {
r <- runs[[tst]]; r <- r[r$ELF == id, ]
data.frame(level = "ELF", ELF = id, measure = names(st), value = vapply(st, function(f) f(g[[id]]), 0),
lo = vapply(names(st), range, 0, r = r, i = 1), hi = vapply(names(st), range, 0, r = r, i = 2), nELF = 1L, nUnits = nrow(g[[id]])) }))
vals <- rbind(pooled, perE)
n <- vals[!duplicated(vals[c("level", "ELF")]), ]; n$measure <- "nFires"; n$value <- n$nUnits; n$lo <- n$hi <- NA_real_
vals <- rbind(vals, n)
longRows(vals, tst, NA_character_, vals$measure, vals$value, vals$lo, vals$hi, nUnits = vals$nUnits)
})
if (length(rows)) do.call(rbind, rows)
}

## The rows of the page's "Given an escape" table: the pooled row, then one per ELF; cells are `c(value, low, high, NA)` ([ratioCell()]) of S8 rho and size log ratio, S9 AUC minus the distance-only AUC, the AUC, the distance-only AUC and the share of the fire inside the circle; `n8`, `n9` the fires
escapePageRows <- function(results) {
n <- function(z, tst) { r <- z[z$test == tst & z$measure == "nFires", ]; if (nrow(r)) r$value[1] }
pageRowsOf(results, c("S8", "S9"), function(label, z)
list(elf = label, rho = resultCell(z, "S8", "rho"), size = resultCell(z, "S8", "log2ratio"), n8 = n(z, "S8"), diff = resultCell(z, "S9", "aucDiff"), auc = resultCell(z, "S9", "auc"),
dist = resultCell(z, "S9", "aucDist"), inside = resultCell(z, "S9", "shareInside"), n9 = n(z, "S9")))
}
17 changes: 14 additions & 3 deletions R/ratioTable.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,21 @@ poolRatios <- function(x) {
nELF = nrow(x), nNonFinite = sum(!is.finite(x$ratio)), nYears = sum(x$nYears), obsRank = medFinite(x$obsRank))
}

## Rows of the long `results` table: `value`, `lo`, `hi` for the rows of `x` (`level`, `ELF`, `nELF`, `nYears`, `nRuns`); `nUnits` is the years of a pooled row, else the runs
longRows <- function(x, test, null, measure, value, lo, hi)
## Rows of the long `results` table: `value`, `lo`, `hi` for the rows of `x` (`level`, `ELF`, `nELF`, `nYears`, `nRuns`); `nUnits` is, unless given, the years of a pooled row, else the runs
longRows <- function(x, test, null, measure, value, lo, hi, nUnits = ifelse(x$level == "pooled", x$nYears, x$nRuns))
data.frame(test = test, null = null, level = x$level, ELF = x$ELF, measure = measure, value = value, lo = lo, hi = hi,
nELF = x$nELF, nUnits = ifelse(x$level == "pooled", x$nYears, x$nRuns), verdict = NA_character_)
nELF = x$nELF, nUnits = nUnits, verdict = NA_character_)

## One cell of a page table from the long `results` rows `z`: `ratioCell(value, lo, hi)` of the test and measure, NULL if there is none
resultCell <- function(z, tst, m) { r <- z[z$test == tst & z$measure == m, ]; if (nrow(r)) ratioCell(r$value[1], r$lo[1], r$hi[1], NA_real_) else NULL }

## The rows of a page table of the tests `tests`: the pooled row, then one per ELF; `rowOf(label, z)` makes a row from the results rows `z` of that label; none without rows of the tests
pageRowsOf <- function(results, tests, rowOf) {
x <- results[results$test %in% tests, ]
if (!nrow(x)) return(list())
c(list(rowOf("all: pooled", x[x$level == "pooled", ])),
lapply(unique(x$ELF[x$level == "ELF"]), function(id) rowOf(id, x[x$level == "ELF" & x$ELF == id, ])))
}

## A cell of the page's tables: `c(value, low, high, obsRank)`, low and high the range of single runs (ELF rows) or over ELFs (pooled); `value` is the ratio (or, for a difference, `x$ratio`)
rangeCell <- function(x, pooled) ratioCell(x$ratio, if (pooled) x$elfLo else x$runLo, if (pooled) x$elfHi else x$runHi, x$obsRank)
Loading
Loading