From 74ef53b82e1fc0aa328e945db997725e5c7cc563 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Tue, 1 Dec 2026 20:14:35 -0700 Subject: [PATCH 1/2] In-sample hindcasts: no S7; new S8 (size given escape) and S9 (shape given escape) S7's whole-ELF AUC is about 0.9 in a hindcast that spreads the observed escapes, only because the fires start where the observed ones did. It is no longer scored for such runs. S8 and S9 score what a fire does once it has escaped: its final size and its shape around its start. A run is detected as in-sample from fireSense_burnSummary.csv (every run starts the same fires). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 + R/bootstrap.R | 9 ++- R/buildPage.R | 4 +- R/escapeTests.R | 102 +++++++++++++++++++++++++ R/readFireSenseHindcast.R | 96 +++++++++++++++++++++--- R/runWave1.R | 14 ++-- R/spatialTests.R | 5 +- README.md | 1 + pageTemplate.html | 22 ++++++ tests/testthat/test-escapes.R | 137 ++++++++++++++++++++++++++++++++++ 10 files changed, 369 insertions(+), 23 deletions(-) create mode 100644 R/escapeTests.R create mode 100644 tests/testthat/test-escapes.R diff --git a/NEWS.md b/NEWS.md index 8af980e..7302e1c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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, `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()`). diff --git a/R/bootstrap.R b/R/bootstrap.R index ad29d64..1245235 100644 --- a/R/bootstrap.R +++ b/R/bootstrap.R @@ -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 @@ -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) diff --git a/R/buildPage.R b/R/buildPage.R index 935469c..57f7f5c 100644 --- a/R/buildPage.R +++ b/R/buildPage.R @@ -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`. @@ -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) diff --git a/R/escapeTests.R b/R/escapeTests.R new file mode 100644 index 0000000..ded358a --- /dev/null +++ b/R/escapeTests.R @@ -0,0 +1,102 @@ +## 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). + +#' 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 <- (xy$x - centre[1])^2 + (xy$y - centre[2])^2 + 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. +#' `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`, 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`, `runs` has `run, auc`. +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])]] + 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)), + runAuc = vapply(by$byRun, function(cells) aucOf(as.integer(circ %in% cells), o), 0)) + }) + one <- Filter(Negate(is.null), one) + runAuc <- do.call(cbind, lapply(one, `[[`, "runAuc")) + list(scores = do.call(rbind, lapply(one, `[[`, "row")), runs = data.frame(run = seq_len(nRuns), auc = apply(runAuc, 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(auc = function(x) stats::median(x$auc, 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)) + 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), function(m) if (m %in% names(r)) quantRange(r[[m]])[1] else NA_real_, 0), hi = vapply(names(st), function(m) if (m %in% names(r)) quantRange(r[[m]])[2] else NA_real_, 0), + 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_ + transform(rbind(vals, n), test = tst, null = NA_character_, verdict = NA_character_) + }) + if (length(rows)) { x <- do.call(rbind, rows); x[, c("test", "null", "level", "ELF", "measure", "value", "lo", "hi", "nELF", "nUnits", "verdict")] } +} + +## 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 and share of the fire inside the circle; `n8`, `n9` the fires +escapePageRows <- function(results) { + x <- results[results$test %in% c("S8", "S9"), ] + if (!nrow(x)) return(list()) + cell <- 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 } + n <- function(z, tst) { r <- z[z$test == tst & z$measure == "nFires", ]; if (nrow(r)) r$value[1] else NULL } + rowOf <- function(label, z) list(elf = label, rho = cell(z, "S8", "rho"), size = cell(z, "S8", "log2ratio"), n8 = n(z, "S8"), auc = cell(z, "S9", "auc"), inside = cell(z, "S9", "shareInside"), n9 = n(z, "S9")) + 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, ]))) +} diff --git a/R/readFireSenseHindcast.R b/R/readFireSenseHindcast.R index 0dd7c43..6b3c980 100644 --- a/R/readFireSenseHindcast.R +++ b/R/readFireSenseHindcast.R @@ -14,6 +14,10 @@ hindcastFinishedYears <- function(hindcastDir, elf, years = seq(1986L, 2021L, 5L years[vapply(years, function(y) all(vapply(sets, function(s) all(file.exists(file.path(hindcastDir, elf, y, s, need))), TRUE)), TRUE)] } +## The parameter set of the rows of a hindcast file (its `paramSet` column when it has one, else the set folder `s`) and the run (`set * 1000 + rep`) +hindcastSet <- function(x, s) if ("paramSet" %in% names(x)) as.integer(x$paramSet) else rep(as.integer(s), NROW(x)) +hindcastRun <- function(x, s) hindcastSet(x, s) * 1000L + x$rep + #' Simulated side: one row per run-year, and the simulated fire sizes #' #' Reads `hindcast_reps.csv` and `hindcast_sizes.csv` of every set. A run is a rep of a set (`run = set * 1000 + rep`). The set is the @@ -27,10 +31,8 @@ readHindcastSim <- function(hindcastDir, elf, years, sets = 1:5, minHa) { both <- lapply(years, function(y) lapply(sets, function(s) { d <- file.path(hindcastDir, elf, y, s) r <- fread0(file.path(d, "hindcast_reps.csv")); z <- fread0(file.path(d, "hindcast_sizes.csv")) - set <- function(x) if ("paramSet" %in% names(x)) as.integer(x$paramSet) else rep(as.integer(s), NROW(x)) - run <- function(x) set(x) * 1000L + x$rep - list(reps = data.frame(year = y, run = run(r), paramSet = set(r), ignitions = r$ignitions), - sizes = data.frame(year = rep(y, NROW(z)), run = if (NROW(z)) run(z) else integer(0), paramSet = if (NROW(z)) set(z) else integer(0), + list(reps = data.frame(year = y, run = hindcastRun(r, s), paramSet = hindcastSet(r, s), ignitions = r$ignitions), + sizes = data.frame(year = rep(y, NROW(z)), run = if (NROW(z)) hindcastRun(z, s) else integer(0), paramSet = if (NROW(z)) hindcastSet(z, s) else integer(0), ha = if (NROW(z)) z$ha else numeric(0))) })) flat <- unlist(both, recursive = FALSE) @@ -130,19 +132,24 @@ readHindcastObserved <- function(rec, hindcastDir, elf, scored, minHa) { escapeSizeHa = rec$escapeSizeHa, fireCauses = rec$fireCauses) } +## A raster's grid as the `grid` of the ELF input (see the top of R/spatialTests.R) +gridOf <- function(r) list(nrow = terra::nrow(r), ncol = terra::ncol(r), xmin = terra::xmin(r), xmax = terra::xmax(r), ymin = terra::ymin(r), ymax = terra::ymax(r)) +## For each cell of a grid of `n` cells, its number among the scored cells `scoredCells` (0 where it is not scored) +toScoredIndex <- function(scoredCells, n) { i <- integer(n); i[scoredCells] <- seq_along(scoredCells); i } + #' Where the hindcast ignited and burned, in the `location` of the ELF input (S6, S7) #' #' Per scored year, over every set: the runs' `hindcast_ignitionProb_rep*.tif` and `hindcast_burnID_rep*.tif` (a cell burned where the burn ID is not NA) and the year's own #' `hindcast_observedPoints.gpkg` and `hindcast_observedPolys.gpkg`; the other years' observed points and polygons come from the record `rec` (as [readHindcastObserved()]). Each year is reduced as #' it is read ([ignitionYear()], the burned cells of each run), so no stack of maps is held. Burns are on the cells of `core` (the burnable core, as the other tests count them). #' @param rec [observedRecord()]. @param hindcastDir,elf,scored,sets As [readHindcastSim()]. @param core [hindcastCore()]. -#' @return `list(ign, burn)`, see the top of `R/spatialTests.R`; `NULL` when the hindcast has no ignition maps. +#' @return `list(ign, burn)`, see the top of `R/spatialTests.R` (`burn` also has `grid` and `gridCell`, the grid and the grid cell of each scored cell); `NULL` when the hindcast has no ignition maps. readHindcastLocation <- function(rec, hindcastDir, elf, scored, sets, core) { dirs <- function(y) file.path(hindcastDir, elf, y, sets) maps <- function(y, what) unlist(lapply(dirs(y), function(d) Sys.glob(file.path(d, paste0("hindcast_", what, "_rep*.tif"))))) if (!length(maps(scored[1], "ignitionProb"))) return(NULL) template <- terra::rast(maps(scored[1], "ignitionProb")[1]) - grid <- list(nrow = terra::nrow(template), ncol = terra::ncol(template), xmin = terra::xmin(template), xmax = terra::xmax(template), ymin = terra::ymin(template), ymax = terra::ymax(template)) + grid <- gridOf(template) own <- function(y, f) { x <- file.path(hindcastDir, elf, y, sets[1], f); if (file.exists(x)) x } years <- sort(unique(c(as.integer(names(rec$polys)), scored))) asVect <- function(y, what, f) { # the hindcast's own file for a scored year, else the record's @@ -150,7 +157,7 @@ readHindcastLocation <- function(rec, hindcastDir, elf, scored, sets, core) { if (!is.null(x)) terra::vect(x) else if (!is.null(rec[[what]][[as.character(y)]])) terra::unwrap(rec[[what]][[as.character(y)]]) } pointsOf <- lapply(stats::setNames(years, years), function(y) { v <- asVect(y, "points", "hindcast_observedPoints.gpkg"); if (!is.null(v) && NROW(v)) { cl <- terra::cellFromXY(template, terra::crds(v)); cl[!is.na(cl)] } else integer(0) }) - scoredCells <- which(!is.na(terra::values(core)[, 1])); toScored <- integer(terra::ncell(core)); toScored[scoredCells] <- seq_along(scoredCells) + scoredCells <- which(!is.na(terra::values(core)[, 1])); toScored <- toScoredIndex(scoredCells, terra::ncell(core)) burnedBy <- function(v) { if (is.null(v) || !NROW(v)) return(integer(0)); b <- terra::rasterize(v, core, field = 1, background = NA); i <- toScored[which(!is.na(terra::values(b)[, 1]))]; i[i > 0] } obsBurn <- lapply(stats::setNames(years, years), function(y) burnedBy(asVect(y, "polys", "hindcast_observedPolys.gpkg"))) perYear <- lapply(stats::setNames(scored, scored), function(y) { @@ -160,7 +167,68 @@ readHindcastLocation <- function(rec, hindcastDir, elf, scored, sets, core) { list(ign = ign, burn = burn, nRuns = length(ids)) }) list(ign = list(grid = grid, points = pointsOf, sim = lapply(perYear, `[[`, "ign")), - burn = list(nCells = length(scoredCells), nRuns = perYear[[1]]$nRuns, obs = obsBurn, sim = lapply(perYear, `[[`, "burn"))) + burn = list(nCells = length(scoredCells), nRuns = perYear[[1]]$nRuns, obs = obsBurn, sim = lapply(perYear, `[[`, "burn"), grid = grid, gridCell = scoredCells)) +} + +#' Where each simulated fire started +#' +#' `fireSense_burnSummary.csv` of every set has one row per fire: its start cell `igLoc` (a cell of the hindcast grid), its time `year` (year + 0.001 x the rep's index, the `time` of `hindcast_reps.csv`) and its size. +#' The fires of a rep are in the order of `fire_id` in `hindcast_sizes.csv` and of the values of that rep's `hindcast_burnID_rep*.tif`; the sizes of the two files are compared, and a set whose fires do not match stops the read. +#' @param hindcastDir,elf,years,sets As [readHindcastSim()]. @return `data.frame(year, run, fire, start, ha)`, `run` as in [readHindcastSim()]; `NULL` when no set has the file. +readHindcastStarts <- function(hindcastDir, elf, years, sets = 1:5) { + out <- lapply(years, function(y) lapply(sets, function(s) { + d <- file.path(hindcastDir, elf, y, s) + bs <- fread0(file.path(d, "fireSense_burnSummary.csv")); r <- fread0(file.path(d, "hindcast_reps.csv")); z <- fread0(file.path(d, "hindcast_sizes.csv")) + if (is.null(bs) || is.null(r) || is.null(z) || !NROW(bs)) return(NULL) # a year without a fire has a header only + t0 <- round(bs$year * 1000); i <- match(t0, round(r$time * 1000)) + if (anyNA(i)) stop("fireSense_burnSummary.csv of ", d, " has a time that no rep of hindcast_reps.csv has") + x <- data.frame(year = y, run = hindcastRun(r, s)[i], fire = stats::ave(seq_along(t0), t0, FUN = seq_along), start = bs$igLoc, ha = bs$areaBurnedHa) + zz <- data.frame(run = hindcastRun(z, s), fire = z$fire_id, ha = z$ha) + j <- match(paste(x$run, x$fire), paste(zz$run, zz$fire)) + if (anyNA(j) || nrow(zz) != nrow(x) || !isTRUE(all.equal(zz$ha[j], x$ha))) stop("the fires of fireSense_burnSummary.csv and hindcast_sizes.csv of ", d, " do not match, so a fire cannot be tied to its start") + x + })) + out <- Filter(Negate(is.null), unlist(out, recursive = FALSE)) + if (length(out)) do.call(rbind, out) +} + +#' Is a hindcast in-sample: does it spread the observed escapes? +#' +#' An in-sample hindcast (`FS_HC_IGNITIONS=observedEscapes`) seeds the observed escapes, so every run of a year starts the same fires, from the same cells. The hindcast's files record no setting for it (only the folder name does), so it is read from the data: +#' TRUE when, in every year with a fire, every run of the year started the same fires in the same order, and there are two runs or more. +#' @param starts [readHindcastStarts()]. @param simYears The `simYears` of [readHindcastSim()] (the runs of each year, with or without a fire). +hindcastInSample <- function(starts, simYears) { + if (is.null(starts) || !nrow(starts) || length(unique(simYears$run)) < 2L) return(FALSE) + all(vapply(split(starts, starts$year), function(z) { + seqs <- tapply(z$start[order(z$fire)], z$run[order(z$fire)], paste, collapse = ",") + length(seqs) == sum(simYears$year == z$year[1]) && length(unique(seqs)) == 1L + }, TRUE)) +} + +#' The seeded observed escapes: S8 and S9's input +#' +#' Each distinct start of `starts` is an observed escape that the run seeded. Its observed fire is the polygon of the year's `hindcast_observedPolys.gpkg` that holds the start cell (a start in no polygon is dropped, and counted in a message); its whole +#' extent, rasterized on the burnable cells (`flammable`, core and buffer, as the simulated fire spreads), gives the observed size, and the cells of it that are scored (`gridCell`) the observed burned cells. +#' @param starts [readHindcastStarts()]. @param hindcastDir,elf,scored,sets As [readHindcastLocation()]. @param flammable [hindcastFlammable()]. @param gridCell `location$burn$gridCell`. +#' @return `list(fires, sizes, obsCells)`, see the top of `R/escapeTests.R`; `NULL` when no start is in a polygon. +readHindcastSeeded <- function(starts, hindcastDir, elf, scored, sets, flammable, gridCell) { + toScored <- toScoredIndex(gridCell, terra::ncell(flammable)); cellHa <- prod(terra::res(flammable)) / 1e4 + one <- lapply(scored, function(y) { + st <- unique(starts$start[starts$year == y]); f <- file.path(hindcastDir, elf, y, sets[1], "hindcast_observedPolys.gpkg") + if (!length(st) || !file.exists(f)) return(NULL) + v <- terra::vect(f); v$idx <- seq_len(NROW(v)) + id <- terra::values(terra::rasterize(v, flammable, field = "idx", background = NA))[, 1] + k <- id[st] + list(fires = data.frame(year = y, start = st[!is.na(k)], obsHa = vapply(k[!is.na(k)], function(p) sum(id == p, na.rm = TRUE) * cellHa, 0)), + obsCells = do.call(rbind, lapply(which(!is.na(k)), function(j) { i <- toScored[which(id == k[j])]; data.frame(year = y, start = st[j], cell = i[i > 0]) })), + dropped = sum(is.na(k))) + }) + one <- Filter(Negate(is.null), one) + if (!length(one)) return(NULL) + if (sum(vapply(one, `[[`, 0, "dropped"))) message(elf, ": ", sum(vapply(one, `[[`, 0, "dropped")), " seeded escapes start in no observed polygon and are not scored in S8 and S9") + fires <- do.call(rbind, lapply(one, `[[`, "fires")) + list(fires = fires, obsCells = do.call(rbind, lapply(one, `[[`, "obsCells")), + sizes = merge(starts[starts$year %in% scored, c("year", "run", "start", "ha")], fires[c("year", "start")], by = c("year", "start"))[c("year", "run", "start", "ha")]) } #' ELF median of the fit's climate covariate (CMD) for every year of the record @@ -213,12 +281,13 @@ burnRate <- function(core, obsYears) { #' @param cores Forked workers for the observed record. @param fireCauses,escapeSizeHa See [observedRecord()]; use the ones the hindcast ran with. #' @param covariateDir Hindcast folder the climate covariate is read from ([readHindcastCovariate()]); a replay hindcast has none of its own. #' @param minHa Escape size scored (the simulated and observed `escapes`, `area50` and sizes); default `escapeSizeHa`. +#' @param inSample Is the hindcast in-sample (it spreads the observed escapes; [hindcastInSample()])? `NA` (default): read it from the data; `TRUE`/`FALSE`: as given. #' @return The list [runWave1()] documents, with `burnableHa` and `burnRate` ([burnRate()]) and the escape definition of the observed record #' (`escapeSizeHa`, `fireCauses`); `NULL` if no year is finished. readFireSenseHindcast <- function(elf, hindcastDir, ledgerFile = NULL, nfdbPath, nbacPath, obsCacheDir, years = seq(1986L, 2021L, 5L), sets = 1:5, inputsDir = "/mnt/fast/inputs", cores = 1L, fireCauses = fireSenseUtils::fireSenseFireCauses, escapeSizeHa = fireSenseUtils::fireSenseEscapeSizeHa, - minHa = escapeSizeHa, covariateDir = hindcastDir) { + minHa = escapeSizeHa, covariateDir = hindcastDir, inSample = NA) { done <- hindcastFinishedYears(hindcastDir, elf, years, sets) if (!length(done)) return(NULL) sim <- readHindcastSim(hindcastDir, elf, done, sets, minHa) @@ -228,10 +297,13 @@ readFireSenseHindcast <- function(elf, hindcastDir, ledgerFile = NULL, nfdbPath, cores = cores, fireCauses = fireCauses, escapeSizeHa = escapeSizeHa) obs <- readHindcastObserved(rec, hindcastDir, elf, done, minHa) location <- readHindcastLocation(rec, hindcastDir, elf, done, sets, core) + 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) 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)) + list(covariate = readHindcastCovariate(covariateDir, elf, core), fit = fit, location = location, inSample = inSample)) } #' The files [readFireSenseHindcast()] reads for one ELF @@ -240,7 +312,7 @@ readFireSenseHindcast <- function(elf, hindcastDir, ledgerFile = NULL, nfdbPath, #' sidecar files) of the scored `years` and `sets`. @param elf,hindcastDir,inputsDir,covariateDir,ledgerFile,nfdbPath,nbacPath,years,sets As [readFireSenseHindcast()]. #' @return Character vector of the files that exist. hindcastReadFiles <- function(elf, hindcastDir, inputsDir, covariateDir, ledgerFile, nfdbPath, nbacPath, years, sets) { - hc <- function(d) list.files(file.path(d, elf, c("climate", outer(years, sets, file.path))), "^hindcast_.*\\.(csv|tif|gpkg)$|^[A-Za-z]+_historical_.*\\.tif$", recursive = TRUE, full.names = TRUE) + hc <- function(d) list.files(file.path(d, elf, c("climate", outer(years, sets, file.path))), "^hindcast_.*\\.(csv|tif|gpkg)$|^[A-Za-z]+_historical_.*\\.tif$|^fireSense_burnSummary\\.csv$", recursive = TRUE, full.names = TRUE) shp <- unlist(lapply(c(nfdbPath, nbacPath), function(f) Sys.glob(paste0(tools::file_path_sans_ext(f), ".*")))) f <- c(hc(hindcastDir), hc(covariateDir), Sys.glob(file.path(inputsDir, elf, c("", "NRV/370/1"), paste0("rtml_", elf, ".tif"))), ledgerFile, shp) sort(unique(f[file.exists(f)])) @@ -249,7 +321,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", - "readHindcastLocation", "ignitionYear") + "readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded") #' Read every finished ELF's hindcast, each read cached #' diff --git a/R/runWave1.R b/R/runWave1.R index 7319275..9c2d535 100644 --- a/R/runWave1.R +++ b/R/runWave1.R @@ -16,6 +16,7 @@ #' \item `obsYears`: `data.frame(year, ignitions, escapes, area50)`, the observed record, every year (scored years included). #' \item `obsSizes`: `data.frame(year, ha)`, observed fire sizes, every year. #' \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 `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 @@ -37,14 +38,15 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = flagged <- names(gl)[!vapply(gl, attr, TRUE, "meaningful")] tag <- function(l) do.call(rbind, Map(function(x, nm) cbind(ELF = nm, x), l, names(l))) s <- lapply(elfs, function(e) list(S1 = scoreS1(e), S2 = scoreS2(e), S3 = scoreS3(e), S4 = scoreS4(e, minHa, nNull, adFun = adFun), S5 = scoreS5(e, nPerm), - S6 = scoreS6(e), S7 = scoreS7(e))) - tagged <- function(f) { l <- Filter(Negate(is.null), lapply(s, f)); if (length(l)) tag(l) } # S6 and S7 only for the ELFs that have `location` + S6 = scoreS6(e), S7 = scoreS7(e), S8 = scoreS8(e), S9 = scoreS9(e))) + tagged <- function(f) { l <- Filter(Negate(is.null), lapply(s, f)); if (length(l)) tag(l) } # S6 and S7 only for the ELFs that have `location`, S7 not for in-sample ones, S8 and S9 only for those perELF <- list(S1 = tag(lapply(s, function(x) x$S1$scores)), S2 = tag(lapply(s, function(x) x$S2$scores)), S3 = tag(lapply(s, function(x) x$S3$scores)), S4ad = tag(lapply(s, function(x) x$S4$ad$scores)), S4largest = tag(lapply(s, function(x) x$S4$largest$scores)), S5 = tag(lapply(s, `[[`, "S5")), - S6 = tagged(function(x) x$S6$scores), S7 = tagged(function(x) x$S7$scores)) - perELF <- Filter(Negate(is.null), perELF) # S6, S7: only when some ELF has `location` - runs <- list(S6 = tagged(function(x) x$S6$runs), S7 = tagged(function(x) x$S7$runs)) # each run's own loss, for the single-run range of the skill + S6 = tagged(function(x) x$S6$scores), S7 = tagged(function(x) x$S7$scores), + S8 = tagged(function(x) x$S8$scores), S9 = tagged(function(x) x$S9$scores)) + perELF <- Filter(Negate(is.null), perELF) # S6 to S9: only when some ELF has `location` + runs <- list(S6 = tagged(function(x) x$S6$runs), S7 = tagged(function(x) x$S7$runs), S8 = tagged(function(x) x$S8$runs), S9 = tagged(function(x) x$S9$runs)) # each run's own loss, for the single-run range of the skill cal <- list(S1 = tag(lapply(s, function(x) x$S1$cal)), S2 = tag(lapply(s, function(x) x$S2$cal)), S3 = tag(lapply(s, function(x) x$S3$cal)), S4largest = tag(lapply(s, function(x) x$S4$largest$cal)), S7 = tagged(function(x) x$S7$cal)) cal <- Filter(Negate(is.null), cal) @@ -89,7 +91,7 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = 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), slopeSplitResultRows(slopeSplit), climatePooledResultRows(climatePooled)) + 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) } diff --git a/R/spatialTests.R b/R/spatialTests.R index 7b21fc3..a24ac8b 100644 --- a/R/spatialTests.R +++ b/R/spatialTests.R @@ -87,11 +87,12 @@ aucOf <- function(p, o) { #' Per scored year: the Brier score of the model's per-cell burn probability (the share of runs in which the cell burned) against the cells observed burned, over the scored cells (the ELF's burnable #' core, the area the other tests count in). Skill is `1 - sum(lossModel) / sum(lossNull)`. N1: the cell's burn frequency over the OTHER years of the record (the scored year is left out), as a probability. #' The AUC of the model's probability is reported per year (`cal$auc`; NA in a year with no observed burn). Each run alone, as a 0/1 map, gives `runs`. +#' Not scored for an in-sample run (`elf$inSample`, see [scoreS8()]): its fires start where the observed ones did, so the map says nothing of where the model puts fire. #' @param elf ELF input list with `location$burn` (see the top of this file). -#' @return `NULL` without `location$burn`, else `list(scores, runs, cal)`: `scores` has `year, null` ("N1"), `lossModel, lossNull`; `runs` has `year, run, lossModel`; `cal` has `year, auc`. +#' @return `NULL` without `location$burn` or for an in-sample run, else `list(scores, runs, cal)`: `scores` has `year, null` ("N1"), `lossModel, lossNull`; `runs` has `year, run, lossModel`; `cal` has `year, auc`. scoreS7 <- function(elf) { b <- elf$location$burn - if (is.null(b)) return(NULL) + if (is.null(b) || isTRUE(elf$inSample)) return(NULL) N <- b$nCells; nRuns <- b$nRuns; yrs <- intersect(scoredYears(elf), as.integer(names(b$sim))) tot <- tabulate(unlist(b$obs, use.names = FALSE), N); nYr <- length(b$obs) out <- lapply(yrs, function(y) { diff --git a/README.md b/README.md index 706742b..e43b603 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Wave 1 of the hindcast test plan: regression on the ELF-mean climate covariate), N0 (shuffled years) as a floor; pooled over ELFs with a bootstrap over ELFs and years (`R/bootstrap.R`). - Spatial skill tests S6 and S7 (`R/spatialTests.R`): where ignitions and burns occur, per ELF-year, against N1 built from the ELF's OTHER years (the scored year is left out). S6 ignition location: mean negative log-likelihood per observed ignition point under the model's per-cell ignition probability, each run's map normalised to sum 1 over the ELF (location only, not totals); N1 is the other years' ignition points smoothed with a Gaussian kernel (sd 25 km) mixed 90/10 with a uniform density. S7 burn location: Brier score of the share of runs in which each burnable core cell burned, against the observed burned cells; N1 is the cell's burn frequency over the other years; AUC is also reported. Skill is `1 - sum(lossModel) / sum(lossNull)` as in S1-S5; ELF rows carry the 2.5-97.5% range of single runs. The ELF input carries `location` (cells of one grid; only the fireSense reader knows file names); ELFs without it are not scored here. +- In-sample tests S8 and S9 (`R/escapeTests.R`), for hindcasts that spread the observed escapes (detected from the data, `hindcastInSample()`; S7 is not scored for them): S8 size given escape (Spearman `rho` and median `log2ratio` of the simulated over the observed size of each seeded fire), S9 shape given escape (AUC inside the circle of 2N cells around the fire's start). Both are rows of `wave1_results.csv` and a table of the page. - Pooled driest years (`climatePooledYears()`, test `C`, `null` = `dry10Pooled` / `wetHalfPooled`): the ELF-years of every ELF's driest 10% (wetter half) of years pooled; `ratio` (headline) = sum sim / sum obs, `medianRatio` = exp(median over ELF-years of log((sim + 1) / (obs + 1))), with a cluster bootstrap over ELFs (2.5-97.5%). - `runWave1()` (`R/runWave1.R`) takes a list of ELF inputs and returns a tidy results table, the gates and per-ELF tables. - `runTablesToELF()` (`R/readRunTables.R`) builds the same input from plain per-run tables (fire sizes, ignitions per run-year), and `buildValidationPage()` (`R/buildPage.R`, layout `pageTemplate.html`) writes the figures and the scores table as one HTML file. diff --git a/pageTemplate.html b/pageTemplate.html index 90bccc6..e4d444c 100644 --- a/pageTemplate.html +++ b/pageTemplate.html @@ -80,6 +80,7 @@ Bias Climate response Location + Given an escape Observed rank Overview By metric @@ -170,6 +171,25 @@

Where fire happens S6 ignition location, S7 burn location: skill agai

Skill is 1 − model loss / null loss, over the scored years; 0 is no better than the null, above 0 is better. The null is the ELF's ignitions (S6) or burned cells (S7) of all OTHER years. S6 normalises each map to sum to 1, so it ignores totals. S7 is the Brier score of the share of runs that burned each cell. AUC: 0.5 is chance. Range: the 2.5–97.5% of single runs (ELF rows), or the bootstrap over ELFs and years (pooled).

+
+

Given an escape S8 size, S9 shape: the observed escapes are the starts; click a column to sort

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

Only for runs that spread the observed escapes from their real starts (in-sample); S7 is not scored there, because the fires start where the observed ones did. S8: for each seeded escape, the median over runs of the final size of the fire that grew from it, against its observed size: the Spearman correlation over the fires (1 is the right order), and the median log2 of simulated over observed size (0 is the right size, 1 is twice as big). S9: the circle centred on the start that holds twice the fire's observed cells (as many 0s as 1s); each cell is scored by the share of runs that burned it, and the fire's AUC is 0.5 for chance and 1 for the right shape; the ELF value is the median over fires. Observed cells outside the circle are not counted; their share is in the last-but-one column. Range: the 2.5–97.5% of single runs (ELF rows), or the bootstrap over ELFs and fires (pooled).

+
+

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

@@ -229,6 +249,7 @@

By ELF area by year, then the four distributions

const BIAS = /*BIAS*/[]; const CLIMATE = /*CLIMATE*/[]; const LOCATION = /*LOCATION*/[]; +const ESCAPE = /*ESCAPE*/[]; const SLOPESPLIT = /*SLOPESPLIT*/[]; const METRICS = [ ["areaByYear", "Area by year"], ["annualArea", "Annual area"], ["fireSizes", "Fire sizes"], @@ -334,6 +355,7 @@

By ELF area by year, then the four distributions

sortableTable("climateSplit", "climateSplitRows", "s", SLOPESPLIT, r => ["Ignitions", "EscapeRate", "Size"].map(m => ratioCells(r, ["simslope" + m]) + plainCell(r["obsslope" + m]) + ratioCells(r, ["slope" + m])).join("")); sortableTable("location", "locationRows", "l", LOCATION, r => ratioCell(r.s6, r.elf, "S6 skill", 0) + ratioCell(r.s7, r.elf, "S7 skill", 0) + ratioCell(r.auc, r.elf, "S7 AUC", 0.5)); +sortableTable("given", "givenRows", "g", ESCAPE, r => ratioCell(r.rho, r.elf, "S8 rho", 1) + ratioCell(r.size, r.elf, "S8 size", 0) + plainCell(r.n8) + ratioCell(r.auc, r.elf, "S9 AUC", 0.5) + ratioCell(r.inside, r.elf, "S9 inside", 1) + plainCell(r.n9)); function setMetric(m) { metric = m; const src = IMG["metric_" + m]; diff --git a/tests/testthat/test-escapes.R b/tests/testthat/test-escapes.R new file mode 100644 index 0000000..0d7d1c1 --- /dev/null +++ b/tests/testthat/test-escapes.R @@ -0,0 +1,137 @@ +## S8 (size given escape), S9 (shape given escape) and the S7 switch-off for in-sample runs. Synthetic ELFs with a known truth. + +## A 40 x 40 grid of 1 km cells, every cell scored. `nFires` observed escapes (one per year), each a blob of `n` cells around its start; the model's runs are +## `perfect` (the observed blob), `shuffled` (the observed blob's cells moved to random places, sizes kept) or `random` (every cell burns with probability 0.3 in every run). +seedToy <- function(model = c("perfect", "shuffled", "random"), nFires = 39L, nRuns = 20L, seed = 1, inSample = TRUE) { + model <- match.arg(model); set.seed(seed) + grid <- list(nrow = 40L, ncol = 40L, xmin = 0, xmax = 40000, ymin = 0, ymax = 40000); n <- 1600L + xy <- gridXY(grid, seq_len(n)); years <- 1986L:2024L + fires <- data.frame(year = years[seq_len(nFires)], start = sample.int(n, nFires, TRUE), nObs = sample(10:40, nFires, TRUE)) + blob <- Map(function(s, k) circleCells(xy, c(xy$x[s], xy$y[s]), k), fires$start, fires$nObs) + fires$obsHa <- fires$nObs * 100 + sizeOf <- if (model == "shuffled") sample(fires$obsHa) else fires$obsHa # a model that sizes fires at random + sizes <- do.call(rbind, lapply(seq_len(nRuns), function(r) data.frame(year = fires$year, run = r, start = fires$start, ha = sizeOf))) + sim <- lapply(stats::setNames(fires$year, fires$year), function(y) { i <- match(y, fires$year); do.call(rbind, lapply(seq_len(nRuns), function(r) { + k <- switch(model, perfect = blob[[i]], shuffled = sample.int(n, fires$nObs[i]), random = which(stats::runif(n) < 0.3)); data.frame(cell = k, run = rep(r, length(k))) })) }) + obs <- lapply(stats::setNames(fires$year, fires$year), function(y) blob[[match(y, fires$year)]]) + list(elf = paste0("seed-", model), inSample = inSample, simYears = data.frame(year = rep(fires$year, each = nRuns), run = rep(seq_len(nRuns), nFires)), + location = list(burn = list(nCells = n, nRuns = nRuns, obs = obs, sim = sim, grid = grid, gridCell = seq_len(n)), + seeded = list(fires = fires[, c("year", "start", "obsHa")], sizes = sizes, + obsCells = do.call(rbind, Map(function(y, s, b) data.frame(year = y, start = s, cell = b), fires$year, fires$start, blob))))) +} + +test_that("S8: a perfect size model has rho 1 and log ratio 0; a model that sizes fires at random has rho near 0", { + p <- scoreS8(seedToy("perfect", seed = 2)) + expect_equal(rankCor(p$scores$obsHa, p$scores$simMedian), 1); expect_equal(stats::median(p$scores$log2ratio), 0) + expect_equal(nrow(p$scores), 39L); expect_equal(nrow(p$runs), 20L); expect_true(all(p$runs$rho == 1 & p$runs$log2ratio == 0)) + s <- scoreS8(seedToy("shuffled", seed = 2)) + expect_lt(abs(rankCor(s$scores$obsHa, s$scores$simMedian)), 0.35) +}) + +test_that("S8: the simulated size of a fire is the median over runs; the log ratio is sim over observed", { + e <- seedToy("perfect", nRuns = 3L); e$location$seeded$sizes$ha[e$location$seeded$sizes$run == 3L] <- 4 * e$location$seeded$fires$obsHa # runs: 1, 1, 4 times observed + expect_equal(unique(scoreS8(e)$scores$log2ratio), 0) + e$location$seeded$sizes$ha[e$location$seeded$sizes$run == 2L] <- 4 * e$location$seeded$fires$obsHa # runs: 1, 4, 4 + expect_equal(unique(scoreS8(e)$scores$log2ratio), 2) +}) + +test_that("S9: the circle holds 2N cells, at the nearest cells to the start", { + grid <- list(nrow = 40L, ncol = 40L, xmin = 0, xmax = 40000, ymin = 0, ymax = 40000); xy <- gridXY(grid, 1:1600) + for (k in c(1L, 20L, 80L)) { + cc <- circleCells(xy, c(xy$x[820], xy$y[820]), k) + expect_length(cc, k); expect_equal(length(unique(cc)), k) + d <- (xy$x - xy$x[820])^2 + (xy$y - xy$y[820])^2 + expect_lte(max(d[cc]), min(d[-cc]) + 1e-9) + } + expect_length(circleCells(xy, c(0, 0), 5000L), 1600L) # a circle that holds more than the grid is the grid +}) + +test_that("S9: a perfect shape has AUC 1 and all its cells inside the circle; a random shape has AUC near 0.5", { + p <- scoreS9(seedToy("perfect", seed = 3)) + expect_true(all(p$scores$auc == 1)); expect_true(all(p$scores$shareInside == 1)); expect_true(all(p$runs$auc == 1)) + expect_equal(p$scores$nCircle, pmin(2 * p$scores$nObs, 1600L)) + r <- scoreS9(seedToy("random", seed = 3)) + expect_lt(abs(stats::median(r$scores$auc) - 0.5), 0.1) + expect_true(all(r$scores$shareInside == 1)) +}) + +test_that("S9: the share of the fire inside the circle is reported when the fire is elongated, and its cells outside are not counted", { + e <- seedToy("perfect", nFires = 1L, seed = 4); n <- 1600L + e$location$seeded$obsCells <- data.frame(year = 1986L, start = e$location$seeded$fires$start, cell = c(e$location$seeded$obsCells$cell, 1L, 1600L)) # two far cells, burned in every run + e$location$burn$sim[["1986"]] <- rbind(e$location$burn$sim[["1986"]], data.frame(cell = c(1L, 1600L), run = rep(1:20, each = 2))) + e$location$seeded$fires$obsHa <- 100 * (e$location$seeded$fires$obsHa / 100 + 2) + s <- scoreS9(e)$scores + expect_lt(s$shareInside, 1); expect_equal(s$shareInside, (s$nObs - 2) / s$nObs) +}) + +test_that("S7 is absent for an in-sample run and present for a normal one; S8 and S9 are the other way round", { + skip_if_not_installed("kSamples") + mk <- function(model, inSample) { e <- toyElf(name = "t", perfect = TRUE); s <- seedToy(model, inSample = inSample); e$inSample <- inSample; e$location <- s$location; e } + expect_null(scoreS7(mk("perfect", TRUE))); expect_false(is.null(scoreS7(mk("perfect", FALSE)))) + a <- runWave1(list(mk("perfect", TRUE)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results + expect_false("S7" %in% a$test); expect_true(all(c("S8", "S9") %in% a$test)) + expect_equal(sort(unique(a$measure[a$test == "S8"])), c("log2ratio", "nFires", "rho")) + expect_equal(sort(unique(a$measure[a$test == "S9"])), c("auc", "nFires", "shareInside")) + expect_equal(a$value[a$test == "S8" & a$measure == "rho" & a$level == "ELF"], 1) + expect_equal(a$value[a$test == "S9" & a$measure == "auc" & a$level == "pooled"], 1) + expect_equal(a$value[a$test == "S8" & a$measure == "nFires" & a$level == "ELF"], 8) # the toy ELF scores every fifth year: 8 fires + b <- runWave1(list(mk("perfect", FALSE)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results # the same data, flagged as a normal run + expect_true("S7" %in% b$test) + n <- mk("perfect", FALSE); n$location$seeded <- NULL + expect_false(any(c("S8", "S9") %in% runWave1(list(n), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results$test)) +}) + +test_that("S8 and S9 rows: pooled over ELFs by a bootstrap, the ELF row's range is the single runs'", { + skip_if_not_installed("kSamples") + mk <- function(seed) { e <- toyElf(name = paste0("t", seed), perfect = TRUE, seed = seed); s <- seedToy("random", seed = seed); e$inSample <- TRUE; e$location <- s$location; e } + a <- runWave1(list(mk(1), mk(2), mk(3)), toyMinHa, nBoot = 30, nNull = 19, nPerm = 99)$results + p <- a[a$test == "S9" & a$measure == "auc" & a$level == "pooled", ] + expect_equal(p$nELF, 3L); expect_equal(p$nUnits, 3L * 8L); expect_true(is.finite(p$lo) && p$lo <= p$value && p$value <= p$hi) + e <- a[a$test == "S9" & a$measure == "auc" & a$level == "ELF", ] + expect_equal(nrow(e), 3L); expect_true(all(e$lo < e$hi)) + expect_equal(a$nUnits[a$test == "S8" & a$measure == "rho" & a$level == "ELF"], rep(8L, 3)) +}) + +test_that("the page's `Given an escape` rows: pooled first, then one per ELF; none without S8 and S9", { + skip_if_not_installed("kSamples") + mk <- function(seed) { e <- toyElf(name = paste0("t", seed), perfect = TRUE, seed = seed); s <- seedToy("perfect", seed = seed); e$inSample <- TRUE; e$location <- s$location; e } + a <- runWave1(list(mk(1), mk(2)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results + r <- escapePageRows(a) + expect_equal(vapply(r, `[[`, "", "elf"), c("all: pooled", "t1", "t2")) + expect_equal(r[[2]]$rho[1], 1); expect_equal(r[[2]]$auc[1], 1); expect_equal(r[[2]]$n8, 8) + expect_length(escapePageRows(a[!a$test %in% c("S8", "S9"), ]), 0) +}) + +test_that("the reader: a run is in-sample when every run of every year starts the same fires, from the data", { + starts <- data.frame(year = rep(c(1986L, 1991L), each = 6), run = rep(rep(1:3, each = 2), 2), fire = 1:2, start = rep(c(11L, 12L), 6), ha = 1) + sy <- data.frame(year = rep(c(1986L, 1991L), each = 3), run = 1:3) + expect_true(hindcastInSample(starts, sy)) + starts$start[starts$year == 1991 & starts$run == 2 & starts$fire == 1] <- 99L # one run drew another start + expect_false(hindcastInSample(starts, sy)) + expect_false(hindcastInSample(starts[starts$run != 3, ], sy)) # a run with no fire in a year with fires: not the same set of fires + expect_false(hindcastInSample(NULL, sy)); expect_false(hindcastInSample(starts[integer(0), , drop = FALSE], sy)) +}) + +test_that("readHindcastStarts ties each fire of a rep to its start by order, and stops when the sizes of the two files differ", { + root <- withr::local_tempdir(); d <- file.path(root, "9.9", 2000, 1); dir.create(d, recursive = TRUE) + write.csv(data.frame(rep = 1:2, paramSet = 1:2, year = 2000, time = c(2000, 2000.001), ignitions = 2, escapes = 2), file.path(d, "hindcast_reps.csv"), row.names = FALSE) + write.csv(data.frame(rep = rep(1:2, each = 2), paramSet = rep(1:2, each = 2), fire_id = 1:2, ha = c(10, 20, 30, 40)), file.path(d, "hindcast_sizes.csv"), row.names = FALSE) + write.csv(data.frame(igLoc = c(5, 7, 5, 7), N = 1, year = rep(c(2000, 2000.001), each = 2), areaBurnedHa = c(10, 20, 30, 40)), file.path(d, "fireSense_burnSummary.csv"), row.names = FALSE) + s <- readHindcastStarts(root, "9.9", 2000L, sets = 1L) + expect_equal(s$run, c(1001, 1001, 2002, 2002)); expect_equal(s$fire, c(1, 2, 1, 2)); expect_equal(s$start, c(5, 7, 5, 7)); expect_equal(s$ha, c(10, 20, 30, 40)) + expect_true(hindcastInSample(s, data.frame(year = 2000L, run = c(1001, 2002)))) + write.csv(data.frame(igLoc = c(5, 7, 5, 7), N = 1, year = rep(c(2000, 2000.001), each = 2), areaBurnedHa = c(10, 21, 30, 40)), file.path(d, "fireSense_burnSummary.csv"), row.names = FALSE) + expect_error(readHindcastStarts(root, "9.9", 2000L, sets = 1L), "do not match") + expect_null(readHindcastStarts(root, "9.9", 1999L, sets = 1L)) # no file: no starts, so not in-sample + write.csv(data.frame(igLoc = numeric(0), N = numeric(0), year = numeric(0), areaBurnedHa = numeric(0)), file.path(d, "fireSense_burnSummary.csv"), row.names = FALSE) + expect_null(readHindcastStarts(root, "9.9", 2000L, sets = 1L)) # a year without a fire has a header only +}) + +test_that("the page has the `Given an escape` table only when S8 and S9 rows exist", { + skip_if_not_installed("jsonlite"); skip_if_not_installed("kSamples") + mk <- function(seed) { e <- toyElf(name = paste0("t", seed), perfect = TRUE, seed = seed); s <- seedToy("perfect", seed = seed); e$inSample <- TRUE; e$location <- s$location; e } + elfs <- list(mk(1), mk(2)); r <- runWave1(elfs, toyMinHa, nBoot = 20, nNull = 19, nPerm = 99) + page <- function(res) { f <- tempfile(fileext = ".html"); buildValidationPage(elfs, r$gates, f, testthat::test_path("..", "..", "pageTemplate.html"), minHa = toyMinHa, dpi = 30, results = res); paste(readLines(f, warn = FALSE), collapse = "\n") } + expect_match(page(r$results), 'const ESCAPE = [{"elf":"all: pooled"', fixed = TRUE) + expect_match(page(r$results[!r$results$test %in% c("S8", "S9"), ]), "const ESCAPE = [];", fixed = TRUE) +}) From 9ef8b5595615b0ba4a0a8dfe80de812863fab9fd Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Tue, 1 Dec 2026 20:27:40 -0700 Subject: [PATCH 2/2] S8/S9 review: shared page and result-row builders, one per-set reader, distance-only baseline for S9 pageRowsOf/resultCell serve the location and escape tables; longRows takes nUnits; readHindcastSetFiles and rasterizedValues are used by the sim, starts, location and seeded readers. S9 reports the AUC of a distance-only score (closer to the start is likelier burned) and the model's AUC minus it as the headline. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 2 +- R/escapeTests.R | 45 +++++++++++++++++++---------------- R/ratioTable.R | 17 ++++++++++--- R/readFireSenseHindcast.R | 16 +++++++++---- R/spatialTests.R | 10 ++------ pageTemplate.html | 6 +++-- tests/testthat/test-escapes.R | 17 +++++++++++-- 7 files changed, 72 insertions(+), 41 deletions(-) diff --git a/NEWS.md b/NEWS.md index 7302e1c..f2be75a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,6 @@ # 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, `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. +* 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/escapeTests.R b/R/escapeTests.R index ded358a..211f3ef 100644 --- a/R/escapeTests.R +++ b/R/escapeTests.R @@ -6,12 +6,15 @@ ## `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 <- (xy$x - centre[1])^2 + (xy$y - centre[2])^2 + 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)] @@ -41,8 +44,9 @@ scoreS8 <- function(elf) { #' #' 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. -#' `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`, 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`, `runs` has `run, auc`. +#' 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) @@ -53,17 +57,20 @@ scoreS9 <- function(elf) { 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])]] - 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)), - runAuc = vapply(by$byRun, function(cells) aucOf(as.integer(circ %in% cells), o), 0)) + 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")) - list(scores = do.call(rbind, lapply(one, `[[`, "row")), runs = data.frame(run = seq_len(nRuns), auc = apply(runAuc, 1, stats::median, na.rm = TRUE))) + 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(auc = function(x) stats::median(x$auc, na.rm = TRUE), shareInside = function(x) stats::median(x$shareInside))) + 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 #' @@ -78,25 +85,23 @@ escapeResultRows <- function(scores, runs, nBoot, seed) { 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), function(m) if (m %in% names(r)) quantRange(r[[m]])[1] else NA_real_, 0), hi = vapply(names(st), function(m) if (m %in% names(r)) quantRange(r[[m]])[2] else NA_real_, 0), - nELF = 1L, nUnits = nrow(g[[id]])) })) + 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_ - transform(rbind(vals, n), test = tst, null = NA_character_, verdict = NA_character_) + vals <- rbind(vals, n) + longRows(vals, tst, NA_character_, vals$measure, vals$value, vals$lo, vals$hi, nUnits = vals$nUnits) }) - if (length(rows)) { x <- do.call(rbind, rows); x[, c("test", "null", "level", "ELF", "measure", "value", "lo", "hi", "nELF", "nUnits", "verdict")] } + 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 and share of the fire inside the circle; `n8`, `n9` the fires +## 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) { - x <- results[results$test %in% c("S8", "S9"), ] - if (!nrow(x)) return(list()) - cell <- 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 } - n <- function(z, tst) { r <- z[z$test == tst & z$measure == "nFires", ]; if (nrow(r)) r$value[1] else NULL } - rowOf <- function(label, z) list(elf = label, rho = cell(z, "S8", "rho"), size = cell(z, "S8", "log2ratio"), n8 = n(z, "S8"), auc = cell(z, "S9", "auc"), inside = cell(z, "S9", "shareInside"), n9 = n(z, "S9")) - 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, ]))) + 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"))) } diff --git a/R/ratioTable.R b/R/ratioTable.R index c960af9..a9220eb 100644 --- a/R/ratioTable.R +++ b/R/ratioTable.R @@ -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) diff --git a/R/readFireSenseHindcast.R b/R/readFireSenseHindcast.R index 6b3c980..c2b73f1 100644 --- a/R/readFireSenseHindcast.R +++ b/R/readFireSenseHindcast.R @@ -18,6 +18,12 @@ hindcastFinishedYears <- function(hindcastDir, elf, years = seq(1986L, 2021L, 5L hindcastSet <- function(x, s) if ("paramSet" %in% names(x)) as.integer(x$paramSet) else rep(as.integer(s), NROW(x)) hindcastRun <- function(x, s) hindcastSet(x, s) * 1000L + x$rep +## The reps and the fire sizes of one set folder `d` +readHindcastSetFiles <- function(d) list(reps = fread0(file.path(d, "hindcast_reps.csv")), sizes = fread0(file.path(d, "hindcast_sizes.csv"))) + +## The values of the raster of the polygons `v` (field `field`) on `template`: NA where no polygon is +rasterizedValues <- function(v, template, field = 1) terra::values(terra::rasterize(v, template, field = field, background = NA))[, 1] + #' Simulated side: one row per run-year, and the simulated fire sizes #' #' Reads `hindcast_reps.csv` and `hindcast_sizes.csv` of every set. A run is a rep of a set (`run = set * 1000 + rep`). The set is the @@ -30,7 +36,7 @@ hindcastRun <- function(x, s) hindcastSet(x, s) * 1000L + x$rep readHindcastSim <- function(hindcastDir, elf, years, sets = 1:5, minHa) { both <- lapply(years, function(y) lapply(sets, function(s) { d <- file.path(hindcastDir, elf, y, s) - r <- fread0(file.path(d, "hindcast_reps.csv")); z <- fread0(file.path(d, "hindcast_sizes.csv")) + f <- readHindcastSetFiles(d); r <- f$reps; z <- f$sizes list(reps = data.frame(year = y, run = hindcastRun(r, s), paramSet = hindcastSet(r, s), ignitions = r$ignitions), sizes = data.frame(year = rep(y, NROW(z)), run = if (NROW(z)) hindcastRun(z, s) else integer(0), paramSet = if (NROW(z)) hindcastSet(z, s) else integer(0), ha = if (NROW(z)) z$ha else numeric(0))) @@ -158,7 +164,7 @@ readHindcastLocation <- function(rec, hindcastDir, elf, scored, sets, core) { } pointsOf <- lapply(stats::setNames(years, years), function(y) { v <- asVect(y, "points", "hindcast_observedPoints.gpkg"); if (!is.null(v) && NROW(v)) { cl <- terra::cellFromXY(template, terra::crds(v)); cl[!is.na(cl)] } else integer(0) }) scoredCells <- which(!is.na(terra::values(core)[, 1])); toScored <- toScoredIndex(scoredCells, terra::ncell(core)) - burnedBy <- function(v) { if (is.null(v) || !NROW(v)) return(integer(0)); b <- terra::rasterize(v, core, field = 1, background = NA); i <- toScored[which(!is.na(terra::values(b)[, 1]))]; i[i > 0] } + burnedBy <- function(v) { if (is.null(v) || !NROW(v)) return(integer(0)); i <- toScored[which(!is.na(rasterizedValues(v, core)))]; i[i > 0] } obsBurn <- lapply(stats::setNames(years, years), function(y) burnedBy(asVect(y, "polys", "hindcast_observedPolys.gpkg"))) perYear <- lapply(stats::setNames(scored, scored), function(y) { ign <- ignitionYear(terra::rast(maps(y, "ignitionProb")), { f <- own(y, "hindcast_observedPoints.gpkg"); if (!is.null(f)) terra::vect(f) }) @@ -178,7 +184,7 @@ readHindcastLocation <- function(rec, hindcastDir, elf, scored, sets, core) { readHindcastStarts <- function(hindcastDir, elf, years, sets = 1:5) { out <- lapply(years, function(y) lapply(sets, function(s) { d <- file.path(hindcastDir, elf, y, s) - bs <- fread0(file.path(d, "fireSense_burnSummary.csv")); r <- fread0(file.path(d, "hindcast_reps.csv")); z <- fread0(file.path(d, "hindcast_sizes.csv")) + bs <- fread0(file.path(d, "fireSense_burnSummary.csv")); f <- readHindcastSetFiles(d); r <- f$reps; z <- f$sizes if (is.null(bs) || is.null(r) || is.null(z) || !NROW(bs)) return(NULL) # a year without a fire has a header only t0 <- round(bs$year * 1000); i <- match(t0, round(r$time * 1000)) if (anyNA(i)) stop("fireSense_burnSummary.csv of ", d, " has a time that no rep of hindcast_reps.csv has") @@ -217,7 +223,7 @@ readHindcastSeeded <- function(starts, hindcastDir, elf, scored, sets, flammable st <- unique(starts$start[starts$year == y]); f <- file.path(hindcastDir, elf, y, sets[1], "hindcast_observedPolys.gpkg") if (!length(st) || !file.exists(f)) return(NULL) v <- terra::vect(f); v$idx <- seq_len(NROW(v)) - id <- terra::values(terra::rasterize(v, flammable, field = "idx", background = NA))[, 1] + id <- rasterizedValues(v, flammable, "idx") k <- id[st] list(fires = data.frame(year = y, start = st[!is.na(k)], obsHa = vapply(k[!is.na(k)], function(p) sum(id == p, na.rm = TRUE) * cellHa, 0)), obsCells = do.call(rbind, lapply(which(!is.na(k)), function(j) { i <- toScored[which(id == k[j])]; data.frame(year = y, start = st[j], cell = i[i > 0]) })), @@ -321,7 +327,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", - "readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded") + "readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastSetFiles", "rasterizedValues", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded") #' Read every finished ELF's hindcast, each read cached #' diff --git a/R/spatialTests.R b/R/spatialTests.R index a24ac8b..8fbca7e 100644 --- a/R/spatialTests.R +++ b/R/spatialTests.R @@ -114,11 +114,5 @@ runSkillRange <- function(runs, scores) { } ## The rows of the page's location table: the pooled row, then one per ELF; cells are `c(value, low, high, NA)` of S6 skill, S7 skill (low, high: range of single runs, or bootstrap for the pooled row) and S7 AUC (median over years) -locationPageRows <- function(results) { - x <- results[results$test %in% c("S6", "S7"), ] - if (!nrow(x)) return(list()) - cell <- 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 } - rowOf <- function(label, z) list(elf = label, s6 = cell(z, "S6", "skill"), s7 = cell(z, "S7", "skill"), auc = cell(z, "S7", "auc")) - 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, ]))) -} +locationPageRows <- function(results) + pageRowsOf(results, c("S6", "S7"), function(label, z) list(elf = label, s6 = resultCell(z, "S6", "skill"), s7 = resultCell(z, "S7", "skill"), auc = resultCell(z, "S7", "auc"))) diff --git a/pageTemplate.html b/pageTemplate.html index e4d444c..6221e1d 100644 --- a/pageTemplate.html +++ b/pageTemplate.html @@ -180,14 +180,16 @@

Given an escape S8 size, S9 shape: the observed escapes are the start + +

-

Only for runs that spread the observed escapes from their real starts (in-sample); S7 is not scored there, because the fires start where the observed ones did. S8: for each seeded escape, the median over runs of the final size of the fire that grew from it, against its observed size: the Spearman correlation over the fires (1 is the right order), and the median log2 of simulated over observed size (0 is the right size, 1 is twice as big). S9: the circle centred on the start that holds twice the fire's observed cells (as many 0s as 1s); each cell is scored by the share of runs that burned it, and the fire's AUC is 0.5 for chance and 1 for the right shape; the ELF value is the median over fires. Observed cells outside the circle are not counted; their share is in the last-but-one column. Range: the 2.5–97.5% of single runs (ELF rows), or the bootstrap over ELFs and fires (pooled).

+

Only for runs that spread the observed escapes from their real starts (in-sample); S7 is not scored there, because the fires start where the observed ones did. S8: for each seeded escape, the median over runs of the final size of the fire that grew from it, against its observed size: the Spearman correlation over the fires (1 is the right order), and the median log2 of simulated over observed size (0 is the right size, 1 is twice as big). S9: the circle centred on the start that holds twice the fire's observed cells (as many 0s as 1s); each cell is scored by the share of runs that burned it, and the fire's AUC is 0.5 for chance and 1 for the right shape; the ELF value is the median over fires. The distance-only AUC scores each cell of the circle by its closeness to the start alone (the baseline: compact fires are near their start); the headline is the model's AUC minus it, 0 meaning the model adds nothing to distance. Observed cells outside the circle are not counted; their share is in the last-but-one column. Range: the 2.5–97.5% of single runs (ELF rows), or the bootstrap over ELFs and fires (pooled).

@@ -355,7 +357,7 @@

By ELF area by year, then the four distributions

sortableTable("climateSplit", "climateSplitRows", "s", SLOPESPLIT, r => ["Ignitions", "EscapeRate", "Size"].map(m => ratioCells(r, ["simslope" + m]) + plainCell(r["obsslope" + m]) + ratioCells(r, ["slope" + m])).join("")); sortableTable("location", "locationRows", "l", LOCATION, r => ratioCell(r.s6, r.elf, "S6 skill", 0) + ratioCell(r.s7, r.elf, "S7 skill", 0) + ratioCell(r.auc, r.elf, "S7 AUC", 0.5)); -sortableTable("given", "givenRows", "g", ESCAPE, r => ratioCell(r.rho, r.elf, "S8 rho", 1) + ratioCell(r.size, r.elf, "S8 size", 0) + plainCell(r.n8) + ratioCell(r.auc, r.elf, "S9 AUC", 0.5) + ratioCell(r.inside, r.elf, "S9 inside", 1) + plainCell(r.n9)); +sortableTable("given", "givenRows", "g", ESCAPE, r => ratioCell(r.rho, r.elf, "S8 rho", 1) + ratioCell(r.size, r.elf, "S8 size", 0) + plainCell(r.n8) + ratioCell(r.diff, r.elf, "S9 AUC difference", 0) + ratioCell(r.auc, r.elf, "S9 AUC", 0.5) + ratioCell(r.dist, r.elf, "S9 distance AUC", 0.5) + ratioCell(r.inside, r.elf, "S9 inside", 1) + plainCell(r.n9)); function setMetric(m) { metric = m; const src = IMG["metric_" + m]; diff --git a/tests/testthat/test-escapes.R b/tests/testthat/test-escapes.R index 0d7d1c1..35e61fc 100644 --- a/tests/testthat/test-escapes.R +++ b/tests/testthat/test-escapes.R @@ -55,6 +55,19 @@ test_that("S9: a perfect shape has AUC 1 and all its cells inside the circle; a expect_true(all(r$scores$shareInside == 1)) }) +test_that("S9: the distance-only baseline is 1 for a compact fire, so a perfect model has difference 0 and a random one about -0.5; a fire off its start is 0, so the model that knows it gains 1", { + p <- scoreS9(seedToy("perfect", seed = 3)) + expect_true(all(p$scores$aucDist > 0.97)); expect_true(all(abs(p$runs$aucDiff) < 0.03)) # ties at the circle's edge count half + r <- scoreS9(seedToy("random", seed = 3)) + expect_lt(abs(stats::median(r$scores$auc - r$scores$aucDist) + 0.5), 0.1) + e <- seedToy("perfect", nFires = 5L, seed = 5); xy <- gridXY(e$location$burn$grid, 1:1600) + ring <- Map(function(s, n) { near <- circleCells(xy, c(xy$x[s], xy$y[s]), 2 * n); setdiff(near, circleCells(xy, c(xy$x[s], xy$y[s]), n)) }, e$location$seeded$fires$start, vapply(split(e$location$seeded$obsCells$cell, e$location$seeded$obsCells$year), length, 0L)) + e$location$seeded$obsCells <- do.call(rbind, Map(function(y, s, b) data.frame(year = y, start = s, cell = b), e$location$seeded$fires$year, e$location$seeded$fires$start, ring)) + e$location$burn$sim <- lapply(stats::setNames(e$location$seeded$fires$year, e$location$seeded$fires$year), function(y) do.call(rbind, lapply(1:20, function(r) data.frame(cell = ring[[match(y, e$location$seeded$fires$year)]], run = r)))) + s <- scoreS9(e) + expect_true(all(s$scores$aucDist < 0.03)); expect_true(all(s$scores$auc == 1)); expect_true(all(s$runs$aucDiff > 0.97)) +}) + test_that("S9: the share of the fire inside the circle is reported when the fire is elongated, and its cells outside are not counted", { e <- seedToy("perfect", nFires = 1L, seed = 4); n <- 1600L e$location$seeded$obsCells <- data.frame(year = 1986L, start = e$location$seeded$fires$start, cell = c(e$location$seeded$obsCells$cell, 1L, 1600L)) # two far cells, burned in every run @@ -71,7 +84,7 @@ test_that("S7 is absent for an in-sample run and present for a normal one; S8 an a <- runWave1(list(mk("perfect", TRUE)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results expect_false("S7" %in% a$test); expect_true(all(c("S8", "S9") %in% a$test)) expect_equal(sort(unique(a$measure[a$test == "S8"])), c("log2ratio", "nFires", "rho")) - expect_equal(sort(unique(a$measure[a$test == "S9"])), c("auc", "nFires", "shareInside")) + expect_equal(sort(unique(a$measure[a$test == "S9"])), c("auc", "aucDiff", "aucDist", "nFires", "shareInside")) expect_equal(a$value[a$test == "S8" & a$measure == "rho" & a$level == "ELF"], 1) expect_equal(a$value[a$test == "S9" & a$measure == "auc" & a$level == "pooled"], 1) expect_equal(a$value[a$test == "S8" & a$measure == "nFires" & a$level == "ELF"], 8) # the toy ELF scores every fifth year: 8 fires @@ -98,7 +111,7 @@ test_that("the page's `Given an escape` rows: pooled first, then one per ELF; no a <- runWave1(list(mk(1), mk(2)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results r <- escapePageRows(a) expect_equal(vapply(r, `[[`, "", "elf"), c("all: pooled", "t1", "t2")) - expect_equal(r[[2]]$rho[1], 1); expect_equal(r[[2]]$auc[1], 1); expect_equal(r[[2]]$n8, 8) + expect_equal(r[[2]]$rho[1], 1); expect_equal(r[[2]]$auc[1], 1); expect_equal(r[[2]]$diff[1], 0, tolerance = 0.03); expect_equal(r[[2]]$dist[1], 1, tolerance = 0.03); expect_equal(r[[2]]$n8, 8) expect_length(escapePageRows(a[!a$test %in% c("S8", "S9"), ]), 0) })