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

* S8 and S9 per parameter set, and the seeded fires as maps. `scoreBySet()` now also scores S8 (size given escape) and S9 (shape given escape) of each set of an in-sample ELF: columns `S8_rho`, `S8_log2ratio`, `S9_aucDiff`, `S9_auc`, `S9_aucDist`, `S9_shareInside`, `S8_nFires`, `S9_nFires`, with `_runLo`/`_runHi` (the ELF rows of `escapeResultRows()`). `elfOfSet()` now keeps only the set's runs in `location$seeded$sizes` and `location$burn` too; before, it subset only `simYears` and `simSizes`. To split the burns by set, `readHindcastLocation()` records the run of each burn map (`burn$runIds`, from `hindcast_reps.csv`, new `burnRunIds()`) and keeps each burned cell's fire (`fire`, its burn ID), and `readHindcastSeeded()` keeps `fire` in `sizes`; the grid also carries its `crs`. New `writeSeededFires()`: `writeOutputs` writes, for each in-sample ELF, `<outputPath>/seededFires/<ELF>/<year>_<start>/observed.tif` and `predicted.tif` (one layer per run, `set<k>_rep<r>`), holding exactly the cells S8 and S9 score (1 burned, 0 burnable and not burned, NA not scored, so lakes are NA), with `fires.csv`; a predicted layer holds only the fire grown from that start. `bySet` defaults to `NA`: score by set when some ELF's runs are of more than one set. The cached ELF reads are rebuilt once.

* 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
31 changes: 27 additions & 4 deletions R/bySet.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,34 @@

#' One ELF's input restricted to one parameter set
#'
#' @param elf An ELF input list ([runWave1()]) whose `simYears` and `simSizes` have a `paramSet` column ([readHindcastSim()]).
#' @param elf An ELF input list ([runWave1()]) whose `simYears` and `simSizes` have a `paramSet` column ([readHindcastSim()]). Its `location`, when there is one, keeps the set's runs too:
#' `seeded$sizes` by `run`, and `burn$sim` by `burn$runIds` (the run of each burn run), renumbered 1..n; without `burn$runIds` the burns cannot be split by set, and `burn` is dropped.
#' @param set The `paramSet` to keep. @return The same list with only that set's runs.
elfOfSet <- function(elf, set) {
elf$simYears <- elf$simYears[elf$simYears$paramSet == set, , drop = FALSE]
elf$simSizes <- elf$simSizes[elf$simSizes$paramSet == set, , drop = FALSE]
runs <- unique(elf$simYears$run); loc <- elf$location
if (!is.null(loc$seeded)) loc$seeded$sizes <- loc$seeded$sizes[loc$seeded$sizes$run %in% runs, , drop = FALSE]
if (!is.null(loc$burn)) loc$burn <- if (!is.null(loc$burn$runIds)) {
keep <- which(loc$burn$runIds %in% runs)
loc$burn$sim <- lapply(loc$burn$sim, function(x) { x <- x[x$run %in% keep, , drop = FALSE]; x$run <- match(x$run, keep); x })
loc$burn$runIds <- loc$burn$runIds[keep]; loc$burn$nRuns <- length(keep); loc$burn
}
elf$location <- loc
elf
}

#' Score each parameter set of an ELF on its own
#'
#' For every `paramSet` of `elf$simYears`: the gates ([runGates()]) and the annual-area skill ([scoreS3()], [skillScore()]), on that set's runs only.
#' The ratios are those of [summariseGates()]: the median run over the observation (area, median of the 10 largest fires, ignitions, escape rate,
#' area per escape), each with the 2.5% and 97.5% of single runs (`_runLo`, `_runHi`).
#' area per escape), each with the 2.5% and 97.5% of single runs (`_runLo`, `_runHi`). An in-sample ELF also has the ELF values of S8 and S9
#' ([scoreS8()], [scoreS9()]) on the set's runs, as the `results` rows of [escapeResultRows()].
#'
#' @param elf An ELF input list with a `paramSet` column in `simYears` and `simSizes`. @param nBoot,seed As [runGates()].
#' @return `data.frame`, one row per set: `ELF`, `paramSet`, `nRuns`, the ratio columns of [summariseGates()], `annualArea_skillN1`,
#' `annualArea_skillN2` (skill of the set's annual area against the null N1 and N2), and `G2`, `G4`, `G6` (pass).
#' `annualArea_skillN2` (skill of the set's annual area against the null N1 and N2), and `G2`, `G4`, `G6` (pass); in-sample, also
#' `<test>_<measure>` with `_runLo`, `_runHi` for each ELF measure of S8 and S9 (e.g. `S8_rho`, `S9_aucDiff`, `S8_nFires`; NA where it has no range).
scoreBySet <- function(elf, nBoot = 1000, seed = 1) {
do.call(rbind, lapply(sort(unique(elf$simYears$paramSet)), function(s) {
e <- elfOfSet(elf, s)
Expand All @@ -27,6 +38,18 @@ scoreBySet <- function(elf, nBoot = 1000, seed = 1) {
skill <- function(nl) { x <- sk[sk$null == nl, ]; skillScore(x$lossModel, x$lossNull) }
pass <- stats::setNames(lapply(c("G2", "G4", "G6"), function(id) g$pass[g$gate == id]), c("G2", "G4", "G6"))
cbind(summariseGates(g), paramSet = s, nRuns = length(unique(e$simYears$run)),
annualArea_skillN1 = skill("N1"), annualArea_skillN2 = skill("N2"), as.data.frame(pass))
annualArea_skillN1 = skill("N1"), annualArea_skillN2 = skill("N2"), as.data.frame(pass), escapeBySetColumns(e, nBoot, seed))
}))
}

## The ELF rows of S8 and S9 ([escapeResultRows()]) of one set as one row of columns `<test>_<measure>`, `_runLo`, `_runHi`; a 0-column data.frame for an ELF that is not in-sample
escapeBySetColumns <- function(e, nBoot, seed) {
if (!isTRUE(e$inSample)) return(data.frame(row.names = 1L))
tag <- function(x) if (!is.null(x)) cbind(ELF = e$elf, x)
s8 <- scoreS8(e); s9 <- scoreS9(e)
r <- escapeResultRows(list(S8 = tag(s8$scores), S9 = tag(s9$scores)), list(S8 = tag(s8$runs), S9 = tag(s9$runs)), nBoot, seed)
r <- r[r$level == "ELF", , drop = FALSE]
if (is.null(r) || !nrow(r)) return(data.frame(row.names = 1L))
nm <- paste(r$test, r$measure, sep = "_")
as.data.frame(as.list(stats::setNames(c(r$value, r$lo, r$hi), c(nm, paste0(nm, "_runLo"), paste0(nm, "_runHi")))))
}
40 changes: 39 additions & 1 deletion R/escapeTests.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## S8 asks how big each seeded fire gets, S9 what shape it takes. Nothing here knows a simulator: the adapter (readFireSenseHindcast.R) builds the plain tables below.
## An ELF input carries `inSample = TRUE` and, in `location`, `burn$grid` and `burn$gridCell` (the grid and the grid cell of each scored cell 1..nCells; see the top of spatialTests.R) and
## seeded: `fires` (`data.frame(year, start, obsHa)`: one row per observed escape that the run seeded, `start` its start as a grid cell, `obsHa` the observed size of the whole fire),
## `sizes` (`data.frame(year, run, start, ha)`: the final size of the fire that grew from each seeded start, in every run),
## `sizes` (`data.frame(year, run, start, ha)`: the final size of the fire that grew from each seeded start, in every run; the fireSense reader adds `fire`, the fire's burn ID in its run),
## `obsCells` (`data.frame(year, start, cell)`: the scored cells the observed fire burned).

## Squared distance of each cell of `xy` (list x, y) to `centre` (c(x, y))
Expand Down Expand Up @@ -105,3 +105,41 @@ escapePageRows <- function(results) {
list(elf = label, rho = resultCell(z, "S8", "rho"), size = resultCell(z, "S8", "log2ratio"), n8 = n(z, "S8"), diff = resultCell(z, "S9", "aucDiff"), auc = resultCell(z, "S9", "auc"),
dist = resultCell(z, "S9", "aucDist"), inside = resultCell(z, "S9", "shareInside"), n9 = n(z, "S9")))
}

#' The seeded fires as maps: each observed fire and the runs' fires grown from its start
#'
#' For other scores of the same fires (e.g. a fractions skill score): per seeded observed escape, the cells S8 and S9 score, as GeoTIFFs on the hindcast grid, cropped to the observed and
#' simulated fire plus `margin` cells. A cell is 1 where the fire burned it, 0 where it is a scored cell (the ELF's burnable core) that did not burn, and NA where it is not scored (not burnable,
#' or outside the core), as in S9. `observed.tif` has one layer; `predicted.tif` one per run, named `set<paramSet>_rep<rep>`, holding only the fire that grew from this start in that run
#' (its burn ID), not the other fires of the year. Files go to `<dir>/<ELF>/<year>_<start>/`, with `<dir>/<ELF>/fires.csv` (`fireId`, `year`, `start`: the start cell of the grid, `obsHa`:
#' the observed size of the whole fire on burnable cells, as S8, `obsCells`: its scored cells, as in `observed.tif`).
#' @param elf ELF input list with `location$seeded` (with `fire` in `sizes`) and `location$burn` (with `runIds`, `fire` in `sim` and `crs` in `grid`), as [readFireSenseHindcast()] builds it.
#' @param dir Folder. @param margin Cells around the fires. @return The `fires.csv` table, invisibly; `NULL` for an ELF without them.
writeSeededFires <- function(elf, dir, margin = 10L) {
sd <- elf$location$seeded; b <- elf$location$burn
if (is.null(sd) || is.null(b$runIds) || !"fire" %in% names(sd$sizes)) return(invisible(NULL))
g <- b$grid; tmpl <- terra::rast(nrows = g$nrow, ncols = g$ncol, extent = terra::ext(g$xmin, g$xmax, g$ymin, g$ymax), crs = g$crs)
scored <- rep(NA_integer_, terra::ncell(tmpl)); scored[b$gridCell] <- 0L
bands <- with(hindcastRunParts(b$runIds), paste0("set", paramSet, "_rep", rep))
out <- file.path(dir, elf$elf); dir.create(out, recursive = TRUE, showWarnings = FALSE)
rows <- lapply(seq_len(nrow(sd$fires)), function(i) {
y <- sd$fires$year[i]; st <- sd$fires$start[i]; s <- b$sim[[as.character(y)]]
obs <- b$gridCell[sd$obsCells$cell[sd$obsCells$year == y & sd$obsCells$start == st]]
if (!length(obs) || is.null(s)) return(NULL)
z <- sd$sizes[sd$sizes$year == y & sd$sizes$start == st, , drop = FALSE]
sim <- lapply(seq_len(b$nRuns), function(r) b$gridCell[s$cell[s$run == r & s$fire %in% z$fire[z$run == b$runIds[r]]]])
all <- c(obs, unlist(sim)); rr <- range(terra::rowFromCell(tmpl, all)); cc <- range(terra::colFromCell(tmpl, all))
r <- terra::crop(tmpl, terra::ext(tmpl, cells = terra::cellFromRowColCombine(tmpl, c(max(1L, rr[1] - margin), min(g$nrow, rr[2] + margin)),
c(max(1L, cc[1] - margin), min(g$ncol, cc[2] + margin)))))
win <- terra::cells(tmpl, terra::ext(r)) # the window's cells of the grid, in the order of r's values
layer <- function(cells) { v <- scored[win]; v[match(cells, win)] <- 1L; v }
id <- paste0(y, "_", st); d <- file.path(out, id); dir.create(d, showWarnings = FALSE)
wr <- function(x, nm, f) { names(x) <- nm; terra::writeRaster(x, file.path(d, f), datatype = "INT1U", gdal = "COMPRESS=DEFLATE", overwrite = TRUE) }
wr(terra::setValues(r, layer(obs)), "observed", "observed.tif")
wr(terra::rast(lapply(sim, function(cl) terra::setValues(r, layer(cl)))), bands, "predicted.tif")
data.frame(fireId = id, year = y, start = st, obsHa = sd$fires$obsHa[i], obsCells = length(obs))
})
fires <- do.call(rbind, rows)
utils::write.csv(fires, file.path(out, "fires.csv"), row.names = FALSE)
invisible(fires)
}
28 changes: 21 additions & 7 deletions R/readFireSenseHindcast.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ hindcastFinishedYears <- function(hindcastDir, elf, years = seq(1986L, 2021L, 5L
## The parameter set of the rows of a hindcast file (its `paramSet` column when it has one, else the set folder `s`) and the run (`set * 1000 + rep`)
hindcastSet <- function(x, s) if ("paramSet" %in% names(x)) as.integer(x$paramSet) else rep(as.integer(s), NROW(x))
hindcastRun <- function(x, s) hindcastSet(x, s) * 1000L + x$rep
## The set and rep of runs numbered by hindcastRun()
hindcastRunParts <- function(run) data.frame(paramSet = run %/% 1000L, rep = run %% 1000L)

## The reps and the fire sizes of one set folder `d`
readHindcastSetFiles <- function(d) list(reps = fread0(file.path(d, "hindcast_reps.csv")), sizes = fread0(file.path(d, "hindcast_sizes.csv")))
Expand Down Expand Up @@ -139,7 +141,7 @@ readHindcastObserved <- function(rec, hindcastDir, elf, scored, minHa) {
}

## A raster's grid as the `grid` of the ELF input (see the top of R/spatialTests.R)
gridOf <- function(r) list(nrow = terra::nrow(r), ncol = terra::ncol(r), xmin = terra::xmin(r), xmax = terra::xmax(r), ymin = terra::ymin(r), ymax = terra::ymax(r))
gridOf <- function(r) list(nrow = terra::nrow(r), ncol = terra::ncol(r), xmin = terra::xmin(r), xmax = terra::xmax(r), ymin = terra::ymin(r), ymax = terra::ymax(r), crs = terra::crs(r))
## For each cell of a grid of `n` cells, its number among the scored cells `scoredCells` (0 where it is not scored)
toScoredIndex <- function(scoredCells, n) { i <- integer(n); i[scoredCells] <- seq_along(scoredCells); i }

Expand All @@ -149,7 +151,8 @@ toScoredIndex <- function(scoredCells, n) { i <- integer(n); i[scoredCells] <- s
#' `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` (`burn` also has `grid` and `gridCell`, the grid and the grid cell of each scored cell); `NULL` when the hindcast has no ignition maps.
#' @return `list(ign, burn)`, see the top of `R/spatialTests.R` (`burn` also has `grid` and `gridCell`, the grid and the grid cell of each scored cell, `runIds`, the run of [readHindcastSim()] of each burn run,
#' and in `sim` a `fire` column, the fire's number in its run: its burn ID); `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")))))
Expand All @@ -169,13 +172,24 @@ readHindcastLocation <- function(rec, hindcastDir, elf, scored, sets, core) {
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))
burn <- do.call(rbind, lapply(seq_along(ids), function(r) {
v <- terra::values(terra::rast(ids[r]))[, 1]; g <- which(!is.na(v)); i <- toScored[g]
data.frame(cell = i[i > 0], run = rep(r, sum(i > 0)), fire = as.integer(v[g][i > 0])) }))
list(ign = ign, burn = burn, nRuns = length(ids), runIds = burnRunIds(ids))
})
runIds <- perYear[[1]]$runIds
if (!all(vapply(perYear, function(x) identical(x$runIds, runIds), TRUE))) stop(elf, ": the burn maps of the scored years are not of the same runs")
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"), grid = grid, gridCell = scoredCells))
burn = list(nCells = length(scoredCells), nRuns = perYear[[1]]$nRuns, runIds = runIds, obs = obsBurn, sim = lapply(perYear, `[[`, "burn"), grid = grid, gridCell = scoredCells))
}

## The run (as `run` of [readHindcastSim()]) of each `hindcast_burnID_rep<NN>.tif` of `files`: rep NN of the `hindcast_reps.csv` beside it
burnRunIds <- function(files) unsplit(lapply(split(files, dirname(files)), function(f) {
r <- readHindcastSetFiles(dirname(f[1]))$reps; i <- match(as.integer(sub("^hindcast_burnID_rep(\\d+)\\.tif$", "\\1", basename(f))), r$rep)
if (anyNA(i)) stop(paste(f[is.na(i)], collapse = ", "), " has no rep in hindcast_reps.csv")
hindcastRun(r[i, , drop = FALSE], as.integer(basename(dirname(f[1]))))
}), dirname(files))

#' Where each simulated fire started
#'
#' `fireSense_burnSummary.csv` of every set has one row per fire: its start cell `igLoc` (a cell of the hindcast grid), its time `year` (year + 0.001 x the rep's index, the `time` of `hindcast_reps.csv`) and its size.
Expand Down Expand Up @@ -234,7 +248,7 @@ readHindcastSeeded <- function(starts, hindcastDir, elf, scored, sets, flammable
if (sum(vapply(one, `[[`, 0, "dropped"))) message(elf, ": ", sum(vapply(one, `[[`, 0, "dropped")), " seeded escapes start in no observed polygon and are not scored in S8 and S9")
fires <- do.call(rbind, lapply(one, `[[`, "fires"))
list(fires = fires, obsCells = do.call(rbind, lapply(one, `[[`, "obsCells")),
sizes = merge(starts[starts$year %in% scored, c("year", "run", "start", "ha")], fires[c("year", "start")], by = c("year", "start"))[c("year", "run", "start", "ha")])
sizes = merge(starts[starts$year %in% scored, c("year", "run", "start", "ha", "fire")], fires[c("year", "start")], by = c("year", "start"))[c("year", "run", "start", "ha", "fire")])
}

#' ELF median of the fit's climate covariate (CMD) for every year of the record
Expand Down Expand Up @@ -327,7 +341,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",
"readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastSetFiles", "rasterizedValues", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded")
"readHindcastLocation", "ignitionYear", "hindcastSet", "hindcastRun", "gridOf", "toScoredIndex", "readHindcastSetFiles", "rasterizedValues", "readHindcastStarts", "hindcastInSample", "readHindcastSeeded", "burnRunIds", "hindcastRunParts")

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