Skip to content
Open
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
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# fireSimulator_validation (development version)

* New residual climate signal: does what the simulation gets wrong (log(simulated / observed) of annual area burned, mean and median fire size, per ELF and scored year) still trend with the year's climate? `residualClimateTables()` regresses each residual on the within-ELF z-score of every annual climate covariate the hindcast has (CMD, CMDsm, CMDsp, cumMDC, Tmaxsm, PPTsm; `readHindcastCovariates()`) and on the ELF's own spread-fit climate variable, with the slope after the own variable in the model, and pools the slopes over ELFs (median and a random-effects summary). A year with no observed fire has no area or size residual (the offset area residual, `minHa` added to both, keeps it). `spreadClimateSD()` gives the year-to-year SD of the fitted spread climate term (coefficient x scaled covariate) next to `yearSpreadSD`; it is NA without spread coefficients, so other simulators are scored too. `runWave1()` returns `residualClimate`; the module writes `residualClimate_years.csv`, `residualClimate_slopes.csv`, `residualClimate_pooled.csv` and `residualClimate_spreadSD.csv` to `outputPath`. `readLedgerRow()` also returns the kept sets' coefficients (`params`) and `covMinMax`; the ELF inputs gain `covariates`. Needs fireSenseUtils >= 0.2.3.9196.

* In-sample hindcasts (they spread the observed escapes from their real starts and years, `FS_HC_IGNITIONS=observedEscapes`): S7 is no longer scored, because its whole-ELF AUC (about 0.9) only shows that the fires start where the observed ones did. New tests S8 and S9 score what a fire does once it has escaped (`R/escapeTests.R`). S8, size given escape: for each seeded observed escape, the median over runs of the final size of the fire that grew from it against the fire's observed size; per ELF the Spearman correlation `rho` (single-run range), the median `log2ratio` of simulated over observed size and `nFires`. S9, shape given escape: for each seeded fire with N observed cells, the circle around its start that holds 2N burnable core cells; the AUC of the share of runs that burned each cell for the cells the fire burned against the others (`aucOf()`), reported as the median over fires with a single-run range, beside a distance-only baseline `aucDist` (each cell of the circle scored by its closeness to the start) and the headline `aucDiff` (model AUC minus baseline AUC), `shareInside` (the share of the fire's cells inside the circle, since cells outside are not counted) and `nFires`. Both are pooled over ELFs with `bootstrapPooled()` and are rows of `wave1_results.csv` (tests `S8`, `S9`); the page has a "Given an escape" table, shown only when there are such rows. A run is in-sample when every run of every year with a fire started the same fires from the same cells (`hindcastInSample()`, read from `fireSense_burnSummary.csv`: the hindcast files record no setting, only the folder name does); `readFireSenseHindcast()` has a new argument `inSample` (default `NA`: detect) and puts `inSample` and `location$seeded` in the ELF input. A fire is tied to its observed escape by its start cell (`igLoc` of `fireSense_burnSummary.csv`, in the order of `hindcast_sizes.csv`), and the start to the observed polygon that holds it. S8 and S9 are not scored for normal runs: their fires do not start where the observed ones did.

* Fix: the per-ELF `auc` rows of S7 were NA whenever one scored year had no observed burn (that year's AUC is undefined, and the ELF's median was taken over it). The ELF row is now the median over the years with an AUC, as the pooled row already was.
Expand Down
33 changes: 26 additions & 7 deletions R/climateResponse.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,33 @@ climateRef <- c(difference = 0, ratio = 1)[climateKind]; names(climateRef) <- na
## the scored years and the covariate standardised over them (`list(years, z)`), or NULL when the ELF has no usable covariate
climateInputs <- 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)
list(years = years, z = (cv - mean(cv)) / stats::sd(cv))
z <- zScore(covariateOf(elf, years))
if (is.null(elf$covariate) || anyNA(z)) return(NULL)
list(years = years, z = z)
}

## `v` standardised over its years (mean 0, SD 1); all NA with a missing value, fewer than 3 years or a constant
zScore <- function(v) if (anyNA(v) || length(v) < 3 || stats::sd(v) == 0) rep(NA_real_, length(v)) else (v - mean(v)) / stats::sd(v)

## log(sim / obs) with an offset added to both (0: none); NA where it is not finite (a quantity of 0 without offset)
logRatio <- function(sim, obs, offset = 0) { r <- log((sim + offset) / (obs + offset)); r[!is.finite(r)] <- NA_real_; r }

## the median over runs of the area of each of `years` (0 for a year without runs)
medianAreaBy <- function(elf, years) vapply(years, function(y) { a <- elf$simYears$area50[elf$simYears$year == y]; if (length(a)) stats::median(a) else 0 }, 0)

## the slope of `y` on `z` (and its standard error and the n of years), with `z2` also in the model when given; NA with fewer than `minN` finite years or a constant covariate
olsSlope <- function(y, z, z2 = NULL, minN = 8L) {
d <- data.frame(y = y, z = z); if (!is.null(z2)) d$z2 <- z2
d <- d[stats::complete.cases(d) & is.finite(d$y), , drop = FALSE]
out <- c(slope = NA_real_, se = NA_real_, n = nrow(d))
if (nrow(d) < minN || any(vapply(d[-1], stats::sd, 0) == 0)) return(out)
f <- stats::coef(suppressWarnings(summary(stats::lm(if (is.null(z2)) y ~ z else y ~ z + z2, d)))) # a perfect fit (toy data) warns about its SE
if ("z" %in% rownames(f)) out[c("slope", "se")] <- f["z", 1:2]
out
}

## 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]) }
logSlope <- function(y, z) unname(olsSlope(y, z, minN = 3L)[["slope"]])

## 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).
Expand Down Expand Up @@ -184,11 +204,10 @@ 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)
data.frame(ELF = e$elf, year = g$years, sim = medianAreaBy(e, g$years), 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)))))
stat <- function(d) c(ratio = if (sum(d$obs) > 0) sum(d$sim) / sum(d$obs) else NA_real_, medianRatio = exp(stats::median(logRatio(d$sim, d$obs, 1))))
do.call(rbind, lapply(names(climateGroups), function(m) {
d <- yrs[yrs[[climateGroups[[m]]]], ]
if (!nrow(d)) return(NULL)
Expand Down
24 changes: 18 additions & 6 deletions R/readFireSenseHindcast.R
Original file line number Diff line number Diff line change
Expand Up @@ -255,16 +255,26 @@ readHindcastCovariate <- function(hindcastDir, elf, core, variable = "CMD") {
data.frame(year = as.integer(sub(".*_(\\d{4})$", "\\1", names(r))), value = v)
}

#' The ledger row of an ELF: what the gates need
#' ELF medians of every annual climate covariate the fit can use
#'
#' [readHindcastCovariate()] for each variable of `fireSenseUtils::climateCovRanges` the hindcast has the file of; a variable without one is left out.
#' @param hindcastDir,elf,core As [readHindcastCovariate()]. @param variables Climate variables.
#' @return Named list of `data.frame(year, value)`.
readHindcastCovariates <- function(hindcastDir, elf, core, variables = names(fireSenseUtils::climateCovRanges))
Filter(Negate(is.null), stats::setNames(lapply(variables, function(v) tryCatch(readHindcastCovariate(hindcastDir, elf, core, v), error = function(e) NULL)), variables))

#' The ledger row of an ELF: what the gates and the residual climate signal need
#'
#' @param ledgerFile A spread-fit ledger `.rds` (`fireSenseParams_*.rds`; the caller downloads it). @param elf ELF (`polygonID`).
#' @return List: `objective` (`objFunVal` of the kept sets), `pc` (`maxAsymptote` of each kept set) and `p50`
#' (`NULL` when the ledger has no power-law columns).
#' @return List: `objective` (`objFunVal` of the kept sets), `pc` (`maxAsymptote` of each kept set), `p50`
#' (`NULL` when the ledger has no power-law columns), `params` (the kept sets' coefficients, one row per set) and `covMinMax`
#' (`covMinMax_spread`, the ranges the covariates were scaled with; `NULL` when the ledger has none).
readLedgerRow <- function(ledgerFile, elf) {
sp <- readRDS(ledgerFile); i <- which(sp$polygonID == elf)[1]
p <- sp$params[[i]]
list(objective = as.numeric(unlist(sp$objFunVal[[i]])), pc = as.numeric(p[["maxAsymptote"]]),
p50 = if ("powerLawPc50_spread" %in% names(sp)) sp$powerLawPc50_spread[[i]] else NULL)
p50 = if ("powerLawPc50_spread" %in% names(sp)) sp$powerLawPc50_spread[[i]] else NULL,
params = as.data.frame(p), covMinMax = if ("covMinMax_spread" %in% names(sp)) as.data.frame(sp$covMinMax_spread[[i]]))
}

#' Burnable area and burn rate of an ELF
Expand Down Expand Up @@ -306,10 +316,12 @@ readFireSenseHindcast <- function(elf, hindcastDir, ledgerFile = NULL, nfdbPath,
starts <- readHindcastStarts(hindcastDir, elf, done, sets)
if (is.na(inSample)) inSample <- hindcastInSample(starts, sim$simYears)
if (inSample && !is.null(location) && !is.null(starts)) location$seeded <- readHindcastSeeded(starts, hindcastDir, elf, done, sets, hindcastFlammable(burnMap), location$burn$gridCell)
covariates <- readHindcastCovariates(covariateDir, elf, core)
if (is.null(covariates$CMD)) readHindcastCovariate(covariateDir, elf, core) # the fit's covariate: stops, naming the missing file
fit <- if (is.null(ledgerFile)) list() else readLedgerRow(ledgerFile, elf)
fit$fitAreaHa <- obs$fitAreaHa; fit$totalAreaHa <- obs$nbacAreaHa
c(list(elf = elf), sim, obs[c("obsYears", "obsSizes", "escapeSizeHa", "fireCauses")], burnRate(core, obs$obsYears),
list(covariate = readHindcastCovariate(covariateDir, elf, core), fit = fit, location = location, inSample = inSample))
list(covariate = covariates$CMD, covariates = covariates, fit = fit, location = location, inSample = inSample))
}

#' The files [readFireSenseHindcast()] reads for one ELF
Expand All @@ -326,7 +338,7 @@ hindcastReadFiles <- function(elf, hindcastDir, inputsDir, covariateDir, ledgerF

## the inner functions readFireSenseHindcast() calls: Cache() sees the body of the function it is given, not of these
readerCallees <- c("hindcastFinishedYears", "readHindcastSim", "hindcastBurnMap", "hindcastCore", "hindcastFlammable", "observedRecord",
"buildObservedRecord", "readHindcastObserved", "readLedgerRow", "burnRate", "readHindcastCovariate", "fread0",
"buildObservedRecord", "readHindcastObserved", "readLedgerRow", "burnRate", "readHindcastCovariate", "readHindcastCovariates", "fread0",
"readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastSetFiles", "rasterizedValues", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded")

#' Read every finished ELF's hindcast, each read cached
Expand Down
Loading
Loading