Score zone metrics — program-area composite + previous-version equivalence gate

Published

2026-11-06

Aggregate the composite components to zones and compute the program-area score (v7’s distinct path, not a roll-up of the cell composite):

  1. component → zone = SUM(cm.val × pct_covered) / SUM(pct_covered)
  2. PA pct_area down-weight: val × (data_coverage / total_coverage) (backs up _prepctareaweighting)
  3. PA score = SUM(val)/COUNT(val) (plain mean) of the pct_area-weighted components

Then the pra_score_delta gate: compare the v8 PA composite to v7’s per program area.

1 Design

Code
flowchart LR
  cm["cell_metric components"] --> za["component → PA<br/>Σ(val·cov)/Σcov"]
  za --> pw["pct_area down-weight"]
  pw --> sc["PA composite score"]
  sc --> zm[("zone_metric (PA rows)<br/>sdm.duckdb")]
  zm --> gate["pra_score_delta<br/>{ver} vs {ver_prev} gate"]
  zm --> mf["hash_query(zone_metric)<br/>→ content-addressed manifest"]
flowchart LR
  cm["cell_metric components"] --> za["component → PA<br/>Σ(val·cov)/Σcov"]
  za --> pw["pct_area down-weight"]
  pw --> sc["PA composite score"]
  sc --> zm[("zone_metric (PA rows)<br/>sdm.duckdb")]
  zm --> gate["pra_score_delta<br/>{ver} vs {ver_prev} gate"]
  zm --> mf["hash_query(zone_metric)<br/>→ content-addressed manifest"]
Figure 1: Aggregate components to program areas (coverage-weighted, pct_area down-weight) → PA composite + v7 gate

2 Setup

Code
# REDO_ZONE_TAXON=1: rebuild ONLY the per-zone species list (msens::build_zone_taxon) on an existing scored version
# and leave zone_metric / cell_metric / the manifest untouched. v8's zone_taxon (cloned into v10, published) was
# built against an earlier subregion geometry and never rebuilt: no Atlantic rows, a third of the Pacific ones
# (found by the v11 control run, 2026-10-30). The share columns on zone_taxon are re-set by score_share_metrics.
redo_zone_taxon_only <- nzchar(Sys.getenv("REDO_ZONE_TAXON"))

librarian::shelf(DBI, dplyr, duckdb, fs, glue, here, jsonlite, logger, sf, quiet = T)
source(here("libs/paths.R")); source(here("libs/vars.R"))
manifest <- here("data/manifests/score_zone_metrics.json"); dir_create(path_dir(manifest))
pa_gpkg  <- glue("{dir_data}/derived/{ver_prev}/ply_programareas_2026_{ver_prev}.gpkg")
stopifnot(file_exists(sdm_db), file_exists(pa_gpkg))

con <- dbConnect(duckdb(sdm_db))
mseq_of <- function(k) dbGetQuery(con, glue("SELECT metric_seq FROM metric WHERE metric_key='{k}'"))$metric_seq[1]
mseq_new <- function(k, desc="") { ex<-dbGetQuery(con,glue("SELECT metric_seq FROM metric WHERE metric_key='{k}'"))
  s <- if(nrow(ex)) ex$metric_seq[1] else { s0<-dbGetQuery(con,"SELECT coalesce(max(metric_seq),0)+1 s FROM metric")$s
    dbExecute(con,glue("INSERT INTO metric VALUES ({s0},'{k}','{desc}')")); s0 }
  dbExecute(con, glue("DELETE FROM zone_metric WHERE metric_seq={s} AND zone_seq IN (SELECT zone_seq FROM zone WHERE fld IN ({flds_sql}))")); s }

stopifnot("msens >= 0.61.1 (components_registry)" = packageVersion("msens") >= "0.61.1")
sp_cats   <- msens::components_registry() |> dplyr::filter(kind == "species", key != "other") |> dplyr::pull(key)
comp_keys <- c(glue("extrisk_{sp_cats}_ecoregion_rescaled"), "primprod_ecoregion_rescaled")
comp_seqs <- sapply(comp_keys, mseq_of)

# Aggregate over EVERY zone set in this release, not only its Program Areas.
# zone now carries zone_set_key, so a release is scored over each registered
# spatial unit and one unit becomes comparable across releases. Program-Area
# results are unaffected: the aggregation is per zone_seq and independent
# across zones, so widening the scope only ADDS rows.
zone_flds <- dbGetQuery(con, "SELECT DISTINCT fld FROM zone ORDER BY 1")$fld
flds_sql  <- paste(sprintf("'%s'", zone_flds), collapse = ", ")
log_info("scoring zone fields: {paste(zone_flds, collapse=', ')}")

3 Component → program-area (coverage-weighted mean) + pct_area down-weight

Code
for (k in comp_keys) {
  bs <- mseq_of(k)
  bk <- mseq_new(glue("{k}_prepctareaweighting"), glue("pre-pct_area backup of {k}"))
  # 2a coverage-weighted mean over PA cells, into zone_metric (this metric_seq, PA zones)
  dbExecute(con, glue("DELETE FROM zone_metric WHERE metric_seq={bs} AND zone_seq IN (SELECT zone_seq FROM zone WHERE fld IN ({flds_sql}))"))
  dbExecute(con, glue("INSERT INTO zone_metric (zone_seq, metric_seq, val)
    SELECT zc.zone_seq, {bs}, SUM(cm.val*zc.pct_covered)/SUM(zc.pct_covered)
    FROM zone_cell zc JOIN zone z USING(zone_seq) JOIN cell_metric cm ON zc.cell_id=cm.cell_id
    WHERE z.fld IN ({flds_sql}) AND cm.metric_seq={bs} AND cm.val IS NOT NULL
    GROUP BY zc.zone_seq"))
  # backup pre-weight val
  dbExecute(con, glue("INSERT INTO zone_metric (zone_seq, metric_seq, val)
    SELECT zone_seq, {bk}, val FROM zone_metric WHERE metric_seq={bs}
      AND zone_seq IN (SELECT zone_seq FROM zone WHERE fld IN ({flds_sql}))"))
  # 2b pct_area = (coverage of cells with data for this metric) / (coverage of all cells in zone); val *= pct_area
  dbExecute(con, glue("UPDATE zone_metric zm SET val = val * (
      SELECT SUM(zc.pct_covered) FILTER (WHERE cm.val IS NOT NULL) * 1.0 / SUM(zc.pct_covered)
      FROM zone_cell zc LEFT JOIN cell_metric cm ON zc.cell_id=cm.cell_id AND cm.metric_seq={bs}
      WHERE zc.zone_seq = zm.zone_seq)
    WHERE zm.metric_seq={bs} AND zm.zone_seq IN (SELECT zone_seq FROM zone WHERE fld IN ({flds_sql}))"))
}
log_info("zone components + pct_area done for {length(comp_keys)} metrics")

4 Program-area composite score

Code
sc <- mseq_new("score_extriskspcat_primprod_ecoregionrescaled_equalweights", "Equal-weight composite (PA)")
seqs_sql <- paste(comp_seqs, collapse=",")
dbExecute(con, glue("INSERT INTO zone_metric (zone_seq, metric_seq, val)
  SELECT zone_seq, {sc}, SUM(val)/COUNT(val)
  FROM zone_metric
  WHERE metric_seq IN ({seqs_sql}) AND val IS NOT NULL
    AND zone_seq IN (SELECT zone_seq FROM zone WHERE fld IN ({flds_sql}))
  GROUP BY zone_seq"))
[1] 37
Code
# PA-only: the v7 equivalence gate compares Program Areas, and the composite is
# now computed for every zone set
v8_pa <- dbGetQuery(con, glue("SELECT z.val AS programarea_key, round(zm.val,2) AS score_new
  FROM zone z JOIN zone_metric zm USING(zone_seq)
  WHERE zm.metric_seq={sc} AND z.fld='programarea_key' ORDER BY 1"))
# content fingerprint of the zone_metric output table (before disconnect)
zm_hash <- msens::hash_query(con, "zone_metric")
dbDisconnect(con, shutdown=TRUE)

5 Zone × taxon table (what the apps read)

zone_taxon is the per-zone species list the scores app shows (and downloads as CSV). It is precomputed here, not aggregated in the app: the server holds only the KB-sized serve.duckdb, whose model_cell is a view over S3 Parquet partitioned by mdl_id for per-model point reads (titiler tiles). A zone-wide aggregation there would have to list and scan the whole ~580M-row dataset over HTTPS, and in practice fails outright (IO Error: ... HTTP GET .../serve/model_cell/). v7 shipped such a table; v8 dropped it, which is what left the app’s Table of Species broken.

Rules live in msens::species_for_zone() / build_zone_taxon() and are unit-tested against synthetic v7 and v8 fixtures, so this notebook and the tests cannot drift.

Code
# the pa_score chunk closes `con`; reopen for this step (under REDO_ZONE_TAXON it was never opened for metrics)
if (exists("con") && inherits(con, "DBIConnection") && dbIsValid(con)) try(dbDisconnect(con, shutdown = TRUE), silent = TRUE)
con <- dbConnect(duckdb(sdm_db))
if (redo_zone_taxon_only) log_info("REDO_ZONE_TAXON: rebuilding zone_taxon only; zone_metric, cell_metric and the manifest are untouched")
n_zt <- msens::build_zone_taxon(con)
d_zt <- tbl(con, "zone_taxon") |>
  group_by(zone_fld) |>
  summarize(n_zones = n_distinct(zone_value), n_rows = n(), .groups = "drop") |>
  collect()
log_info("zone_taxon: {n_zt} rows across {sum(d_zt$n_zones)} zones")
dbDisconnect(con, shutdown = TRUE)
d_zt
# A tibble: 3 × 3
  zone_fld        n_zones n_rows
  <chr>             <dbl>  <dbl>
1 subregion_key         5  45346
2 ecoregion_key        12  51526
3 programarea_key      20  35337

6 v7 equivalence gate (pra_score_delta)

Code
v7_pa <- st_read(pa_gpkg, quiet=TRUE) |> st_drop_geometry() |>
  transmute(programarea_key, score_prev = round(score_extriskspcat_primprod_ecoregionrescaled_equalweights, 2))
cmp <- v8_pa |> inner_join(v7_pa, by="programarea_key") |>
  mutate(delta = round(score_new - score_prev, 2)) |> arrange(desc(abs(delta)))
msens::report_table(cmp, caption = glue("program-area score: {ver} (score_new) vs {ver_prev} (score_prev)"))
program-area score: v11 (score_new) vs v10 (score_prev)
programarea_key score_new score_prev delta
GOA 25.04 39.5 -14.46
NAV 17.69 27.3 -9.61
ALA 20.77 28.3 -7.53
GEO 27.40 33.9 -6.50
COK 46.94 52.6 -5.66
MAT 19.43 24.9 -5.47
SOC 25.03 29.7 -4.67
NOR 24.66 29.0 -4.34
BOW 14.80 18.4 -3.60
NOC 17.33 20.7 -3.37
KOD 28.98 32.1 -3.12
CEC 19.27 21.9 -2.63
CHU 27.47 24.9 2.57
ALB 10.12 12.3 -2.18
GAB 24.24 25.7 -1.46
GAA 31.67 33.1 -1.43
HOP 51.28 52.7 -1.42
SHU 29.09 29.7 -0.61
BFT 11.80 11.3 0.50
HAR 7.66 7.5 0.16
Code
gate <- with(cmp, list(n=nrow(cmp), mean_abs=round(mean(abs(delta)),2), max_abs=round(max(abs(delta)),2),
  rmse=round(sqrt(mean(delta^2)),2), cor=round(cor(score_new, score_prev),3)))
str(gate)
List of 5
 $ n       : int 20
 $ mean_abs: num 4.06
 $ max_abs : num 14.5
 $ rmse    : num 5.3
 $ cor     : num 0.944
Code
# content-addressed: fingerprint of the zone_metric output table + deterministic gate stats
msens::write_manifest(
  manifest, target = "score_zone_metrics", content_hash = zm_hash,
  stats = c(list(ver = ver), gate),
  force = msens::force_target("score_zone_metrics"))