diff --git a/NEWS.md b/NEWS.md index 7161d0e..b5af703 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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. diff --git a/R/bias.R b/R/bias.R index f67e305..179ee4f 100644 --- a/R/bias.R +++ b/R/bias.R @@ -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 @@ -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])) diff --git a/R/climateResponse.R b/R/climateResponse.R index bd4a760..2a3768f 100644 --- a/R/climateResponse.R +++ b/R/climateResponse.R @@ -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) @@ -28,11 +32,11 @@ 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) } @@ -40,33 +44,36 @@ scoreClimateResponse <- function(elf) { #' 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", ])), diff --git a/R/gates.R b/R/gates.R index 89840d9..2acc584 100644 --- a/R/gates.R +++ b/R/gates.R @@ -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 diff --git a/R/imports.R b/R/imports.R new file mode 100644 index 0000000..fadaa9d --- /dev/null +++ b/R/imports.R @@ -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 + diff --git a/R/ratioTable.R b/R/ratioTable.R index d9ace34..c960af9 100644 --- a/R/ratioTable.R +++ b/R/ratioTable.R @@ -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)) } @@ -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) diff --git a/pageTemplate.html b/pageTemplate.html index e31e22a..7d5d7b7 100644 --- a/pageTemplate.html +++ b/pageTemplate.html @@ -132,7 +132,7 @@
Ratio of the median run to the observed record over the scored years; 1 is no bias. The mean columns are the same ratio for the mean over runs (what compounds over a long run; the median is the robust centre). The mean columns have no observed rank. Small numbers: the 95% range of single runs (the "all" row: the range over ELFs); "obs N%": the share of runs below the observed record. Per 1000 yr: how far the median run's total drifts from the observed rate over 1000 years (simulated minus observed; the totals only). "all: median of ELFs" treats every ELF alike; "all: ratio of sums" is dominated by the large ELFs.
+Ratio of the median run to the observed record over the scored years; 1 is no bias. The mean columns are the same ratio for the mean over runs (what compounds over a long run; the median is the robust centre). The mean columns have no observed rank. Small numbers: the 95% range of single runs (the "all" row: the 2.5-97.5% range over ELFs); "obs N%": the share of runs below the observed record. Per 1000 yr: how far the median run's total drifts from the observed rate over 1000 years (simulated minus observed; the totals only). "all: median of ELFs" treats every ELF alike; "all: ratio of sums" is dominated by the large ELFs.
| - | + | + | + | - |
|---|
Simulated over observed, over the scored years; 1 is the observed response. Slope: of log annual area burned on the year's climate covariate (standardised; higher is drier). Driest 10%: area in the years at or above the 90% quantile of the covariate. Wetter half: area in the years at or below its median. Each ratio is the median of the runs; small numbers are the 95% range of single runs (the "all" row: the range over ELFs); "obs N%": the share of runs the observed is above. Area is the area in fires of the escape size or more, as in the area row above. The observed slope is per standard deviation of the climate covariate over the scored years.
+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.