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
@@ -1,5 +1,9 @@
# fireSimulator_validation (development version)

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

* New climate-response metrics, scored for every arm by the same scorer: `scoreClimateResponse()` gives, per ELF and per run, the slope of log annual area burned on the standardised climate covariate (`slope`), the area in the driest 10% of the scored years (`dry10`) and in the wetter half (`wetHalf`), each as simulated over observed (the definitions of the extreme-fire-years climate comparison). Area is `area50` (fires of the escape size or more, as the page's area row); `dry10` is the years at or above the 90% quantile of the climate covariate over the scored years (about 4 of 39); the covariate is standardised over the scored years, so the observed slope is per standard deviation of the scored years; a year a run lacks counts as no area. The ratio is the median of the single runs, with their 2.5-97.5% range (`runLo`, `runHi`) and the observed rank (`obsRank`, the page's "obs N%"), from `runSummary()`, which `bootRuns()` now calls too. `climateTable()` adds the median over ELFs with the range over ELFs. `runWave1()` returns it as `climate` (computed in the cached `init`) and adds its rows to `results` (test `C`, the metric in `null`, measure `ratio`), so `wave1_results.csv` has them; `validation.html` has a sortable climate-response table. ELFs without a covariate are left out. Gates and scores are unchanged; the `runWave1()` result has one more element and `buildValidationPage()` one more argument. The pooling over ELFs, the long-table rows and the page cells are shared with the bias table (`poolRatios()`, `longRows()`, `rangeCell()`; one `sortableTable()` in the page); the bias results are unchanged.

* The page (`validation.html`), the figures, `wave1.rds`, `wave1_results.csv` and `wave1_bySet.csv` are written by a new event `writeOutputs` from `validationResults`, not by `init`. A cached `init` restores only `validationResults`, so a score job that hit the cache left these files unwritten or stale. Modes `anova` and `weights` are split the same way (new output `weightsResults`), and `scoreBySet()` runs in `init` (new output `bySetResults`), so `writeOutputs` only renders the figures and the page and writes files. `.inputObjects` reads the files of the `anova` and `weights` modes (new inputs `anovaLong`, `weightsTables`), so their content is in `init`'s cache key; a changed file is a miss, as for the hindcast. `runAnova()` and `runWeights()` are removed (`readAnovaScores()`/`computeAnova()`/`writeAnova()`, `readWeightsTables()`/`tuneWeights()`/`writeWeights()`). The page and plot parameters (`pageTitle`, `pageSubtitle`, `pageDpi`, `simLabel`, `.plots`, `.plotInitialTime`) and the input-file parameters of the two modes are no longer in `init`'s cache key; no figure is built when `.plots` is `NA`. A user's `.neverCache` can no longer drop `writeOutputs`. `writeOutputs` is in the default of `.neverCache`; the scoring stays cached.
Expand Down
7 changes: 3 additions & 4 deletions R/bias.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ scoreBias <- function(elf, nBoot = 1000, seed = 1) {

#' Bias pooled over ELFs
#'
#' Two pooled ratios, not the same number. `ratio` is the median over ELFs of the ELF ratios (`elfLo`, `elfHi`: their range, lowest and highest ELF);
#' Two pooled ratios, not the same number. `ratio` is the median over ELFs of the ELF ratios (`elfLo`, `elfHi`: their 2.5-97.5% range over ELFs);
#' it treats every ELF alike. ELFs with a ratio that is not finite (nothing observed, something simulated: Inf) are left out of the median and range, and counted: `nELF` is the number of ELFs and `nNonFinite` how many of them were left out. `ratioOfSums` is the sum over ELFs of the median run's total over the sum of the observed totals (NA for the largest
#' fires, which have no total); large ELFs dominate it. `per1000yr` is the sum over ELFs of the ELFs' differences. The mean-run ratio is pooled the same two ways: `meanRatio` is the median over ELFs of the ELFs' `meanRatio`
#' (`meanLo`, `meanHi`: their range over ELFs, not a bootstrap interval) and `meanRatioOfSums` the sum of the run-mean totals over the sum of the observed.
#' (`meanLo`, `meanHi`: their 2.5-97.5% range over ELFs, not a bootstrap interval) and `meanRatioOfSums` the sum of the run-mean totals over the sum of the observed.
#'
#' @param bias The rows of [scoreBias()] of several ELFs, bound.
#' @return `data.frame` with the columns of [scoreBias()], one row per quantity, `level` "pooled" and `ELF` "all". `observed` and `simMedian` are sums over ELFs (NA
Expand All @@ -59,8 +59,7 @@ poolBias <- function(bias) {
ratio = pr$ratio, log2ratio = med(x$log2ratio), lo = NA_real_, hi = NA_real_, runLo = NA_real_, runHi = NA_real_,
elfLo = pr$elfLo, elfHi = pr$elfHi, nELF = pr$nELF, nNonFinite = pr$nNonFinite, ratioOfSums = if (tot) zeroSafeRatio(sum(x$simMedian), sum(x$observed)) else NA_real_,
simMean = if (tot) sum(x$simMean) else NA_real_, meanRatio = if (tot) med(x$meanRatio) else NA_real_,
meanLo = if (tot && any(is.finite(x$meanRatio))) min(x$meanRatio[is.finite(x$meanRatio)]) else NA_real_,
meanHi = if (tot && any(is.finite(x$meanRatio))) max(x$meanRatio[is.finite(x$meanRatio)]) else NA_real_,
meanLo = if (tot) elfRange(x$meanRatio)[1] else NA_real_, meanHi = if (tot) elfRange(x$meanRatio)[2] else NA_real_,
meanRatioOfSums = if (tot) zeroSafeRatio(sum(x$simMean), sum(x$observed)) else NA_real_,
obsRank = pr$obsRank, nRuns = NA_integer_, nYears = pr$nYears, per1000yr = if (tot) sum(x$per1000yr) else NA_real_,
unit = unname(biasUnits[q]))
Expand Down
35 changes: 21 additions & 14 deletions R/climateResponse.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,26 @@
## Definitions are those of the climate comparison of the extreme-fire-years analysis (climCompare.R); a run is one simulated history of the scored years.

climateMetrics <- c(slope = "climate slope", dry10 = "driest 10% of years", wetHalf = "wetter half of years")
## How each metric is compared with the observed, defined once: a "difference" (sim - obs, 0 is the observed) or a "ratio" (sim / obs, 1 is the observed).
## The per-run value, the observed rank, the `measure` of the results rows and the page's shading all come from this.
climateKind <- c(slope = "difference", dry10 = "ratio", wetHalf = "ratio")
climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- names(climateKind)

#' Climate response of one ELF
#'
#' Three ratios of the simulated to the observed record over the scored years, each computed for every run alone. Area is `area50` (fires of the escape size or
#' 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
#' more, as the area row of the page); a year a run (or the record) lacks counts as no area. The covariate (`elf$covariate`, higher = drier) is standardised over the scored years,
#' so the observed slope is per standard deviation of the covariate over the scored years.
#' \itemize{
#' \item `slope`: the slope of log annual area burned on the standardised covariate, years with fire only; sim / obs.
#' \item `slope`: the slope of log annual area burned on the standardised covariate, years with fire only; reported as the difference sim - obs, in the units of the slope (change in log annual area per standard deviation of the covariate; 0 is the observed response). A ratio of slopes is unstable when the observed slope is near 0, so there is none.
#' \item `dry10`: the area burned in the driest 10% of the scored years (years at or above the 90% quantile of the covariate over the scored years); sim / obs.
#' \item `wetHalf`: the area burned in the wetter half of the scored years (covariate at or below its median); sim / obs.
#' }
#' The area ratios use [zeroSafeRatio()]. A slope is NA with fewer than 3 years with fire, and a ratio of slopes is NA when the observed slope is 0 (to within 1.5e-8) or NA. The single runs are summarised by [runSummary()].
#' The area ratios use [zeroSafeRatio()]. A slope is NA with fewer than 3 years with fire (the difference is then NA); an observed slope of 0 gives a finite difference. The single runs are summarised by [runSummary()]; the observed rank of the slope is the share of runs with a slope below the observed (difference below 0).
#'
#' @param elf An ELF input list ([runWave1()]); without a `covariate` of the scored years there is no result (`NULL`).
#' @return `data.frame`, one row per metric: `level` ("ELF"), `ELF`, `metric`, `observed` (the observed slope, or area in ha), `simMedian` (median over runs of the run's value), `ratio` (median over runs of the
#' run's ratio to the observed), `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`.
#' @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)
Expand All @@ -28,45 +32,48 @@ scoreClimateResponse <- function(elf) {
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))
ratioTo <- function(v) c(slope = if (isTRUE(abs(obs[["slope"]]) > sqrt(.Machine$double.eps))) v[["slope"]] / obs[["slope"]] else NA_real_,
dry10 = zeroSafeRatio(v[["dry10"]], obs[["dry10"]]), wetHalf = zeroSafeRatio(v[["wetHalf"]], obs[["wetHalf"]]))
ratioTo <- function(v) vapply(names(climateKind), function(m) if (climateKind[[m]] == "difference") v[[m]] - obs[[m]] else zeroSafeRatio(v[[m]], obs[[m]]), 0)
runs <- lapply(split(elf$simYears, elf$simYears$run), function(r) values(r$area50[match(years, r$year)]))
v <- do.call(rbind, runs); single <- vapply(runs, ratioTo, numeric(3)); rs <- runSummary(single)
v <- do.call(rbind, runs); single <- vapply(runs, ratioTo, numeric(3)); rs <- runSummary(single, at = climateRef); sr <- runSummary(t(v))
data.frame(level = "ELF", ELF = elf$elf, metric = names(climateMetrics), observed = unname(obs), simMedian = apply(v, 2, stats::median, na.rm = TRUE),
simLo = sr$runLo, simHi = sr$runHi,
ratio = apply(single, 1, medFinite), runLo = rs$runLo, runHi = rs$runHi, obsRank = rs$obsRank,
elfLo = NA_real_, elfHi = NA_real_, nELF = 1L, nNonFinite = 0L, nRuns = length(runs), nYears = length(years), row.names = NULL)
}

#' Climate response of every ELF, and pooled
#'
#' @param elfs List of ELF inputs ([runWave1()]). @return The rows of [scoreClimateResponse()] of every ELF with a covariate, then per metric a pooled row (`level` "pooled", `ELF` "all") from [poolRatios()]:
#' `ratio` the median over ELFs of the ELF ratios, `elfLo`, `elfHi` their range, `nELF` the ELFs, `nNonFinite` those left out as not finite. `NULL` when no ELF has a covariate.
#' `ratio` the median over ELFs of the ELF values (the slope's difference, the area ratios), `elfLo`, `elfHi` their 2.5-97.5% range over ELFs, `nELF` the ELFs, `nNonFinite` those left out as not finite. `NULL` when no ELF has a covariate.
climateTable <- function(elfs) {
x <- do.call(rbind, lapply(elfs, scoreClimateResponse))
if (is.null(x)) return(NULL)
pooled <- do.call(rbind, lapply(names(climateMetrics), function(m) {
pr <- poolRatios(x[x$metric == m, ])
data.frame(level = "pooled", ELF = "all", metric = m, observed = NA_real_, simMedian = NA_real_, ratio = pr$ratio, runLo = NA_real_, runHi = NA_real_, obsRank = pr$obsRank,
data.frame(level = "pooled", ELF = "all", metric = m, observed = NA_real_, simMedian = NA_real_, simLo = NA_real_, simHi = NA_real_, ratio = pr$ratio, runLo = NA_real_, runHi = NA_real_, obsRank = pr$obsRank,
elfLo = pr$elfLo, elfHi = pr$elfHi, nELF = pr$nELF, nNonFinite = pr$nNonFinite, nRuns = NA_integer_, nYears = pr$nYears)
}))
out <- rbind(x, pooled); rownames(out) <- NULL
out
}

## `climate` as rows of the long `results` table of runWave1(): test "C", the metric in `null`, measure "ratio"; `lo` and `hi` are the single-run range (ELF rows) or the range over ELFs (pooled rows)
## `climate` as rows of the long `results` table of runWave1(): test "C", the metric in `null`, measure "ratio" ("difference" for the slope); `lo` and `hi` are the single-run range (ELF rows) or the range over ELFs (pooled rows)
climateResultRows <- function(climate) {
if (is.null(climate)) return(NULL)
p <- climate$level == "pooled"
longRows(climate, "C", climate$metric, "ratio", climate$ratio, ifelse(p, climate$elfLo, climate$runLo), ifelse(p, climate$elfHi, climate$runHi))
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; each metric is a ratio cell, `obsSlope` the observed slope
## 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) {
if (is.null(climate)) return(list())
rowOf <- function(label, x) {
r <- list(elf = label)
for (m in names(climateMetrics)) { z <- x[x$metric == m, ]; r[[m]] <- rangeCell(z, z$level == "pooled") }
r$obsSlope <- signif(x$observed[x$metric == "slope"], 3)
s <- x[x$metric == "slope", ]
r$simSlope <- ratioCell(s$simMedian, s$simLo, s$simHi, NA_real_) # no pooled simulated slope: the cell is empty
r$ref <- as.list(c(climateRef, simSlope = NA_real_)) # what each cell is compared with, for the page's shading
r$obsSlope <- signif(s$observed, 3)
r
}
c(list(rowOf("all: median of ELFs", climate[climate$level == "pooled", ])),
Expand Down
10 changes: 6 additions & 4 deletions R/gates.R
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,12 @@ bootRuns <- function(sim, stat, nBoot = 1000, seed = 1) {

## The spread of single runs, from `single` (one row per statistic, one column per run; a ratio to the observed): 2.5% and 97.5% over the runs
## (`runLo`, `runHi`) and the mid-rank percentile of the observed among the runs (`obsRank`, see bootRuns()); non-finite runs are left out.
runSummary <- function(single) {
q <- matrix(apply(single, 1, stats::quantile, c(0.025, 0.975), na.rm = TRUE, names = FALSE), nrow = 2)
obsRank <- apply(single, 1, function(x) { x <- x[is.finite(x)]; (sum(x < 1) + 0.5 * sum(x == 1)) / length(x) })
list(runLo = q[1, ], runHi = q[2, ], obsRank = obsRank)
## `at` is the value of a statistic that means the observed (1 for a ratio, 0 for a difference), one per row or one for all.
runSummary <- function(single, at = 1) {
q <- matrix(apply(single, 1, quantRange), nrow = 2)
at <- rep_len(at, nrow(single))
obsRank <- vapply(seq_len(nrow(single)), function(i) { x <- single[i, ]; x <- x[is.finite(x)]; (sum(x < at[i]) + 0.5 * sum(x == at[i])) / length(x) }, 0)
list(runLo = q[1, ], runHi = q[2, ], obsRank = stats::setNames(obsRank, rownames(single)))
}

## "value (median-run 95%: lo-hi; single runs 95%: runLo-runHi); observed above X% of N runs" for the detail text
Expand Down
45 changes: 45 additions & 0 deletions R/imports.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#' @rawNamespace import(data.table, except = c("shift"))
NULL


#' @import reproducible
NULL


#' @rawNamespace import(MASS, except = c("area"))
NULL


#' @import withr
NULL


#' @rawNamespace import(ggplot2, except = c("alpha"))
NULL


#' @rawNamespace import(patchwork, except = c("area"))
NULL


#' @rawNamespace import(scales, except = c("rescale"))
NULL


#' @import jsonlite
NULL

#' @import terra
NULL


#' @rawNamespace import(SpaDES.core, except = c(".addChangedAttr", ".addTagsToOutput", ".cacheMessage", ".checkCacheRepo", ".preDigestByClass", ".prepareOutput", ".robustDigest", ".tagsByClass", "clearCache", "Copy", "keepCache", "paddedFloatToChar", "padYears", "showCache", "time<-"))
NULL


#' @import fireregimetools
NULL

#' @import fireSenseUtils
NULL

13 changes: 9 additions & 4 deletions R/ratioTable.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@

medFinite <- function(v) stats::median(v[is.finite(v)])

## The pooled row of ratios: `x` has one row per ELF with `ratio`, `obsRank` and `nYears`. `ratio`: the median over ELFs of the finite ratios, `elfLo`, `elfHi`: their range;
## The range over ELFs: the 2.5% and 97.5% quantiles of the finite values (the same 95% as the range of single runs), NA with none
elfRange <- function(v) quantRange(v[is.finite(v)])
## The 2.5% and 97.5% quantiles (NAs left out; NA, NA with none): the one place of the 95% range
quantRange <- function(v) unname(stats::quantile(v, c(0.025, 0.975), na.rm = TRUE))

## The pooled row of ratios: `x` has one row per ELF with `ratio`, `obsRank` and `nYears`. `ratio`: the median over ELFs of the finite ratios, `elfLo`, `elfHi`: their 2.5-97.5% range (elfRange());
## `nELF`: the ELFs, `nNonFinite`: those left out as not finite; `nYears` summed, `obsRank` the median.
poolRatios <- function(x) {
r <- x$ratio[is.finite(x$ratio)]
list(ratio = medFinite(x$ratio), elfLo = if (length(r)) min(r) else NA_real_, elfHi = if (length(r)) max(r) else NA_real_,
r <- elfRange(x$ratio)
list(ratio = medFinite(x$ratio), elfLo = r[1], elfHi = r[2],
nELF = nrow(x), nNonFinite = sum(!is.finite(x$ratio)), nYears = sum(x$nYears), obsRank = medFinite(x$obsRank))
}

Expand All @@ -15,5 +20,5 @@ longRows <- function(x, test, null, measure, value, lo, hi)
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_)

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