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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

* 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()`).

* 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.
Expand Down
6 changes: 3 additions & 3 deletions R/bootstrap.R
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions R/buildPage.R
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ 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 slopeSplit The `slopeSplit` table of [runWave1()], for the table of the climate slope's three parts under the climate table; `NULL`: none.
#' @param bias The `bias` table of [runWave1()] (per ELF and pooled), for the bias table of the page; `NULL`: no bias table.
#' @param file Where to write the page. @param template Path of `pageTemplate.html`.
#' @param title The page title (browser tab and heading). @param subtitle One line under the title. @param label Name of the simulated series in the figures. @param minHa Escape size.
#' @param dpi Resolution of the inlined figures (80 keeps a 16-ELF page near 9 MB).
#' @return `file`, invisibly.
buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast validation", subtitle = "", label = "simulated", minHa, dpi = 80, bias = NULL, climate = NULL, slopeSplit = NULL) {
buildValidationPage <- function(elfs, gates, file, template, title = "Hindcast validation", subtitle = "", label = "simulated", minHa, dpi = 80, bias = NULL, climate = NULL, slopeSplit = 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
Expand All @@ -40,13 +42,15 @@ 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)
slopeSplitRows <- slopeSplitPageRows(slopeSplit)
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("/*SLOPESPLIT*/[]", as.character(jsonlite::toJSON(slopeSplitRows, auto_unbox = TRUE, na = "null")))
fill("/*IMG*/{}", as.character(jsonlite::toJSON(img, auto_unbox = TRUE)))
tpl <- gsub("__OVERVIEW__", overview, tpl, fixed = TRUE)
Expand Down
64 changes: 57 additions & 7 deletions R/climateResponse.R
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ climateInputs <- function(elf) {
## the slope of `y` (a log value; years with a non-finite value are left out) on `z`: NA with fewer than 3 years
logSlope <- function(y, z) { k <- is.finite(y); if (sum(k) < 3) NA_real_ else unname(stats::coef(stats::lm(y[k] ~ z[k]))[2]) }

## The scored years of an ELF split by its own climate, from [climateInputs()]: `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 as climateInputs(). The one place the dry and wet years are chosen (the ELF's own climate and threshold).
climateYears <- function(elf) {
ci <- climateInputs(elf)
if (is.null(ci)) NULL else c(ci, list(dry = ci$z >= stats::quantile(ci$z, 0.9), wet = ci$z <= stats::median(ci$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
Expand All @@ -35,10 +42,9 @@ logSlope <- function(y, z) { k <- is.finite(y); if (sum(k) < 3) NA_real_ else un
#' @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) {
ci <- climateInputs(elf)
if (is.null(ci)) return(NULL)
years <- ci$years; z <- ci$z
dry <- z >= stats::quantile(z, 0.9); wet <- z <= stats::median(z)
g <- climateYears(elf)
if (is.null(g)) return(NULL)
years <- g$years; z <- g$z; dry <- g$dry; wet <- g$wet
values <- function(area) c(slope = logSlope(log(area), z), dry10 = sum(area[dry], na.rm = TRUE), wetHalf = sum(area[wet], na.rm = TRUE)) # area: per scored year, in `years` order
obs <- values(obsBy(elf, "area50", years))
ratioTo <- function(v) vapply(names(climateKind), function(m) if (climateKind[[m]] == "difference") v[[m]] - obs[[m]] else zeroSafeRatio(v[[m]], obs[[m]]), 0)
Expand Down Expand Up @@ -75,8 +81,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)
Expand All @@ -87,7 +93,11 @@ 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, ])))
}

Expand Down Expand Up @@ -154,3 +164,43 @@ slopeSplitPageRows <- function(slopeSplit) {
c(list(rowOf("all: median of ELFs", slopeSplit[slopeSplit$level == "pooled", ])),
lapply(unique(slopeSplit$ELF[slopeSplit$level == "ELF"]), function(id) rowOf(id, slopeSplit[slopeSplit$level == "ELF" & slopeSplit$ELF == id, ])))
}

## 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)
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)
}))
}

## `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_)
}
Loading
Loading