From 5eb72d9e7e9f63ec13fd54b87948318fa535c749 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Tue, 1 Dec 2026 14:30:58 -0700 Subject: [PATCH 1/2] Spatial skill tests S6 (ignition location) and S7 (burn location), and the pooled driest-years score Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- NEWS.md | 4 ++ R/buildPage.R | 8 ++- R/climateResponse.R | 70 +++++++++++++++--- R/readFireSenseHindcast.R | 48 +++++++++++-- R/runWave1.R | 27 ++++--- R/spatialTests.R | 121 +++++++++++++++++++++++++++++++ README.md | 2 + fireSimulator_validation.R | 3 +- pageTemplate.html | 20 ++++++ tests/testthat/test-climate.R | 3 +- tests/testthat/test-skill.R | 2 +- tests/testthat/test-spatial.R | 132 ++++++++++++++++++++++++++++++++++ 12 files changed, 413 insertions(+), 27 deletions(-) create mode 100644 R/spatialTests.R create mode 100644 tests/testthat/test-spatial.R diff --git a/NEWS.md b/NEWS.md index b5af703..df0b80c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # fireSimulator_validation (development version) +* New spatial skill tests, scored per ELF-year against historical nulls that leave the scored year out (`R/spatialTests.R`). S6, ignition location: the mean negative log-likelihood per observed ignition point under the model's ignition probability map (each run's map normalised to sum 1, so totals do not count), against N1, the ELF's other years' ignition points smoothed with a Gaussian kernel (25 km) and mixed 90/10 with a uniform density. S7, burn location: the Brier score of the share of runs that burned each burnable core cell, against N1, the cell's burn frequency over the other years; the per-year AUC is also reported. `wave1_results.csv` has tests `S6` and `S7` (null `N1`, measure `skill`, ELF rows with the range of single runs; `S7` also measure `auc`), and the page a "Where fire happens" table. The ELF input has an optional `location`; `readFireSenseHindcast()` builds it from `hindcast_ignitionProb_rep*.tif`, `hindcast_burnID_rep*.tif`, `hindcast_observedPoints.gpkg` and `hindcast_observedPolys.gpkg`, reducing each year as it reads. `observedRecord()` now also keeps each year's natural ignition points, so the cached ELF reads and observed records are rebuilt once. + +* New pooled driest-years score (`climatePooledYears()`): the ELF-years of every ELF's driest 10% of years (and, for symmetry, wetter half) pooled over ELFs, using the same selection as `dry10`/`wetHalf` (`climateYears()`). Headline `ratio`: the sum of simulated over the sum of observed area (median run per ELF-year); `medianRatio` is exp of the median over ELF-years of log((simulated + 1) / (observed + 1)), which is exactly 1 when most ELF-years have no fire, so it is not the headline. The interval is a cluster bootstrap over ELFs (2.5-97.5%). Rows in `results` (test `C`, `null` `dry10Pooled`, `wetHalfPooled`, level `pooled`); `runWave1()` returns `climatePooled`; the climate table of the page has a row "all: pooled ELF-years". The existing pooled `dry10` row is the median of the per-ELF ratios; it is unchanged. + * The climate `slope` is reported in its own units instead of as sim / obs, which is unstable when the observed slope is near 0 (on the 47-ELF national score: -3.7 to 13.4, 3 negative ELFs). Per ELF the climate table has the simulated slope (median over runs, 2.5-97.5% range of single runs: new columns `simLo`, `simHi`), the observed slope and the difference sim - obs (`ratio` column: median over runs of the per-run difference, with the single-run range); an observed slope of 0 now gives a finite difference. `obsRank` of the slope is the share of runs with a slope below the observed (`runSummary()` has a new argument `at`, the value that means the observed: 1 for ratios, 0 for the difference). The pooled slope row is the median over ELFs of the difference. In `wave1_results.csv` the slope rows of test `C` have measure `difference`; `dry10` and `wetHalf` stay ratios. The page's climate table shows Simulated slope, Observed slope, Difference (sim - obs), Driest 10%, Wetter half. * The pooled range over ELFs (bias and climate tables, `elfLo`/`elfHi`, `meanLo`/`meanHi`, and the `lo`/`hi` of pooled rows in `wave1_results.csv`) is now the 2.5-97.5% quantiles over ELFs (`elfRange()`, used by `poolRatios()`), as the page's notes say; it was the minimum and maximum, so one ELF with a wild value set it. Pooled medians are unchanged. diff --git a/R/buildPage.R b/R/buildPage.R index b645829..1248769 100644 --- a/R/buildPage.R +++ b/R/buildPage.R @@ -13,12 +13,14 @@ ratioCell <- function(ratio, lo, hi, obsRank) round(c(ratio, lo, hi, obsRank), 3 #' @param elfs List of ELF inputs ([runWave1()]); `elf` is the id shown on the page. #' @param gates The `gates` table of [runWave1()] (its `ELF` values are the ids of `elfs`). Only G2, G4 and G6 are used. #' @param climate The `climate` table of [runWave1()], for the climate-response table of the page; `NULL`: none. +#' @param 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 bias The `bias` table of [runWave1()] (per ELF and pooled), for the bias table of the page; `NULL`: no bias table. #' @param file Where to write the page. @param template Path of `pageTemplate.html`. #' @param title The page title (browser tab and heading). @param subtitle One line under the title. @param label Name of the simulated series in the figures. @param minHa Escape size. #' @param dpi Resolution of the inlined figures (80 keeps a 16-ELF page near 9 MB). #' @return `file`, invisibly. -buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast validation", subtitle = "", label = "simulated", minHa, dpi = 80, bias = NULL, climate = NULL) { +buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast validation", subtitle = "", label = "simulated", minHa, dpi = 80, bias = NULL, climate = NULL, climatePooled = NULL, results = NULL) { ids <- vapply(elfs, `[[`, "", "elf"); names(elfs) <- ids summ <- summariseGates(gates); summ$ELF <- as.character(summ$ELF) summ$burnRate <- vapply(elfs[summ$ELF], function(e) e$burnRate %||% NA_real_, 0) # for elfOrder(); an ELF input without one sorts last @@ -39,12 +41,14 @@ buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast v for (k in names(key)) r[[k]] <- ratioCell(z[[paste0(key[k], "_ratio")]], z[[paste0(key[k], "_runLo")]], z[[paste0(key[k], "_runHi")]], z[[paste0(key[k], "_obsRank")]]) r }) biasRows <- biasPageRows(bias) - climateRows <- climatePageRows(climate) + climateRows <- climatePageRows(climate, climatePooled) + locationRows <- if (!is.null(results)) locationPageRows(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("/*IMG*/{}", as.character(jsonlite::toJSON(img, auto_unbox = TRUE))) tpl <- gsub("__OVERVIEW__", overview, tpl, fixed = TRUE) tpl <- gsub("__TITLE__", title, tpl, fixed = TRUE) diff --git a/R/climateResponse.R b/R/climateResponse.R index 2a3768f..968fe36 100644 --- a/R/climateResponse.R +++ b/R/climateResponse.R @@ -8,6 +8,16 @@ climateMetrics <- c(slope = "climate slope", dry10 = "driest 10% of years", wetH climateKind <- c(slope = "difference", dry10 = "ratio", wetHalf = "ratio") climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- names(climateKind) +## The scored years of an ELF split by its own climate: `z` (covariate standardised over the scored years), `dry` (z at or above its 90% quantile: the driest 10%), `wet` (z at or below its median: the wetter half). +## NULL without a covariate of every scored year, with fewer than 3 years or no variation. The one place the dry and wet years are chosen (the ELF's own climate and threshold). +climateYears <- function(elf) { + years <- scoredYears(elf) + cv <- covariateOf(elf, years) + if (is.null(elf$covariate) || anyNA(cv) || length(years) < 3 || stats::sd(cv) == 0) return(NULL) + z <- (cv - mean(cv)) / stats::sd(cv) + list(years = years, z = z, dry = z >= stats::quantile(z, 0.9), wet = z <= stats::median(z)) +} + #' Climate response of one ELF #' #' Three comparisons of the simulated with the observed record over the scored years, each computed for every run alone. Area is `area50` (fires of the escape size or @@ -24,11 +34,9 @@ climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- na #' @return `data.frame`, one row per metric: `level` ("ELF"), `ELF`, `metric`, `observed` (the observed slope, or area in ha), `simMedian`, `simLo`, `simHi` (median, 2.5% and 97.5% over runs of the run's value), `ratio` (median over runs of the #' run's value relative to the observed: the difference sim - obs for the slope, the ratio for the areas), `runLo`, `runHi` (2.5% and 97.5% of the single runs' `ratio`), `obsRank` (share of runs below the observed), `elfLo`, `elfHi` (NA here), `nELF` (1), `nNonFinite` (0), `nRuns`, `nYears`. scoreClimateResponse <- function(elf) { - years <- scoredYears(elf) - cv <- covariateOf(elf, years) - if (is.null(elf$covariate) || anyNA(cv) || length(years) < 3 || stats::sd(cv) == 0) return(NULL) - z <- (cv - mean(cv)) / stats::sd(cv) - dry <- z >= stats::quantile(z, 0.9); wet <- z <= stats::median(z) + g <- climateYears(elf) + if (is.null(g)) return(NULL) + years <- g$years; z <- g$z; dry <- g$dry; wet <- g$wet slopeOf <- function(area) { k <- !is.na(area) & area > 0; if (sum(k) < 3) NA_real_ else unname(stats::coef(stats::lm(log(area[k]) ~ z[k]))[2]) } values <- function(area) c(slope = slopeOf(area), dry10 = sum(area[dry], na.rm = TRUE), wetHalf = sum(area[wet], na.rm = TRUE)) # area: per scored year, in `years` order obs <- values(obsBy(elf, "area50", years)) @@ -64,8 +72,8 @@ climateResultRows <- function(climate) { longRows(climate, "C", climate$metric, unname(climateKind[climate$metric]), climate$ratio, ifelse(p, climate$elfLo, climate$runLo), ifelse(p, climate$elfHi, climate$runHi)) } -## the rows of the page's climate table: the median of the ELFs, then one per ELF; `slope` is the difference sim - obs, `simSlope` the simulated slope (median, single-run range; no rank), `obsSlope` the observed slope; the areas are ratio cells -climatePageRows <- function(climate) { +## the rows of the page's climate table: the median of the ELFs, the pooled ELF-years ([climatePooledYears()]: `dry10` and `wetHalf` only), then one per ELF; `slope` is the difference sim - obs, `simSlope` the simulated slope (median, single-run range; no rank), `obsSlope` the observed slope; the areas are ratio cells +climatePageRows <- function(climate, pooled = NULL) { if (is.null(climate)) return(list()) rowOf <- function(label, x) { r <- list(elf = label) @@ -76,6 +84,52 @@ climatePageRows <- function(climate) { r$obsSlope <- signif(s$observed, 3) r } - c(list(rowOf("all: median of ELFs", climate[climate$level == "pooled", ])), + pooledRow <- if (!is.null(pooled)) { # the pooled ELF-years: the ratio and the bootstrap range over ELFs, no rank; only the area ratios + cell <- function(m) { z <- pooled[pooled$metric == m & pooled$measure == "ratio", ]; ratioCell(z$value, z$lo, z$hi, NA_real_) } + list(list(elf = "all: pooled ELF-years", dry10 = cell("dry10"), wetHalf = cell("wetHalf"), ref = as.list(c(slope = NA_real_, dry10 = 1, wetHalf = 1, simSlope = NA_real_)))) + } + c(list(rowOf("all: median of ELFs", climate[climate$level == "pooled", ])), pooledRow, lapply(unique(climate$ELF[climate$level == "ELF"]), function(id) rowOf(id, climate[climate$level == "ELF" & climate$ELF == id, ]))) } + +## What the pooled-years score compares: dry10 and wetHalf, each over the years of its group. +climateGroups <- c(dry10 = "dry", wetHalf = "wet") + +#' Driest-years score pooled over ELFs +#' +#' The per-ELF `dry10` rests on about 4 years, so its single-run range is wide, and its pooled row ([climateTable()]) is the median of ELF ratios. This pools the ELF-years instead: +#' every ELF's driest 10% of years (its own covariate and threshold, [climateYears()]) form one set; `wetHalf` is pooled the same way over each ELF's wetter half. For each ELF-year the simulated +#' area is the median over runs of the run's `area50` (a year a run lacks counts as no area) and the observed area is the record's `area50`. +#' Two numbers: `ratio`, the headline, sum(simulated) / sum(observed) over the ELF-years: the area the model burns in those years over the area burned, so large ELFs weigh most, as they do in area; +#' `medianRatio`, exp(median over ELF-years of log((sim + 1) / (obs + 1))) with areas in ha, where every ELF-year counts once (the +1 ha keeps years with no fire finite). `ratio` is the headline because +#' most ELF-years of the wetter half, and some of the driest, have no fire in the model and the record, so `medianRatio` is then exactly 1 and cannot tell a model that burns 2x from one that burns 0.5x. +#' The interval of both is a cluster bootstrap over ELFs: ELFs are drawn with replacement, each with all its years of the group +#' (`nBoot` draws, 2.5% and 97.5% quantiles); years are not resampled apart from their ELF. +#' @param elfs List of ELF inputs ([runWave1()]); ELFs without a usable covariate are left out. @param nBoot Bootstrap draws. @param seed Seed. +#' @return `data.frame`, one row per `metric` (`dry10`, `wetHalf`) and `measure` (`ratio`, `medianRatio`): `value`, `lo`, `hi` (bootstrap), `nELF`, `nYears` (ELF-years). `NULL` when no ELF has a covariate. +climatePooledYears <- function(elfs, nBoot = 999, seed = 1) { + yrs <- do.call(rbind, lapply(elfs, function(e) { + g <- climateYears(e) + if (is.null(g)) return(NULL) + sim <- vapply(g$years, function(y) { a <- e$simYears$area50[e$simYears$year == y]; if (length(a)) stats::median(a) else 0 }, 0) + data.frame(ELF = e$elf, year = g$years, sim = sim, obs = obsBy(e, "area50", g$years), dry = g$dry, wet = g$wet) + })) + if (is.null(yrs)) return(NULL) + stat <- function(d) c(ratio = if (sum(d$obs) > 0) sum(d$sim) / sum(d$obs) else NA_real_, medianRatio = exp(stats::median(log((d$sim + 1) / (d$obs + 1))))) + do.call(rbind, lapply(names(climateGroups), function(m) { + d <- yrs[yrs[[climateGroups[[m]]]], ] + if (!nrow(d)) return(NULL) + byElf <- split(d, d$ELF) + boot <- withSeed(seed, vapply(seq_len(nBoot), function(b) + stat(do.call(rbind, byElf[sample(names(byElf), length(byElf), replace = TRUE)])), numeric(2))) + est <- stat(d); q <- apply(boot, 1, quantRange) + data.frame(metric = m, measure = names(est), value = unname(est), lo = q[1, ], hi = q[2, ], nELF = length(byElf), nYears = nrow(d), row.names = NULL) + })) +} + +## `climatePooledYears()` as rows of the long `results` table: test "C", the metric + "Pooled" in `null` (`dry10Pooled`, `wetHalfPooled`), level "pooled", ELF "all"; `nUnits` is the ELF-years +climatePooledResultRows <- function(pooled) { + if (is.null(pooled)) return(NULL) + data.frame(test = "C", null = paste0(pooled$metric, "Pooled"), level = "pooled", ELF = "all", measure = pooled$measure, value = pooled$value, lo = pooled$lo, hi = pooled$hi, + nELF = pooled$nELF, nUnits = pooled$nYears, verdict = NA_character_) +} diff --git a/R/readFireSenseHindcast.R b/R/readFireSenseHindcast.R index fa3bc11..0dd7c43 100644 --- a/R/readFireSenseHindcast.R +++ b/R/readFireSenseHindcast.R @@ -79,8 +79,8 @@ hindcastFlammable <- function(burnMap) terra::ifel(is.na(burnMap), NA, 1) #' and the hindcast ran with. #' @param escapeSizeHa Smallest whole polygon (ha) that is an escape; default `fireSenseUtils::fireSenseEscapeSizeHa`. Use the one the fit and #' the hindcast ran with. -#' @return `list(counts, sizes, polys, escapeSizeHa, fireCauses)`: counts per year (`escapes` is the number of escape polygons), sizes with -#' `cause` and `year`, polygons (wrapped), and the escape definition the record was made with. +#' @return `list(counts, sizes, polys, points, escapeSizeHa, fireCauses)`: counts per year (`escapes` is the number of escape polygons), sizes with +#' `cause` and `year`, polygons and the natural ignition points of each year (wrapped; `NULL` for a year without), and the escape definition the record was made with. observedRecord <- function(core, flammableRTM, nfdbPath, nbacPath, years = 1986:2024, cachePath = NULL, cores = 1L, fireCauses = fireSenseUtils::fireSenseFireCauses, escapeSizeHa = fireSenseUtils::fireSenseEscapeSizeHa) { reproducible::Cache(buildObservedRecord, core, flammableRTM, nfdbPath, nbacPath, years, cores, fireCauses, escapeSizeHa, @@ -94,10 +94,11 @@ buildObservedRecord <- function(core, flammableRTM, nfdbPath, nbacPath, years, c o <- parallel::mclapply(years, function(y) { x <- fireSenseUtils::hindcastObserved(core, pts, pol, y, escapeSizeHa = escapeSizeHa, flammableRTM = flammableRTM, fireCauses = fireCauses, coreStart = TRUE) x$polys <- if (!is.null(x$polys) && NROW(x$polys)) terra::wrap(x$polys) else NULL # SpatVectors cannot leave a fork unwrapped + x$points <- if (!is.null(x$points) && NROW(x$points)) terra::wrap(x$points) else NULL x }, mc.cores = cores) list(counts = data.table::rbindlist(lapply(o, `[[`, "counts")), sizes = data.table::rbindlist(Map(function(x, y) cbind(year = y, x$sizes), o, years)), - polys = stats::setNames(lapply(o, `[[`, "polys"), years), escapeSizeHa = escapeSizeHa, fireCauses = fireCauses) + polys = stats::setNames(lapply(o, `[[`, "polys"), years), points = stats::setNames(lapply(o, `[[`, "points"), years), escapeSizeHa = escapeSizeHa, fireCauses = fireCauses) } #' Observed side in the ELF input format @@ -129,6 +130,39 @@ readHindcastObserved <- function(rec, hindcastDir, elf, scored, minHa) { escapeSizeHa = rec$escapeSizeHa, fireCauses = rec$fireCauses) } +#' 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. +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)) + 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 + x <- if (y %in% scored) own(y, f) + 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) + 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) { + ign <- ignitionYear(terra::rast(maps(y, "ignitionProb")), { f <- own(y, "hindcast_observedPoints.gpkg"); if (!is.null(f)) terra::vect(f) }) + ids <- maps(y, "burnID") + burn <- do.call(rbind, lapply(seq_along(ids), function(r) { i <- toScored[which(!is.na(terra::values(terra::rast(ids[r]))[, 1]))]; i <- i[i > 0]; data.frame(cell = i, run = rep(r, length(i))) })) + 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"))) +} + #' ELF median of the fit's climate covariate (CMD) for every year of the record #' #' Reads `climate/CMD_historical_.tif` (one layer per year) and takes its median over the core. The file is looked for in @@ -193,10 +227,11 @@ readFireSenseHindcast <- function(elf, hindcastDir, ledgerFile = NULL, nfdbPath, rec <- observedRecord(core, hindcastFlammable(burnMap), nfdbPath, nbacPath, cachePath = obsCacheDir, cores = cores, fireCauses = fireCauses, escapeSizeHa = escapeSizeHa) obs <- readHindcastObserved(rec, hindcastDir, elf, done, minHa) + location <- readHindcastLocation(rec, hindcastDir, elf, done, sets, core) 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)) + list(covariate = readHindcastCovariate(covariateDir, elf, core), fit = fit, location = location)) } #' The files [readFireSenseHindcast()] reads for one ELF @@ -205,7 +240,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)$|^[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$", 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)])) @@ -213,7 +248,8 @@ hindcastReadFiles <- function(elf, hindcastDir, inputsDir, covariateDir, ledgerF ## the inner functions readFireSenseHindcast() calls: Cache() sees the body of the function it is given, not of these readerCallees <- c("hindcastFinishedYears", "readHindcastSim", "hindcastBurnMap", "hindcastCore", "hindcastFlammable", "observedRecord", - "buildObservedRecord", "readHindcastObserved", "readLedgerRow", "burnRate", "readHindcastCovariate", "fread0") + "buildObservedRecord", "readHindcastObserved", "readLedgerRow", "burnRate", "readHindcastCovariate", "fread0", + "readHindcastLocation", "ignitionYear") #' Read every finished ELF's hindcast, each read cached #' diff --git a/R/runWave1.R b/R/runWave1.R index a6c7fd9..e6be12f 100644 --- a/R/runWave1.R +++ b/R/runWave1.R @@ -36,19 +36,29 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = rownames(gates) <- NULL 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))) + 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` 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"))) + 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 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))) + 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) perELF$calibration <- cal - skillRows <- do.call(rbind, lapply(c("S1", "S2", "S3", "S4ad", "S4largest"), function(tst) { + ## S6 and S7 have single runs: the ELF row's lo and hi are the 2.5-97.5% range of the skill of single runs (the others have none) + runRange <- function(tst, z) if (!is.null(runs[[tst]])) { r <- runs[[tst]]; r <- r[r$ELF == z$ELF[1], ]; runSkillRange(r, z[z$null == "N1", ]) } else c(NA_real_, NA_real_) + runLo <- function(tst, z) runRange(tst, z)[1]; runHi <- function(tst, z) runRange(tst, z)[2] + skillRows <- do.call(rbind, lapply(c("S1", "S2", "S3", "S4ad", "S4largest", "S6", "S7"), function(tst) { d <- perELF[[tst]] + if (is.null(d)) return(NULL) do.call(rbind, lapply(unique(d$null), function(nl) { x <- d[d$null == nl, ] perE <- do.call(rbind, lapply(split(x, x$ELF), function(z) data.frame(level = "ELF", ELF = z$ELF[1], measure = "skill", - value = skillScore(z$lossModel, z$lossNull), lo = NA_real_, hi = NA_real_, nELF = 1L, nUnits = nrow(z)))) + value = skillScore(z$lossModel, z$lossNull), lo = runLo(tst, z), hi = runHi(tst, z), nELF = 1L, nUnits = nrow(z)))) p <- bootstrapSkill(x, nBoot, seed) rbind(data.frame(level = "pooled", ELF = "all", measure = "skill", value = p$skill, lo = p$lo, hi = p$hi, nELF = p$nELF, nUnits = p$nUnits), perE) |> transform(test = tst, null = nl) @@ -56,7 +66,7 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = })) calRows <- do.call(rbind, lapply(names(cal), function(tst) { d <- cal[[tst]] - do.call(rbind, lapply(intersect(c("cover50", "cover90", "logScore"), names(d)), function(m) { + do.call(rbind, lapply(intersect(c("cover50", "cover90", "logScore", "auc"), names(d)), function(m) { x <- data.frame(ELF = d$ELF, year = d$year, value = as.numeric(d[[m]])) p <- bootstrapMean(x, nBoot, seed) perE <- do.call(rbind, lapply(split(x, x$ELF), function(z) data.frame(level = "ELF", ELF = z$ELF[1], value = pooledValue(z$value), @@ -73,14 +83,15 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = rankRows$test <- "S5"; rankRows$null <- ifelse(rankRows$measure == "pPermN0", "N0", "N2") bias <- biasTable(elfs, nBoot, seed) climate <- climateTable(elfs) + climatePooled <- climatePooledYears(elfs, nBoot, seed) res <- rbind(skillRows, calRows, rankRows) judged <- res$level == "pooled" & res$measure %in% c("skill", "rhoDiff") & res$null %in% c("N1", "N2") # N0 is a floor, not judged res$verdict <- ifelse(judged & is.finite(res$lo), ifelse(res$lo > 0, "beats null", ifelse(res$hi < 0, "worse than null", "no difference")), NA_character_) res <- res[, c("test", "null", "level", "ELF", "measure", "value", "lo", "hi", "nELF", "nUnits", "verdict")] - res <- rbind(res, biasResultRows(bias), climateResultRows(climate)) + res <- rbind(res, biasResultRows(bias), climateResultRows(climate), climatePooledResultRows(climatePooled)) rownames(res) <- NULL - list(results = res, gates = gates, bias = bias, climate = climate, perELF = perELF, flagged = flagged) + list(results = res, gates = gates, bias = bias, climate = climate, climatePooled = climatePooled, perELF = perELF, flagged = flagged) } bootRankRows <- function(rankD, nBoot, seed) { diff --git a/R/spatialTests.R b/R/spatialTests.R new file mode 100644 index 0000000..44c04d5 --- /dev/null +++ b/R/spatialTests.R @@ -0,0 +1,121 @@ +## Spatial skill tests S6 and S7: WHERE ignitions and burns occur, per ELF-year, against historical nulls that leave the scored year out. +## S1-S5 score per-year totals, so they cannot see a model that moves fire without changing how much. Nothing here knows a simulator: +## the functions take cell indices of one grid and, for the model, probabilities per cell; the adapter (readFireSenseHindcast.R) builds them from files. +## An ELF input carries `location = list(ign = ..., burn = ...)` (either part optional); ELFs without it are not scored here. +## ign: `grid` (list nrow, ncol, xmin, xmax, ymin, ymax: cells numbered row by row from the top left, as terra), `points` (list by year, as character, of the cells of the +## observed ignition points: every year of the record), `sim` (list by scored year of `list(domain, cells, p)`: the cells the model gives a probability, the cells +## of the observed points inside `domain`, and `p`, a matrix cells x runs of the model's probability at them, each run's map normalised to sum 1 over `domain`; see [ignitionYear()]). +## burn: `nCells` (the scored cells: the ELF's burnable core, numbered 1..nCells), `nRuns`, `obs` (list by year, as character, of the scored cells observed burned: every year of the record), +## `sim` (list by scored year of `data.frame(cell, run)`: the scored cells a run burned). + +## N1 of S6 mixes the smoothed history with a uniform density, so no cell has zero density +ignNullFloor <- 0.1 +## Gaussian kernel sd (map units, m) that smooths the historical ignition points into N1 of S6 +ignNullBandwidth <- 25000 + +## The centre of each cell of `grid` listed in `cells` +gridXY <- function(grid, cells) { + row <- (cells - 1L) %/% grid$ncol; col <- (cells - 1L) %% grid$ncol + list(x = grid$xmin + (col + 0.5) * (grid$xmax - grid$xmin) / grid$ncol, y = grid$ymax - (row + 0.5) * (grid$ymax - grid$ymin) / grid$nrow) +} + +#' A year's ignition map as S6 needs it +#' +#' @param maps A `SpatRaster` with one layer per run: the model's ignition probability per cell (NA where no ignition can occur). @param pts `SpatVector` of the year's observed ignition points. +#' @return `list(domain, cells, p)`: the cells of `maps` that are not NA in every run, the cells of `pts` in `domain` (points where the model has no probability are left out), and the matrix (points x runs) +#' of each run's probability at them after normalising the run's map to sum 1 over `domain`. +ignitionYear <- function(maps, pts) { + v <- terra::values(maps) + domain <- which(rowSums(is.na(v)) == 0) + cells <- if (NROW(pts)) terra::cellFromXY(maps, terra::crds(pts)) else integer(0) + cells <- cells[!is.na(cells) & cells %in% domain] + p <- sweep(v[cells, , drop = FALSE], 2, colSums(v[domain, , drop = FALSE]), "/") + list(domain = domain, cells = cells, p = p) +} + +## The Gaussian kernel of each point of `cells`, summed over every cell of the grid (a vector of length nrow x ncol) +kernelSum <- function(grid, cells, bandwidth) { + all <- gridXY(grid, seq_len(grid$nrow * grid$ncol)); xy <- gridXY(grid, cells) + k <- numeric(grid$nrow * grid$ncol) + for (i in seq_along(cells)) k <- k + exp(-((all$x - xy$x[i])^2 + (all$y - xy$y[i])^2) / (2 * bandwidth^2)) + k +} + +#' S6: ignition location +#' +#' Per scored year with observed ignitions in the model's domain: the 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: the totals are S1's), averaged over runs. Loss `-log(p)`; skill is `1 - sum(lossModel) / sum(lossNull)` ([skillScore()]) as in S1-S5. +#' N1: the ELF's ignition density from the observed points of all OTHER years (the scored year is left out), smoothed with a Gaussian kernel of sd `bandwidth` (map units, m), mixed +#' with a uniform density (weight `ignNullFloor`) so no cell has zero density, and normalised to sum 1 over the same cells as the model. N0 does not apply. +#' @param elf ELF input list with `location$ign` (see the top of this file). @param bandwidth Kernel sd of N1. @param floor Uniform share of N1. +#' @return `NULL` without `location$ign`, else `list(scores, runs)`: `scores` has `year, null` ("N1"), `lossModel, lossNull`, `runs` has `year, run, lossModel` (each run's own loss). +scoreS6 <- function(elf, bandwidth = ignNullBandwidth, floor = ignNullFloor) { + g <- elf$location$ign + if (is.null(g)) return(NULL) + pts <- g$points; yrs <- intersect(scoredYears(elf), as.integer(names(g$sim))) + K <- lapply(pts, function(cells) if (length(cells)) kernelSum(g$grid, cells, bandwidth)) + total <- Reduce(`+`, Filter(Negate(is.null), K), 0) + out <- lapply(yrs, function(y) { + s <- g$sim[[as.character(y)]] + if (!length(s$cells)) return(NULL) + d <- total - (K[[as.character(y)]] %||% 0) + dens <- d[s$domain] + nul <- if (sum(dens) > 0) (1 - floor) * dens / sum(dens) + floor / length(s$domain) else rep(1 / length(s$domain), length(s$domain)) + lossRun <- colMeans(-log(s$p)) + list(scores = data.frame(year = y, null = "N1", lossModel = mean(lossRun), lossNull = mean(-log(nul[match(s$cells, s$domain)]))), + runs = data.frame(year = y, run = seq_along(lossRun), lossModel = lossRun)) + }) + out <- Filter(Negate(is.null), out) + if (!length(out)) return(NULL) + list(scores = do.call(rbind, lapply(out, `[[`, "scores")), runs = do.call(rbind, lapply(out, `[[`, "runs"))) +} + +## Brier score of the probabilities `p` (a vector over the scored cells) against the 0/1 vector `o` +brier <- function(p, o) mean((p - o)^2) +## Area under the ROC curve of the scores `p` for the 0/1 vector `o` (ties count half); NA without both classes +aucOf <- function(p, o) { + n1 <- sum(o == 1); n0 <- length(o) - n1 + if (n1 == 0 || n0 == 0) NA_real_ else (sum(rank(p)[o == 1]) - n1 * (n1 + 1) / 2) / (n1 * n0) +} + +#' S7: burn location +#' +#' 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`. +#' @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`. +scoreS7 <- function(elf) { + b <- elf$location$burn + if (is.null(b)) 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) { + oc <- b$obs[[as.character(y)]]; s <- b$sim[[as.character(y)]] + if (is.null(oc) || nYr < 2) return(NULL) + o <- tabulate(oc, N); p <- tabulate(s$cell, N) / nRuns; f <- (tot - o) / (nYr - 1) + lossRun <- vapply(seq_len(nRuns), function(r) { sr <- s$cell[s$run == r]; (length(sr) - 2 * sum(sr %in% oc) + length(oc)) / N }, 0) # a 0/1 map's Brier score + list(scores = data.frame(year = y, null = "N1", lossModel = brier(p, o), lossNull = brier(f, o)), + runs = data.frame(year = y, run = seq_len(nRuns), lossModel = lossRun), cal = data.frame(year = y, auc = aucOf(p, o))) + }) + out <- Filter(Negate(is.null), out) + if (!length(out)) return(NULL) + list(scores = do.call(rbind, lapply(out, `[[`, "scores")), runs = do.call(rbind, lapply(out, `[[`, "runs")), cal = do.call(rbind, lapply(out, `[[`, "cal"))) +} + +## The 2.5-97.5% range of the skill of each single run: 1 - (the run's losses summed over years) / (the null's) +runSkillRange <- function(runs, scores) { + nul <- scores$lossNull[match(runs$year, scores$year)] + s <- vapply(split(seq_len(nrow(runs)), runs$run), function(i) skillScore(runs$lossModel[i], nul[i]), 0) + quantRange(s[is.finite(s)]) +} + +## 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, ]))) +} diff --git a/README.md b/README.md index 72e3b94..706742b 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Wave 1 of the hindcast test plan: - Skill tests S1-S5 (`R/skillTests.R`): CRPS skill on log(1 + x) against N1 (the ELF's own history) and N2 (a 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. +- 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. - `R/readFireSenseHindcast.R` is the only fireSense-specific file: it turns FireSenseTesting hindcast outputs, the diff --git a/fireSimulator_validation.R b/fireSimulator_validation.R index 55caf7b..7fd365c 100644 --- a/fireSimulator_validation.R +++ b/fireSimulator_validation.R @@ -191,7 +191,8 @@ doEvent.fireSimulator_validation <- function(sim, eventTime, eventType) { buildValidationPage(sim$validationELFs, sim$validationResults$gates, file.path(out, "validation.html"), template = file.path(modulePath(sim), currentModule(sim), "pageTemplate.html"), title = P(sim)$pageTitle, subtitle = P(sim)$pageSubtitle, label = P(sim)$simLabel, - minHa = scoredMinHa(P(sim)), dpi = P(sim)$pageDpi, bias = sim$validationResults$bias, climate = sim$validationResults$climate) + minHa = scoredMinHa(P(sim)), dpi = P(sim)$pageDpi, bias = sim$validationResults$bias, climate = sim$validationResults$climate, + climatePooled = sim$validationResults$climatePooled, results = sim$validationResults$results) }, warning(paste("Undefined event type: '", current(sim)[1, "eventType", with = FALSE], "' in module '", current(sim)[1, "moduleName", with = FALSE], "'", sep = "")) diff --git a/pageTemplate.html b/pageTemplate.html index 7d5d7b7..de30739 100644 --- a/pageTemplate.html +++ b/pageTemplate.html @@ -79,6 +79,7 @@ Scores Bias Climate response + Location Observed rank Overview By metric @@ -153,6 +154,22 @@

Climate response does annual area respond to climate as observed does

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

+
+

Where fire happens S6 ignition location, S7 burn location: skill against the ELF's own other years; click a column to sort

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

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

+
+

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

@@ -189,6 +206,7 @@

By ELF area by year, then the four distributions

const ROWS = /*ROWS*/[]; const BIAS = /*BIAS*/[]; const CLIMATE = /*CLIMATE*/[]; +const LOCATION = /*LOCATION*/[]; const METRICS = [ ["areaByYear", "Area by year"], ["annualArea", "Annual area"], ["fireSizes", "Fire sizes"], ["ignitions", "Ignitions"], ["escapes", "Escapes"]]; @@ -291,6 +309,8 @@

By ELF area by year, then the four distributions

+ ["areaDiff", "ignitionsDiff", "escapesDiff"].map(k => plainCell(r[k])).join("")); sortableTable("climate", "climateRows", "c", CLIMATE, r => ratioCells(r, ["simSlope"]) + plainCell(r.obsSlope) + ratioCells(r, ["slope", "dry10", "wetHalf"])); +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)); + function setMetric(m) { metric = m; const src = IMG["metric_" + m]; const img = document.getElementById("metricImg"); diff --git a/tests/testthat/test-climate.R b/tests/testthat/test-climate.R index 8a847ea..02b78d7 100644 --- a/tests/testthat/test-climate.R +++ b/tests/testthat/test-climate.R @@ -103,7 +103,8 @@ test_that("runWave1() returns the climate table and its rows in results; the pag e <- toyElf(seed = 3, name = "a-x"); e2 <- toyElf(seed = 5, name = "b-y") r <- runWave1(list(e, e2), minHa = toyMinHa, nBoot = 10, nNull = 5, nPerm = 20) expect_equal(sort(unique(r$climate$ELF)), c("a-x", "all", "b-y")) - expect_equal(sum(r$results$test == "C"), 9L); expect_equal(unique(r$results$measure[r$results$test == "C" & r$results$null == "slope"]), "difference") + expect_equal(sum(r$results$test == "C"), 9L + 4L); # the per-ELF and pooled rows, and the pooled ELF-years rows (dry10, wetHalf: ratio and medianRatio) + expect_equal(unique(r$results$measure[r$results$test == "C" & r$results$null == "slope"]), "difference") g <- do.call(rbind, lapply(list(e, e2), function(x) cbind(ELF = x$elf, runGates(x, nBoot = 20)))) f <- tempfile(fileext = ".html") buildValidationPage(list(e, e2), g, f, testthat::test_path("..", "..", "pageTemplate.html"), minHa = toyMinHa, dpi = 30, bias = r$bias, climate = r$climate) diff --git a/tests/testthat/test-skill.R b/tests/testthat/test-skill.R index e537a6c..951a48d 100644 --- a/tests/testthat/test-skill.R +++ b/tests/testthat/test-skill.R @@ -61,7 +61,7 @@ test_that("the runner returns the tidy table, gates, per-ELF tables and the flag elfs <- list(toyElf("a", perfect = TRUE, seed = 1), toyElf("b", perfect = TRUE, seed = 2), toyElf("c", perfect = FALSE, seed = 3)) elfs[[3]]$fit$fitAreaHa <- 0 # fails G3 out <- runWave1(elfs, toyMinHa, nBoot = 49, nNull = 29, nPerm = 99) - expect_named(out, c("results", "gates", "bias", "climate", "perELF", "flagged")) + expect_named(out, c("results", "gates", "bias", "climate", "climatePooled", "perELF", "flagged")) expect_equal(out$flagged, "c") expect_equal(nrow(out$gates), 18) r <- out$results diff --git a/tests/testthat/test-spatial.R b/tests/testthat/test-spatial.R new file mode 100644 index 0000000..5cc523a --- /dev/null +++ b/tests/testthat/test-spatial.R @@ -0,0 +1,132 @@ +## S6 (ignition location), S7 (burn location) and the pooled driest-years score. Synthetic ELFs with a known truth. + +## An ELF input with `location`: a 40 x 40 grid of 1 km cells, ignitions drawn from `truth` (cell intensity), the model's map `model` in every run +spatialToy <- function(model, truth, years = 1986:2024, nPer = 8, seed = 1) { + set.seed(seed) + grid <- list(nrow = 40L, ncol = 40L, xmin = 0, xmax = 40000, ymin = 0, ymax = 40000) + n <- grid$nrow * grid$ncol; p <- model / sum(model) + pts <- lapply(stats::setNames(years, years), function(y) sample.int(n, nPer, replace = TRUE, prob = truth / sum(truth))) + sim <- lapply(stats::setNames(years, years), function(y) { + cells <- pts[[as.character(y)]] + list(domain = seq_len(n), cells = cells, p = matrix(p[cells], length(cells), 3L)) + }) + list(elf = "sp", simYears = data.frame(year = rep(years, each = 3L), run = rep(1:3, length(years))), location = list(ign = list(grid = grid, points = pts, sim = sim))) +} +hotspot <- function() { x <- rep(seq(500, 39500, 1000), 40); y <- rep(seq(39500, 500, -1000), each = 40); 0.02 + exp(-((x - 12000)^2 + (y - 28000)^2) / (2 * 4000^2)) } + +test_that("S6: a map that matches the true ignition intensity beats a flat null by a positive skill; a shuffled map does not", { + truth <- hotspot(); e <- spatialToy(truth, truth) + r <- scoreS6(e, bandwidth = 4000) + expect_gt(skillScore(r$scores$lossModel, r$scores$lossNull), 0) + set.seed(2); shuf <- spatialToy(sample(truth), truth) + s <- scoreS6(shuf, bandwidth = 4000) + expect_lt(skillScore(s$scores$lossModel, s$scores$lossNull), 0.02) + expect_equal(unique(r$scores$null), "N1") + expect_equal(sort(unique(r$runs$run)), 1:3) +}) + +test_that("S6: the null of a year leaves that year's points out, and uses every other year's", { + truth <- hotspot(); e <- spatialToy(truth, truth) + a <- scoreS6(e, bandwidth = 4000)$scores + e$location$ign$points[["2000"]] <- rep(1L, 50) # change the record of one year only + b <- scoreS6(e, bandwidth = 4000)$scores + expect_equal(b$lossNull[b$year == 2000], a$lossNull[a$year == 2000]) # its own null did not see it + expect_false(isTRUE(all.equal(b$lossNull[b$year == 2001], a$lossNull[a$year == 2001]))) # the other years' nulls did +}) + +test_that("S6: years without observed ignitions are skipped", { + truth <- hotspot(); e <- spatialToy(truth, truth) + e$location$ign$sim[["1990"]]$cells <- integer(0); e$location$ign$sim[["1990"]]$p <- matrix(numeric(0), 0, 3) + expect_false(1990L %in% scoreS6(e, bandwidth = 4000)$scores$year) +}) + +## burn toy: 1000 cells; the truth burns a block of cells with probability `pBurn` each year; the model is that probability (or shuffled) +burnToy <- function(model, truth, years = 1986:2024, nRuns = 20L, seed = 1) { + set.seed(seed); n <- length(truth) + obs <- lapply(stats::setNames(years, years), function(y) which(stats::runif(n) < truth)) + sim <- lapply(stats::setNames(years, years), function(y) do.call(rbind, lapply(seq_len(nRuns), function(r) { k <- which(stats::runif(n) < model); data.frame(cell = k, run = rep(r, length(k))) }))) + list(elf = "bt", simYears = data.frame(year = rep(years, each = nRuns), run = rep(seq_len(nRuns), length(years))), location = list(burn = list(nCells = n, nRuns = nRuns, obs = obs, sim = sim))) +} + +test_that("S7: a model whose burn probability is the truth has positive skill and AUC well above 0.5; a shuffled one has skill about 0 or below", { + truth <- c(rep(0.3, 100), rep(0.01, 900)) + r <- scoreS7(burnToy(truth, truth, nRuns = 200L)) # many runs: the model's own sampling noise is small beside the 38-year frequency + expect_gt(skillScore(r$scores$lossModel, r$scores$lossNull), 0) + expect_gt(stats::median(r$cal$auc), 0.7) + set.seed(3); s <- scoreS7(burnToy(sample(truth), truth, nRuns = 200L)) + expect_lt(skillScore(s$scores$lossModel, s$scores$lossNull), 0.02) + expect_lt(stats::median(s$cal$auc), 0.6) + expect_equal(unique(r$scores$null), "N1"); expect_equal(sort(unique(r$runs$run)), 1:200) +}) + +test_that("S7: a year's null is the burn frequency of the other years, not its own", { + truth <- c(rep(0.3, 100), rep(0.01, 900)); e <- burnToy(truth, truth) + a <- scoreS7(e)$scores + e$location$burn$obs[["2000"]] <- 1:1000 # every cell burns in 2000: only the other years' nulls see it + b <- scoreS7(e)$scores + expect_equal(b$lossNull[b$year == 2000], 0.0 + brier((tabulate(unlist(e$location$burn$obs[names(e$location$burn$obs) != "2000"]), 1000)) / 38, rep(1, 1000))) + expect_false(isTRUE(all.equal(b$lossNull[b$year == 2001], a$lossNull[a$year == 2001]))) +}) + +test_that("runWave1 adds S6 and S7 rows (pooled and per ELF, single-run range on the ELF row) when the ELFs have `location`, and none otherwise", { + skip_if_not_installed("kSamples") + truth <- hotspot(); bt <- c(rep(0.3, 100), rep(0.01, 900)) + mk <- function(nm, seed) { e <- toyElf(name = nm, perfect = TRUE, seed = seed); e$location <- c(spatialToy(truth, truth, seed = seed)$location, burnToy(bt, bt, seed = seed)$location); e } + r <- runWave1(list(mk("a", 1), mk("b", 2)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99) + x <- r$results + expect_true(all(c("S6", "S7") %in% x$test)) + expect_equal(sort(unique(x$measure[x$test == "S7"])), c("auc", "skill")) + e7 <- x[x$test == "S7" & x$measure == "skill" & x$level == "ELF", ] + expect_equal(nrow(e7), 2); expect_true(all(is.finite(e7$lo) & is.finite(e7$hi))) + expect_equal(x$null[x$test == "S6" & x$level == "pooled"], "N1") + plain <- runWave1(list(toyElf(name = "c", perfect = TRUE)), toyMinHa, nBoot = 20, nNull = 19, nPerm = 99)$results + expect_false(any(c("S6", "S7") %in% plain$test)) +}) + +## pooled driest years: ELFs with 20 scored years; the model is the observed area times `k` in every year, so the true pooled ratio is `k` +pooledToy <- function(name, k, seed) { + set.seed(seed); years <- 1986:2005; cv <- rnorm(20) + area <- rlnorm(20, 5, 1) + list(elf = name, covariate = data.frame(year = years, value = cv), obsYears = data.frame(year = years, area50 = area), + simYears = data.frame(year = rep(years, each = 3L), run = rep(1:3, 20), area50 = rep(area * k, each = 3L))) +} + +test_that("pooled driest years: the ratio of a model that is k times the observed is k, for dry and wet years, with an interval from a bootstrap over ELFs", { + elfs <- lapply(1:6, function(i) pooledToy(paste0("e", i), 2, i)) + p <- climatePooledYears(elfs, nBoot = 50) + d <- p[p$metric == "dry10", ] + expect_equal(d$value[d$measure == "ratio"], 2) + expect_equal(d$value[d$measure == "medianRatio"], 2, tolerance = 0.05) # the +1 ha moves a log ratio of areas of hundreds of ha by about 0.001 + expect_true(all(d$lo <= 2.05 & d$hi >= 1.95)) + expect_equal(d$nELF[1], 6L); expect_equal(d$nYears[1], 6L * 2L) # the driest 10% of 20 years: 2 each + expect_equal(p$value[p$metric == "wetHalf" & p$measure == "ratio"], 2) + r <- climatePooledResultRows(p) + expect_equal(unique(r$null), c("dry10Pooled", "wetHalfPooled")); expect_true(all(r$level == "pooled" & r$ELF == "all" & r$test == "C")) +}) + +test_that("pooled driest years: the bootstrap resamples whole ELFs, and the dry years are those the per-ELF dry10 uses", { + e <- pooledToy("x", 1, 4); g <- climateYears(e) + expect_equal(sum(g$dry), 2L) + elfs <- list(pooledToy("a", 1, 1), pooledToy("b", 4, 2)) # two ELFs with different ratios: a draw of two copies of one ELF gives that ELF's ratio + p <- climatePooledYears(elfs, nBoot = 200) + d <- p[p$metric == "dry10" & p$measure == "ratio", ] + expect_equal(d$lo, 1); expect_equal(d$hi, 4) + expect_equal(scoreClimateResponse(elfs[[1]])$observed[2], sum(elfs[[1]]$obsYears$area50[match(1986:2005, elfs[[1]]$obsYears$year)][climateYears(elfs[[1]])$dry])) +}) + +test_that("the page carries the location table and the pooled ELF-years row of the climate table", { + skip_if_not_installed("jsonlite"); skip_if_not_installed("kSamples") + truth <- hotspot(); bt <- c(rep(0.3, 100), rep(0.01, 900)) + mk <- function(nm, seed) { e <- toyElf(name = nm, perfect = TRUE, seed = seed); e$location <- c(spatialToy(truth, truth, seed = seed)$location, burnToy(bt, bt, seed = seed)$location); e } + elfs <- list(mk("a-x", 1), mk("b-y", 2)) + r <- runWave1(elfs, toyMinHa, nBoot = 20, nNull = 19, nPerm = 99) + f <- tempfile(fileext = ".html") + buildValidationPage(elfs, r$gates, f, testthat::test_path("..", "..", "pageTemplate.html"), minHa = toyMinHa, dpi = 30, bias = r$bias, + climate = r$climate, climatePooled = r$climatePooled, results = r$results) + h <- paste(readLines(f, warn = FALSE), collapse = "\n") + expect_false(grepl("/\\*LOCATION\\*/\\[\\]", h)) + loc <- jsonlite::fromJSON(sub(";.*", "", sub(".*const LOCATION = ", "", h)), simplifyVector = FALSE) + expect_equal(vapply(loc, `[[`, "", "elf"), c("all: pooled", "a-x", "b-y")) + cl <- jsonlite::fromJSON(sub(";.*", "", sub(".*const CLIMATE = ", "", h)), simplifyVector = FALSE) + expect_true("all: pooled ELF-years" %in% vapply(cl, `[[`, "", "elf")) +}) From 49f701e62bdd1bbcec4b6dc07de06287fbf44021 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Tue, 1 Dec 2026 14:37:47 -0700 Subject: [PATCH 2/2] Pooled driest years use bootstrapPooled(resampleYears = FALSE); one runSkillRange call per ELF; one bindYears helper Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXhXsFis2pbqBTh2PPh --- R/bootstrap.R | 6 +++--- R/climateResponse.R | 8 +++----- R/runWave1.R | 5 ++--- R/spatialTests.R | 14 ++++++++------ 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/R/bootstrap.R b/R/bootstrap.R index b754b39..ad29d64 100644 --- a/R/bootstrap.R +++ b/R/bootstrap.R @@ -5,16 +5,16 @@ #' @param d `data.frame` with columns `ELF` and `year` and whatever `stat` needs. #' @param stat `function(df)` returning a numeric vector; `df` has the resampled rows and an `ELF` column in which #' every drawn ELF has its own label (a copy drawn twice counts twice). -#' @param nBoot Resamples. @param seed Seed (the caller's RNG state is restored). +#' @param nBoot Resamples. @param seed Seed (the caller's RNG state is restored). @param resampleYears `FALSE`: a cluster bootstrap, each drawn ELF keeps all its rows. #' @return List: `est` (stat on `d`), `lo`, `hi` (2.5% and 97.5% of the resamples, per element of `stat`), `boot` #' (matrix of resamples, one column each). -bootstrapPooled <- function(d, stat, nBoot = 999, seed = 1) { +bootstrapPooled <- function(d, stat, nBoot = 999, seed = 1, resampleYears = TRUE) { g <- split(d, d$ELF) est <- stat(d) boot <- withSeed(seed, vapply(seq_len(nBoot), function(b) { pick <- sample(names(g), length(g), replace = TRUE) stat(do.call(rbind, lapply(seq_along(pick), function(i) { - x <- g[[pick[i]]]; x <- x[sample.int(nrow(x), replace = TRUE), , drop = FALSE]; x$ELF <- paste0(pick[i], "#", i); x }))) + x <- g[[pick[i]]]; if (resampleYears) x <- x[sample.int(nrow(x), replace = TRUE), , drop = FALSE]; x$ELF <- paste0(pick[i], "#", i); x }))) }, numeric(length(est)))) boot <- matrix(boot, nrow = length(est)) q <- apply(boot, 1, stats::quantile, c(0.025, 0.975), na.rm = TRUE, names = FALSE) diff --git a/R/climateResponse.R b/R/climateResponse.R index 968fe36..1165d9e 100644 --- a/R/climateResponse.R +++ b/R/climateResponse.R @@ -119,11 +119,9 @@ climatePooledYears <- function(elfs, nBoot = 999, seed = 1) { do.call(rbind, lapply(names(climateGroups), function(m) { d <- yrs[yrs[[climateGroups[[m]]]], ] if (!nrow(d)) return(NULL) - byElf <- split(d, d$ELF) - boot <- withSeed(seed, vapply(seq_len(nBoot), function(b) - stat(do.call(rbind, byElf[sample(names(byElf), length(byElf), replace = TRUE)])), numeric(2))) - est <- stat(d); q <- apply(boot, 1, quantRange) - data.frame(metric = m, measure = names(est), value = unname(est), lo = q[1, ], hi = q[2, ], nELF = length(byElf), nYears = nrow(d), row.names = NULL) + b <- bootstrapPooled(d, stat, nBoot, seed, resampleYears = FALSE) + est <- b$est; q <- rbind(b$lo, b$hi) + data.frame(metric = m, measure = names(est), value = unname(est), lo = b$lo, hi = b$hi, nELF = length(unique(d$ELF)), nYears = nrow(d), row.names = NULL) })) } diff --git a/R/runWave1.R b/R/runWave1.R index e6be12f..6d181d9 100644 --- a/R/runWave1.R +++ b/R/runWave1.R @@ -51,14 +51,13 @@ runWave1 <- function(elfs, minHa, nBoot = 999, nNull = 199, nPerm = 9999, seed = perELF$calibration <- cal ## S6 and S7 have single runs: the ELF row's lo and hi are the 2.5-97.5% range of the skill of single runs (the others have none) runRange <- function(tst, z) if (!is.null(runs[[tst]])) { r <- runs[[tst]]; r <- r[r$ELF == z$ELF[1], ]; runSkillRange(r, z[z$null == "N1", ]) } else c(NA_real_, NA_real_) - runLo <- function(tst, z) runRange(tst, z)[1]; runHi <- function(tst, z) runRange(tst, z)[2] skillRows <- do.call(rbind, lapply(c("S1", "S2", "S3", "S4ad", "S4largest", "S6", "S7"), function(tst) { d <- perELF[[tst]] if (is.null(d)) return(NULL) do.call(rbind, lapply(unique(d$null), function(nl) { x <- d[d$null == nl, ] - perE <- do.call(rbind, lapply(split(x, x$ELF), function(z) data.frame(level = "ELF", ELF = z$ELF[1], measure = "skill", - value = skillScore(z$lossModel, z$lossNull), lo = runLo(tst, z), hi = runHi(tst, z), nELF = 1L, nUnits = nrow(z)))) + perE <- do.call(rbind, lapply(split(x, x$ELF), function(z) { rr <- runRange(tst, z); data.frame(level = "ELF", ELF = z$ELF[1], measure = "skill", + value = skillScore(z$lossModel, z$lossNull), lo = rr[1], hi = rr[2], nELF = 1L, nUnits = nrow(z)) })) p <- bootstrapSkill(x, nBoot, seed) rbind(data.frame(level = "pooled", ELF = "all", measure = "skill", value = p$skill, lo = p$lo, hi = p$hi, nELF = p$nELF, nUnits = p$nUnits), perE) |> transform(test = tst, null = nl) diff --git a/R/spatialTests.R b/R/spatialTests.R index 44c04d5..7b21fc3 100644 --- a/R/spatialTests.R +++ b/R/spatialTests.R @@ -33,6 +33,12 @@ ignitionYear <- function(maps, pts) { list(domain = domain, cells = cells, p = p) } +## The per-year lists `list(scores, runs, ...)` of S6/S7 as one list of tables (years without a result are NULL and dropped); NULL when none +bindYears <- function(out) { + out <- Filter(Negate(is.null), out) + if (length(out)) lapply(stats::setNames(names(out[[1]]), names(out[[1]])), function(n) do.call(rbind, lapply(out, `[[`, n))) +} + ## The Gaussian kernel of each point of `cells`, summed over every cell of the grid (a vector of length nrow x ncol) kernelSum <- function(grid, cells, bandwidth) { all <- gridXY(grid, seq_len(grid$nrow * grid$ncol)); xy <- gridXY(grid, cells) @@ -65,9 +71,7 @@ scoreS6 <- function(elf, bandwidth = ignNullBandwidth, floor = ignNullFloor) { list(scores = data.frame(year = y, null = "N1", lossModel = mean(lossRun), lossNull = mean(-log(nul[match(s$cells, s$domain)]))), runs = data.frame(year = y, run = seq_along(lossRun), lossModel = lossRun)) }) - out <- Filter(Negate(is.null), out) - if (!length(out)) return(NULL) - list(scores = do.call(rbind, lapply(out, `[[`, "scores")), runs = do.call(rbind, lapply(out, `[[`, "runs"))) + bindYears(out) } ## Brier score of the probabilities `p` (a vector over the scored cells) against the 0/1 vector `o` @@ -98,9 +102,7 @@ scoreS7 <- function(elf) { list(scores = data.frame(year = y, null = "N1", lossModel = brier(p, o), lossNull = brier(f, o)), runs = data.frame(year = y, run = seq_len(nRuns), lossModel = lossRun), cal = data.frame(year = y, auc = aucOf(p, o))) }) - out <- Filter(Negate(is.null), out) - if (!length(out)) return(NULL) - list(scores = do.call(rbind, lapply(out, `[[`, "scores")), runs = do.call(rbind, lapply(out, `[[`, "runs")), cal = do.call(rbind, lapply(out, `[[`, "cal"))) + bindYears(out) } ## The 2.5-97.5% range of the skill of each single run: 1 - (the run's losses summed over years) / (the null's)