The occurrence rule over every scored taxon x 12 ecoregions (v11 Q2)

msens::occurrence_rule() at the D10 defaults on OBIS records: anchors, tabulation by component, sensitivity to buffer, effort proxy and ratio

Published

2026-10-29

1 Goal

v7c removed two things by hand-evidenced rows: the sea turtles from the East Bering Sea (zero records in nine channels) and the North Atlantic right whale from the Gulf of America ecoregions (an “outside range” judgment). Tim White (2026-10-21) asked for one written rule that treats both the same way, with tiers: protected places override, “unsampled is unknown, not absent”, wide-ranging taxa. The rule is msens::occurrence_rule() (msens 0.63.0, a wrapper of region_effort_test(), rule E of obis_range_constraint.qmd): per ecoregion, the species’ modelled 0.5-degree blocks that were searched (a record of its effort group exists) against those that hold a record of the species, judged against the species’ record rate in its OTHER ecoregions (OCC_BASELINE=zones, the default since msens 0.63.0; range = the whole modelled range, the rule as first written, kept below as a sensitivity: the right whale’s modelled range spans the North Atlantic, most of it unsurveyed in OBIS, and against that diluted baseline its Gulf pairs could not be significantly fewer); an ecoregion is dropped only when records are significantly (binomial p < alpha) AND materially (rate < ratio x the baseline rate) fewer, kept when nobody looked.

This notebook runs that rule at the D10 defaults over every scored taxon x the 12 BOEM ecoregions and tabulates it by component. It writes data/v11/zone_exclusions_occ.csv, which merge_models.qmd consumes under OCC_RULE=1.

Scope of this version of the notebook. Records come from OBIS only (the obisindicators obis_cell export, libs/obis_h3.R). GBIF through speciesgrids, iNaturalist and the Alaska stranding / observer channels are later additions (plan 2026-10-29 section 4.3, D10): more channels can only add searched blocks and records, so a drop here that disappears with GBIF is a channel gap, and the anchors are read with that in mind (the Gulf of Alaska turtles are reported, not asserted).

Defaults (D10): effort = megafauna records for air-breathers (mammals, turtles, birds) and the taxon’s own order for the rest; buffer d = OCC_BUFFER_KM (100 km: a record just outside an ecoregion counts, for RECORDS and EFFORT only; presence stays inside the ecoregion); ratio 0.25, alpha 0.05, 0.5-degree blocks, no recency weight, critical habitat and narrow-range (< 20 cells) overrides, all taxa. One data-quality choice is not in D10: OBIS records dated before 1950 are ignored (OCC_YEAR_MIN, as obis_range_constraint.qmd did); records without a year are kept.

2 Design

Code
flowchart LR
  obis[("obis_cell + worms_taxon<br/>(obisindicators release)")] --> sp["records per species x cell<br/>+ order / megafauna effort blocks"]
  rng[("v10 merged GLOBAL surfaces<br/>(AquaMaps for am-only taxa)")] --> pr["present blocks<br/>(val >= 1)"]
  zc[("ecoregion zone_cell")] --> rg["majority region<br/>+ region_rec (d km)"]
  ch[("ch_fws / ch_nmfs / ca_nmfs")] --> rule
  sp --> rule["occurrence_rule()<br/>per batch of taxa"]
  pr --> rule
  rg --> rule
  rule --> ver["verdict: kept / dropped / unsearched<br/>+ overrides"]
  ver --> csv["data/v11/zone_exclusions_occ.csv<br/>(merge_models, OCC_RULE=1)"]
  ver --> tab["tables: anchors, components,<br/>sensitivity (d x effort x ratio)"]
flowchart LR
  obis[("obis_cell + worms_taxon<br/>(obisindicators release)")] --> sp["records per species x cell<br/>+ order / megafauna effort blocks"]
  rng[("v10 merged GLOBAL surfaces<br/>(AquaMaps for am-only taxa)")] --> pr["present blocks<br/>(val >= 1)"]
  zc[("ecoregion zone_cell")] --> rg["majority region<br/>+ region_rec (d km)"]
  ch[("ch_fws / ch_nmfs / ca_nmfs")] --> rule
  sp --> rule["occurrence_rule()<br/>per batch of taxa"]
  pr --> rule
  rg --> rule
  rule --> ver["verdict: kept / dropped / unsearched<br/>+ overrides"]
  ver --> csv["data/v11/zone_exclusions_occ.csv<br/>(merge_models, OCC_RULE=1)"]
  ver --> tab["tables: anchors, components,<br/>sensitivity (d x effort x ratio)"]
Figure 1: OBIS records + the v10 modelled range, per species x ecoregion, through occurrence_rule()

3 Setup

Code
librarian::shelf(
  DBI, digest, dplyr, duckdb, fs, glue, here, jsonlite, knitr, purrr, readr, stringr,
  tibble, tidyr, MarineSensitivity/msens, quiet = T)
source(here("libs/paths.R"))          # ver, ver_prev, dir_big, dir_big_v, obis_h3_*
source(here("libs/vars.R"))           # .flag(), occ_buffer_km
source(here("libs/duckdb_budget.R"))  # duckdb_tune()
source(here("libs/obis_h3.R"))        # obis_h3_src(), obis_h3_info()

stopifnot(
  "msens >= 0.64.1 (occurrence_rule(baseline), occurrence_exclusions(gate), encounter_weight, cells_within_sql) is required; reinstall msens" =
    packageVersion("msens") >= "0.64.1" && all(c("occurrence_rule", "occurrence_exclusions", "encounter_weight", "cells_within_sql") %in% getNamespaceExports("msens")))

# parameters ---- (env-overridable; the defaults are D10's)
redo_occ     <- .flag("REDO_OCC")                                  # rebuild every cache below
occ_test_n   <- as.integer(Sys.getenv("OCC_TEST_N", "0"))          # smoke test: anchors + first n taxa, writes nothing to data/
occ_alpha    <- as.numeric(Sys.getenv("OCC_ALPHA", "0.05"))
occ_ratio    <- as.numeric(Sys.getenv("OCC_RATIO", "0.25"))
occ_block    <- as.integer(Sys.getenv("OCC_BLOCK", "10"))          # cells per block side: 10 = 0.5 degrees on global05
occ_min_cells<- as.integer(Sys.getenv("OCC_MIN_CELLS", "20"))      # narrow-range override below this many cells worldwide
occ_year_min <- as.integer(Sys.getenv("OCC_YEAR_MIN", "1950"))     # OBIS records dated earlier are ignored (NULL year kept)
occ_baseline <- match.arg(Sys.getenv("OCC_BASELINE", "zones"), c("zones", "range"))   # what a zone is judged against (msens 0.63.0)
occ_gate     <- match.arg(Sys.getenv("OCC_GATE", "zero"), c("zero", "all"))            # D11: gate = zero records (default) | every dropped pair
occ_nc       <- 7200L                                              # global05 columns
d_default    <- occ_buffer_km                                      # libs/vars.R OCC_BUFFER_KM, default 100
d_all        <- sort(unique(c(0, 100, 250, d_default)))            # sensitivity buffers (km)
ratio_all    <- sort(unique(c(0.25, 0.5, 1, occ_ratio)))
cap_rows     <- as.numeric(Sys.getenv("OCC_BATCH_ROWS", "2e8"))    # merged-surface rows per batch
am_per_batch <- as.integer(Sys.getenv("OCC_AM_PER_BATCH", "300"))  # AquaMaps models per batch
sp_cats      <- c("bird", "mammal", "turtle", "fish", "coral", "invertebrate", "primary_producer")
air_cats     <- c("bird", "mammal", "turtle")                      # effort = megafauna by default
stopifnot(occ_block >= 1, nc_div = occ_nc %% occ_block == 0, all(d_all >= 0), occ_ratio > 0, occ_ratio <= 1)

# paths ---- inputs are the SOURCE version's (default v10) merged outputs; caches live in this version's dir
ver_src      <- Sys.getenv("OCC_SRC_VER", ver_prev)
dir_src_v    <- ifelse(is_server, glue("{dir_derived}/{ver_src}"), glue("{dir_big}/{ver_src}"))
dir_src      <- path_expand(glue("{dir_src_v}/marine-atlas"))
sdm_src      <- path_expand(glue("{dir_src_v}/sdm.duckdb"))
dir_occ      <- path_expand(Sys.getenv("OCC_DIR", glue("{dir_big_v}/marine-atlas/occ")))
dir_tmp      <- glue("{dir_occ}/duckdb_tmp")
f_zone_cell  <- path_expand(glue("{dir_big}/zones/ecoregion_2025-06/global05/zone_cell.parquet"))
f_obis       <- path_expand(obis_h3_src("obis_cell.parquet")$path)
f_worms      <- path_expand(obis_h3_src("worms_taxon.parquet")$path)
f_csv        <- here("data/v11/zone_exclusions_occ.csv")   # the GATE (OCC_RULE=1 in merge_models)
f_wcsv       <- here("data/v11/zone_weights_occ.csv")      # the WEIGHTS (REGION_WEIGHT=1 in merge_models)
manifest     <- here("data/manifests/explore_occurrence_rule.json")
dir_create(c(dir_occ, dir_tmp, path_dir(f_csv), path_dir(manifest)))
stopifnot(
  "OBIS release is not on local disk (libs/obis_h3.R would read HTTPS; stage ~/_big/obis first)" =
    file_exists(f_obis) && file_exists(f_worms),
  "source version's sdm.duckdb not found" = file_exists(sdm_src),
  "ecoregion zone_cell extract not found" = file_exists(f_zone_cell))
obis_info <- tryCatch(obis_h3_info(), error = \(e) list(release = obis_h3_release, obis_snapshot = NA, worms_version = NA))

con <- dbConnect(duckdb())
duckdb_tune(con, dir_tmp)
q <- \(x) paste0("'", x, "'", collapse = ", ")   # SQL list of string literals

# the block (unit) of a cell: IDENTICAL to occurrence_counts_sql()'s arithmetic (checked below)
unit_sql <- \(id) glue(
  "CAST((((CAST({id} AS BIGINT) - 1) // {occ_nc}) // {occ_block}) * {occ_nc %/% occ_block} + ((CAST({id} AS BIGINT) - 1) % {occ_nc}) // {occ_block} AS INTEGER)")

message(glue("explore_occurrence_rule: source {ver_src}, OBIS {obis_h3_release}, d {d_default} km, ratio {occ_ratio}, test_n {occ_test_n}"))

The block arithmetic is repeated here (effort is looked up by block), so a toy run of the msens rule proves the two agree: cells of one block share a verdict count, a neighbouring block does not.

Code
cells <- c(a = 5 * occ_nc + 10 + 1, b = 5 * occ_nc + 19 + 1,              # same 10 x 10 block (row 5, cols 10-19)
           c = 5 * occ_nc + 20 + 1, d = 10 * occ_nc + 10 + 1)              # next block east / next block south
u <- dbGetQuery(con, glue("SELECT {unit_sql('c')} AS u FROM (SELECT unnest([{paste(cells, collapse = ',')}]) AS c) ORDER BY c"))$u
stopifnot("unit_sql: cells of one block must share a unit" = u[1] == u[2], "unit_sql: neighbouring blocks must differ" = length(unique(u)) == 3)
dbWriteTable(con, "chk_present", data.frame(mdl_key = "x", cell_id = unname(cells)), overwrite = TRUE)
dbWriteTable(con, "chk_occ",     data.frame(mdl_key = "x", cell_id = cells[["a"]], records = 1L), overwrite = TRUE)
dbWriteTable(con, "chk_effort",  data.frame(mdl_key = "x", cell_id = cells[["b"]]), overwrite = TRUE)   # b, not a: same block
dbWriteTable(con, "chk_region",  data.frame(zone_key = "Z", cell_id = unname(cells)), overwrite = TRUE)
chk <- dbGetQuery(con, occurrence_counts_sql("chk_present", "chk_occ", "chk_effort", "chk_region", nc = occ_nc, block = occ_block))
stopifnot("msens block unit disagrees with unit_sql" = chk$n_searched == 1, chk$n_occupied == 1, chk$n_cells == 4)
for (t in c("chk_present", "chk_occ", "chk_effort", "chk_region")) dbExecute(con, glue("DROP TABLE {t}"))

4 WoRMS: records of a species, its order, the megafauna

OBIS records carry an AphiaID, which may be a synonym or an infraspecific name. Every record is credited to the accepted species: the accepted name (acceptedNameUsageID), then, for a subspecies / variety / form, its parent species. The accepted-species ids are then walked up parentNameUsageID to their Order and Class (worms_lineage). The two effort groups follow: order:{id} = blocks with a record of any species of the order, and mega = blocks with a record of any bird (Aves), mammal (Mammalia) or turtle (order Testudines).

Code
dbExecute(con, glue("CREATE OR REPLACE VIEW worms AS SELECT * FROM read_parquet('{f_worms}')"))
[1] 0
Code
dbExecute(con, "
  CREATE OR REPLACE TABLE w_alias AS
  SELECT w.taxonID AS aphiaid,
         CASE WHEN a.taxonID IS NULL THEN w.taxonID
              WHEN a.taxonRank IN ('Subspecies', 'Variety', 'Subvariety', 'Forma', 'Subforma') THEN COALESCE(a.parentNameUsageID, a.taxonID)
              ELSE a.taxonID END AS sp_id
  FROM worms w
  LEFT JOIN worms a ON a.taxonID = COALESCE(w.acceptedNameUsageID, w.taxonID)")
[1] 1581522
Code
f_obis_sp <- glue("{dir_occ}/obis_sp_{obis_h3_release}_y{occ_year_min}.parquet")
if (redo_occ || !file_exists(f_obis_sp)) {
  tmp <- glue("{f_obis_sp}.tmp")
  dbExecute(con, glue("
    COPY (
      SELECT a.sp_id, o.cell_id, sum(o.records)::BIGINT AS records
      FROM read_parquet('{f_obis}') o
      JOIN w_alias a ON a.aphiaid = o.aphiaid
      WHERE a.sp_id IS NOT NULL AND (o.date_year IS NULL OR o.date_year >= {occ_year_min})
      GROUP BY a.sp_id, o.cell_id
    ) TO '{tmp}' (FORMAT parquet, COMPRESSION zstd)"))
  file_move(tmp, f_obis_sp)
}
dbExecute(con, glue("CREATE OR REPLACE TABLE obis_sp AS SELECT * FROM read_parquet('{f_obis_sp}')"))
[1] 17470782
Code
obis_n <- dbGetQuery(con, "SELECT count(*) AS rows, count(DISTINCT sp_id) AS species, count(DISTINCT cell_id) AS cells, sum(records) AS records FROM obis_sp")
kable(obis_n, format.args = list(big.mark = ","), caption = glue("OBIS records credited to accepted species ({obis_h3_release}; dated >= {occ_year_min} or undated)."))
OBIS records credited to accepted species (v20261012; dated >= 1950 or undated).
rows species cells records
17,470,782 161,749 2,409,131 148,190,649

5 The scored taxa and where their modelled range lives

A scored taxon is taxon.is_valid_usa AND taxon.is_marine with sp_cat in the seven components (reptiles and amphibians are not scored). Its present cells are val >= 1 on the v10 merged GLOBAL surface (dist_merged_global, built for the 2,105 range-constrained taxa); a taxon without one is AquaMaps-only, and its present cells are the union of its am models (taxon_model), the surface the merge itself would have used. The global surface is the right one (not the US trim): a zone is judged against the species’ record rate across its whole range. Which bucket directory (b1 … b402, and turtle) of the merged surface holds each key is read once (a taxon lives in exactly one). BirdLife taxa carry a BOTW id, not an AphiaID, so they are matched to WoRMS accepted species by name; an unmatched taxon has no records and every ecoregion comes out “unsearched” (kept), which is the safe direction.

Code
f_taxa_base <- glue("{dir_occ}/taxa_base_{ver_src}.parquet")
f_buckets   <- glue("{dir_occ}/merged_buckets_{ver_src}.parquet")
f_am        <- glue("{dir_occ}/am_models_{ver_src}.parquet")
glob_mg     <- glue("{dir_src}/dist_merged_global/dataset=ms_merge/**/*.parquet")

if (redo_occ || !all(file_exists(c(f_taxa_base, f_buckets, f_am)))) {
  con_s <- dbConnect(duckdb(), dbdir = sdm_src, read_only = TRUE)
  tx <- dbGetQuery(con_s, glue("
    SELECT ms_merge_key AS mdl_key, taxon_authority, taxon_id, scientific_name, common_name, sp_cat
    FROM taxon
    WHERE is_valid_usa AND is_marine AND sp_cat IN ({q(sp_cats)})"))
  tm_am <- dbGetQuery(con_s, "
    SELECT ms_merge_key AS mdl_key, mdl_key AS am_key FROM taxon_model WHERE ds_key = 'am'") |>
    semi_join(tx, by = "mdl_key")
  # which merged bucket holds each key (one scan of the key column)
  bk <- dbGetQuery(con, glue("
    SELECT DISTINCT mdl_key, regexp_extract(filename, 'dataset=ms_merge/([^/]+)/', 1) AS bucket
    FROM read_parquet('{glob_mg}', filename = true, hive_partitioning = false)"))
  stopifnot("a merged key lives in two buckets" = !anyDuplicated(bk$mdl_key), "bucket not parsed" = all(nzchar(bk$bucket)))
  dbDisconnect(con_s, shutdown = TRUE)
  write_parquet_df <- \(df, f) { dbWriteTable(con, "tmp_df", df, overwrite = TRUE); dbExecute(con, glue("COPY tmp_df TO '{f}' (FORMAT parquet)")); dbExecute(con, "DROP TABLE tmp_df") }
  write_parquet_df(tx,    f_taxa_base)
  write_parquet_df(bk,    f_buckets)
  write_parquet_df(tm_am, f_am)
}
rd <- \(f) dbGetQuery(con, glue("SELECT * FROM read_parquet('{f}')")) |> as_tibble()
tx <- rd(f_taxa_base); bk <- rd(f_buckets); tm_am <- rd(f_am)

# AphiaID of each taxon: WoRMS taxa carry it; BOTW taxa are matched to a WoRMS accepted species by name
nm <- dbGetQuery(con, "
  SELECT scientificName AS scientific_name, min(taxonID) AS nm_id
  FROM worms WHERE taxonRank = 'Species' AND taxonomicStatus = 'accepted' GROUP BY 1") |> as_tibble()
alias <- dbGetQuery(con, "SELECT aphiaid, sp_id FROM w_alias") |> as_tibble()
tx <- tx |>
  left_join(nm, by = "scientific_name") |>
  mutate(aphia = case_when(taxon_authority == "worms" ~ suppressWarnings(as.numeric(taxon_id)), TRUE ~ as.numeric(nm_id))) |>
  left_join(alias |> mutate(aphia = as.numeric(aphiaid)) |> select(aphia, sp_id), by = "aphia") |>
  select(-nm_id) |>
  mutate(
    sp_id       = as.numeric(sp_id),
    src         = case_when(mdl_key %in% bk$mdl_key ~ "merged", mdl_key %in% tm_am$mdl_key ~ "am", TRUE ~ NA_character_),
    eff_default = ifelse(sp_cat %in% air_cats, "megafauna", "order"),
    anchor      = scientific_name %in% c("Eubalaena glacialis") | sp_cat == "turtle") |>
  left_join(bk, by = "mdl_key")
n_nosurface <- sum(is.na(tx$src))
tx <- tx |> filter(!is.na(src))
if (occ_test_n > 0) {                                                            # smoke test: the anchors + an even spread of taxa
  keep <- sort(unique(c(which(tx$anchor), round(seq(1, nrow(tx), length.out = occ_test_n)))))
  tx <- tx[keep, ]
}
tx |> count(sp_cat, src) |> pivot_wider(names_from = src, values_from = n, values_fill = 0) |>
  kable(format.args = list(big.mark = ","), caption = glue("Scored taxa by component and where their modelled range comes from (no surface at all: {n_nosurface}; no AphiaID: {sum(is.na(tx$sp_id))})."))
Scored taxa by component and where their modelled range comes from (no surface at all: 0; no AphiaID: 38).
sp_cat merged am
bird 229 0
coral 452 331
fish 1,124 5,162
invertebrate 200 9,210
mammal 69 6
primary_producer 37 282
turtle 6 0
Code
f_lin <- glue("{dir_occ}/worms_lineage_{obis_h3_release}.parquet")
ids_needed <- dbGetQuery(con, "SELECT DISTINCT sp_id FROM obis_sp")$sp_id |> union(tx$sp_id) |> na.omit()
lin <- if (!redo_occ && file_exists(f_lin)) rd(f_lin) else NULL
if (is.null(lin) || !all(ids_needed %in% lin$sp_id)) {
  dbWriteTable(con, "lin_ids", tibble(sp_id = as.numeric(ids_needed)), overwrite = TRUE)
  # walk each accepted species up the parent chain (<= 40 steps) and keep the Order and the Class on the way
  lin <- dbGetQuery(con, "
    WITH RECURSIVE up(start_id, cur, depth) AS (
      SELECT sp_id::BIGINT, sp_id::BIGINT, 0 FROM lin_ids
      UNION ALL
      SELECT up.start_id, w.parentNameUsageID, up.depth + 1
      FROM up JOIN worms w ON w.taxonID = up.cur
      WHERE w.parentNameUsageID IS NOT NULL AND up.depth < 40)
    SELECT up.start_id AS sp_id,
           max(CASE WHEN w.taxonRank = 'Order' THEN w.taxonID END)        AS order_id,
           max(CASE WHEN w.taxonRank = 'Order' THEN w.scientificName END) AS order_name,
           max(CASE WHEN w.taxonRank = 'Class' THEN w.scientificName END) AS class_name
    FROM up JOIN worms w ON w.taxonID = up.cur
    GROUP BY up.start_id") |> as_tibble()
  dbWriteTable(con, "tmp_df", lin, overwrite = TRUE)
  dbExecute(con, glue("COPY tmp_df TO '{f_lin}' (FORMAT parquet)")); dbExecute(con, "DROP TABLE tmp_df")
}
dbWriteTable(con, "worms_lineage", lin |> mutate(sp_id = as.numeric(sp_id), order_id = as.numeric(order_id)), overwrite = TRUE)
tx <- tx |>
  left_join(lin |> transmute(sp_id = as.numeric(sp_id), order_id = as.numeric(order_id), order_name, class_name), by = "sp_id") |>
  mutate(grp_order = ifelse(is.na(order_id), NA_character_, paste0("order:", sprintf("%.0f", order_id))))
tx |> count(sp_cat, has_order = !is.na(order_id), has_aphia = !is.na(sp_id)) |>
  kable(format.args = list(big.mark = ","), caption = "Scored taxa with a resolved AphiaID and Order (an unresolved taxon has no records / no order effort: every ecoregion is 'unsearched').")
Scored taxa with a resolved AphiaID and Order (an unresolved taxon has no records / no order effort: every ecoregion is ‘unsearched’).
sp_cat has_order has_aphia n
bird FALSE FALSE 38
bird TRUE TRUE 191
coral TRUE TRUE 783
fish TRUE TRUE 6,286
invertebrate FALSE TRUE 270
invertebrate TRUE TRUE 9,140
mammal TRUE TRUE 75
primary_producer FALSE TRUE 2
primary_producer TRUE TRUE 317
turtle TRUE TRUE 6
Code
f_eff <- glue("{dir_occ}/effort_blocks_{obis_h3_release}_y{occ_year_min}_b{occ_block}.parquet")
if (redo_occ || !file_exists(f_eff)) {
  tmp <- glue("{f_eff}.tmp")
  dbExecute(con, glue("
    COPY (
      SELECT DISTINCT 'order:' || CAST(l.order_id::BIGINT AS VARCHAR) AS grp, {unit_sql('o.cell_id')} AS unit_id
      FROM obis_sp o JOIN worms_lineage l ON l.sp_id = o.sp_id
      WHERE l.order_id IS NOT NULL
      UNION
      SELECT DISTINCT 'mega' AS grp, {unit_sql('o.cell_id')} AS unit_id
      FROM obis_sp o JOIN worms_lineage l ON l.sp_id = o.sp_id
      WHERE l.class_name IN ('Aves', 'Mammalia') OR l.order_name = 'Testudines'
    ) TO '{tmp}' (FORMAT parquet, COMPRESSION zstd)"))
  file_move(tmp, f_eff)
}
dbExecute(con, glue("CREATE OR REPLACE TABLE effort_blocks AS SELECT * FROM read_parquet('{f_eff}')"))
[1] 1680815
Code
dbGetQuery(con, "SELECT (grp = 'mega') AS is_mega, count(DISTINCT grp) AS groups, count(*) AS group_blocks, max(CASE WHEN grp = 'mega' THEN 1 END) AS x FROM effort_blocks GROUP BY 1") |>
  select(-x) |> kable(format.args = list(big.mark = ","), caption = "Effort blocks (0.5 degree) by group: order groups, and the megafauna group (birds + mammals + turtles).")
Effort blocks (0.5 degree) by group: order groups, and the megafauna group (birds + mammals + turtles).
is_mega groups group_blocks
FALSE 1,143 1,555,902
TRUE 1 124,913

6 Ecoregions: the majority region and the buffered region

occ_region gives each cell to the ecoregion covering most of it (msens::cell_zone_major_sql(), ties to the first key, the rule zone_exclude_sql() will delete under): PRESENCE is counted there. occ_rec_{d} is the same region dilated by d km: every cell whose centre is within d km of a cell of the ecoregion (msens::cells_within_sql(), haversine on cell centres, the column index wraps at the antimeridian); RECORDS and EFFORT are counted there. Each dilation is cached as region_rec_{d}km.parquet.

Code
dbExecute(con, glue("CREATE OR REPLACE TEMP VIEW zc_raw AS SELECT * FROM read_parquet('{f_zone_cell}')"))
[1] 0
Code
# present the extract in the v1-v7 `zone` / `zone_cell` schema cell_zone_major_sql() reads
dbExecute(con, "CREATE OR REPLACE TEMP TABLE zone AS SELECT row_number() OVER (ORDER BY zone_key) AS zone_seq, 'ecoregion_key' AS fld, zone_key AS value FROM (SELECT DISTINCT zone_key FROM zc_raw)")
[1] 12
Code
dbExecute(con, "CREATE OR REPLACE TEMP TABLE zone_cell AS SELECT z.zone_seq, p.cell_id, p.pct_covered FROM zc_raw p JOIN zone z ON z.value = p.zone_key")
[1] 630944
Code
dbExecute(con, glue("CREATE OR REPLACE TABLE occ_region AS SELECT cell_id, zone_key FROM ({cell_zone_major_sql()})"))
[1] 629993
Code
zones <- dbGetQuery(con, "SELECT zone_key, count(*) AS cells FROM occ_region GROUP BY 1 ORDER BY 1") |> as_tibble()
stopifnot("expected the 12 BOEM ecoregions" = nrow(zones) == 12,
          "anchor ecoregions missing from the extract" = all(c("EBS", "GOA", "EGOA", "WCGOA") %in% zones$zone_key))

dbExecute(con, "CREATE OR REPLACE VIEW occ_rec_0 AS SELECT zone_key, cell_id FROM occ_region")
[1] 0
Code
for (d in setdiff(d_all, 0)) {
  f <- glue("{dir_occ}/region_rec_{d}km.parquet")
  if (redo_occ || !file_exists(f)) {
    t0 <- Sys.time(); tmp <- glue("{f}.tmp")
    dbExecute(con, glue("COPY (SELECT zone_key, cell_id FROM ({cells_within_sql('occ_region', d, by = 'zone_key')})) TO '{tmp}' (FORMAT parquet, COMPRESSION zstd)"))
    file_move(tmp, f)
    message(glue("region_rec {d} km built in {round(as.numeric(difftime(Sys.time(), t0, units = 'secs')))} s"))
  }
  dbExecute(con, glue("CREATE OR REPLACE TABLE occ_rec_{d} AS SELECT * FROM read_parquet('{f}')"))
}
rec_n <- map_dfr(d_all, \(d) dbGetQuery(con, glue("SELECT zone_key, {d} AS d, count(*) AS cells FROM occ_rec_{d} GROUP BY 1"))) |>
  pivot_wider(names_from = d, values_from = cells, names_prefix = "d")
zones |> left_join(rec_n, by = "zone_key") |>
  kable(format.args = list(big.mark = ","), caption = "Ecoregion cells (majority region) and the cells of the region dilated by d km (columns d0, d100, ...).")
Ecoregion cells (majority region) and the cells of the region dilated by d km (columns d0, d100, …).
zone_key cells d0 d100 d250
CAC 24,311 24,311 41,449 71,550
CBS 59,979 59,979 106,707 187,133
EBS 131,220 131,220 176,346 246,547
EGOA 11,355 11,355 21,096 39,734
GOA 56,528 56,528 96,490 155,086
HAR 67,303 67,303 126,680 245,861
NECS 25,238 25,238 41,732 70,905
PIS 203,010 203,010 297,208 459,302
PUR 7,736 7,736 15,781 32,006
SECS 19,700 19,700 37,177 66,436
WAOR 10,993 10,993 21,655 43,265
WCGOA 12,620 12,620 23,395 43,924

7 Protected cells and batches

The protected override is about places, not ESA status: a zone holding designated cells of the species (critical habitat from ch_fws, ch_nmfs, the NMFS core areas ca_nmfs) is never dropped, which is why both v7c exclusions survive without carrying a status test. The three datasets’ mdl_key are mapped to the merged key through taxon_model.

Code
f_ch <- glue("{dir_occ}/ch_{ver_src}.parquet")
if (redo_occ || !file_exists(f_ch)) {
  con_s <- dbConnect(duckdb(), dbdir = sdm_src, read_only = TRUE)
  tm_ch <- dbGetQuery(con_s, "SELECT mdl_key AS ch_key, ms_merge_key AS mdl_key FROM taxon_model WHERE ds_key IN ('ch_fws', 'ch_nmfs', 'ca_nmfs')")
  dbDisconnect(con_s, shutdown = TRUE)
  dbWriteTable(con, "tm_ch", tm_ch, overwrite = TRUE)
  globs <- glue("{dir_src}/dist/dataset={c('ch_fws', 'ch_nmfs', 'ca_nmfs')}/**/*.parquet")
  dbExecute(con, glue("
    COPY (SELECT DISTINCT t.mdl_key, c.cell_id
          FROM read_parquet([{q(globs)}], hive_partitioning = false) c
          JOIN tm_ch t ON t.ch_key = c.mdl_key)
    TO '{f_ch}' (FORMAT parquet)"))
}
dbExecute(con, glue("CREATE OR REPLACE TABLE occ_ch AS SELECT * FROM read_parquet('{f_ch}')"))
[1] 336327
Code
dbGetQuery(con, "SELECT count(DISTINCT mdl_key) AS taxa_with_ch, count(*) AS ch_cells FROM occ_ch") |>
  kable(format.args = list(big.mark = ","), caption = "Protected cells (critical habitat + core areas), by merged taxon.")
Protected cells (critical habitat + core areas), by merged taxon.
taxa_with_ch ch_cells
60 336,327

Taxa are processed in batches so the multi-billion-row surfaces stream: merged-surface taxa by bucket directory (about OCC_BATCH_ROWS rows each), AquaMaps-only taxa by OCC_AM_PER_BATCH models. The batch of a taxon is stored with it; counts/{sig}/{batch}.parquet is the resume marker, and sig hashes everything the counts depend on.

Code
if (nrow(tx) > 0) {
  bk_n <- dbGetQuery(con, glue("
    SELECT regexp_extract(file_name, 'dataset=ms_merge/([^/]+)/', 1) AS bucket, sum(num_rows) AS n
    FROM parquet_file_metadata('{glob_mg}') GROUP BY 1")) |> as_tibble()
  m_b <- tx |> filter(src == "merged") |> distinct(bucket) |>
    left_join(bk_n, by = "bucket") |> arrange(suppressWarnings(as.integer(sub("^b", "", bucket))), bucket) |>
    mutate(batch = sprintf("m%03d", dense_rank(cumsum(n) %/% cap_rows)))
  n_am <- tm_am |> count(mdl_key, name = "n_mod")
  a_b <- tx |> filter(src == "am") |> arrange(mdl_key) |> left_join(n_am, by = "mdl_key") |>
    mutate(batch = sprintf("a%03d", dense_rank(cumsum(n_mod) %/% am_per_batch))) |> select(mdl_key, batch)
  tx <- tx |> select(-any_of(c("batch", "n_mod", "multi"))) |>
    left_join(n_am, by = "mdl_key") |>
    mutate(batch = coalesce(m_b$batch[match(bucket, m_b$bucket)], a_b$batch[match(mdl_key, a_b$mdl_key)]),
           multi = coalesce(n_mod, 0L) > 1L)
  stopifnot("every taxon needs a batch" = !anyNA(tx$batch))
}
sig <- substr(digest::digest(list(
  ver_src, obis_h3_release, occ_year_min, occ_block, occ_min_cells, occ_alpha, d_all, ratio_all, occ_ratio, d_default,
  occ_baseline, "msens 0.63.0 counts", occ_test_n, sort(tx$mdl_key), tx$batch[order(tx$mdl_key)]), algo = "xxhash64"), 1, 10)
dir_cnt <- glue("{dir_occ}/counts/{sig}")
dir_create(dir_cnt)
tx |> count(batch, src, name = "taxa") |>
  summarise(batches = n(), merged_batches = sum(src == "merged"), am_batches = sum(src == "am"), taxa = sum(taxa)) |>
  kable(format.args = list(big.mark = ","), caption = glue("Batches (cache signature {sig}; {length(list.files(dir_cnt, '[.]parquet$'))} already done)."))
Batches (cache signature 140bddd19f; 64 already done).
batches merged_batches am_batches taxa
64 13 51 17,108

8 Run the rule, batch by batch

For one batch: stream the batch’s surfaces into (taxon, cell) pairs with val >= 1, then reduce them without changing any count the rule takes: it uses present cells (a) inside an ecoregion (n_cells, and the protected test), (b) as distinct 0.5-degree blocks (searched / occupied / totals), and (c) as a worldwide cell count for the narrow-range override. So a species of at least block^2 x min_cells cells keeps every present cell inside an ecoregion plus one representative cell per block (which preserves the block set, and still has at least min_cells cells), and a smaller species keeps all its cells; a check below proves the narrow-range classification is unchanged. The effort relation is the species’ effort group restricted to the species’ own present blocks (the rule reads effort only there). Then occurrence_rule() runs: once at the D10 defaults (effort by taxon, d = OCC_BUFFER_KM, ratio OCC_RATIO) and, for the sensitivity table, at every buffer x effort proxy with ratio = 1 (the verdict at a smaller ratio is the ratio-1 verdict with rate < ratio x p_core applied on top, which the tabulation re-derives with region_effort_test() and checks against the default run).

Code
thr_small <- occ_block^2 * occ_min_cells     # a species with fewer cells than this keeps ALL of them

rule <- function(eff, d, ratio) occurrence_rule(
  con, present = "occ_present", occ = "occ_records", effort = glue("occ_effort_{eff}"),
  region = "occ_region", region_rec = glue("occ_rec_{d}"), ch = "occ_ch",
  nc = occ_nc, block = occ_block, alpha = occ_alpha, ratio = ratio, min_cells = occ_min_cells, baseline = occ_baseline)

run_batch <- function(b) {
  f_out <- glue("{dir_cnt}/{b}.parquet")
  if (file_exists(f_out)) return(invisible(NULL))
  t0 <- Sys.time()
  tb <- tx |> filter(batch == b) |> mutate(k = row_number())
  stopifnot(length(unique(tb$src)) == 1)
  dbWriteTable(con, "occ_tx", tb |> transmute(mdl_key, k = as.integer(k), sp_id, grp_order, eff_default, multi), overwrite = TRUE)

  # 1. stream the surfaces into (k, cell_id), val >= 1
  if (tb$src[1] == "merged") {
    globs <- glue("{dir_src}/dist_merged_global/dataset=ms_merge/{unique(tb$bucket)}/*.parquet")
    dbExecute(con, glue("
      CREATE OR REPLACE TABLE occ_scan AS
      SELECT t.k, s.cell_id
      FROM read_parquet([{q(globs)}], hive_partitioning = false) s
      JOIN occ_tx t ON t.mdl_key = s.mdl_key
      WHERE s.val >= 1"))
  } else {
    am <- tm_am |> inner_join(tb |> select(mdl_key, k), by = "mdl_key")
    files <- glue("{dir_src}/dist/dataset=am/{sub('^am[|]', '', am$am_key)}.parquet")
    stopifnot("an AquaMaps surface file is missing" = all(file_exists(files)))
    dbWriteTable(con, "occ_am", am |> transmute(am_key, k = as.integer(k)), overwrite = TRUE)
    dbExecute(con, glue("
      CREATE OR REPLACE TABLE occ_scan AS
      SELECT a.k, s.cell_id
      FROM read_parquet([{q(files)}], hive_partitioning = false) s
      JOIN occ_am a ON a.am_key = s.mdl_key
      WHERE s.val >= 1"))
  }
  # worldwide present cells per taxon (distinct: a multi-model AquaMaps taxon repeats cells)
  dbExecute(con, "
    CREATE OR REPLACE TABLE occ_n AS
    SELECT k, count(*) AS n FROM occ_scan WHERE k NOT IN (SELECT k FROM occ_tx WHERE multi) GROUP BY k
    UNION ALL
    SELECT k, count(DISTINCT cell_id) AS n FROM occ_scan WHERE k IN (SELECT k FROM occ_tx WHERE multi) GROUP BY k")
  # 2. reduce (see the prose above)
  dbExecute(con, glue("
    CREATE OR REPLACE TABLE occ_present AS
    SELECT t.mdl_key, x.cell_id FROM (
      SELECT DISTINCT k, cell_id FROM occ_scan WHERE k IN (SELECT k FROM occ_n WHERE n < {thr_small})
      UNION
      SELECT k, min(cell_id) FROM occ_scan WHERE k IN (SELECT k FROM occ_n WHERE n >= {thr_small}) GROUP BY k, {unit_sql('cell_id')}
      UNION
      SELECT k, cell_id FROM occ_scan WHERE k IN (SELECT k FROM occ_n WHERE n >= {thr_small}) AND cell_id IN (SELECT cell_id FROM occ_region)
    ) x JOIN occ_tx t USING (k)"))
  bad <- dbGetQuery(con, glue("
    SELECT count(*) AS n FROM (
      SELECT t.k, count(DISTINCT p.cell_id) AS r FROM occ_present p JOIN occ_tx t USING (mdl_key) GROUP BY t.k) a
    JOIN occ_n USING (k) WHERE (a.r < {occ_min_cells}) <> (occ_n.n < {occ_min_cells})"))$n
  stopifnot("the reduction changed a narrow-range classification" = bad == 0)
  n_in  <- dbGetQuery(con, "SELECT count(*) AS n FROM occ_scan")$n
  n_red <- dbGetQuery(con, "SELECT count(*) AS n FROM occ_present")$n
  dbExecute(con, "DROP TABLE occ_scan")

  # 3. records of each taxon (its accepted species, all synonyms / infraspecifics) and the effort relations
  dbExecute(con, "
    CREATE OR REPLACE TABLE occ_records AS
    SELECT t.mdl_key, o.cell_id, sum(o.records)::BIGINT AS records
    FROM occ_tx t JOIN obis_sp o ON o.sp_id = t.sp_id GROUP BY t.mdl_key, o.cell_id")
  mk_eff <- \(name, grp_expr) dbExecute(con, glue("
    CREATE OR REPLACE TABLE {name} AS
    SELECT DISTINCT p.mdl_key, p.cell_id
    FROM occ_present p JOIN occ_tx t USING (mdl_key)
    JOIN effort_blocks e ON e.grp = {grp_expr} AND e.unit_id = {unit_sql('p.cell_id')}"))
  mk_eff("occ_effort_order", "t.grp_order")
  mk_eff("occ_effort_mega",  "'mega'")
  dbExecute(con, "
    CREATE OR REPLACE TABLE occ_effort_default AS
    SELECT * FROM occ_effort_order WHERE mdl_key IN (SELECT mdl_key FROM occ_tx WHERE eff_default = 'order')
    UNION ALL
    SELECT * FROM occ_effort_mega  WHERE mdl_key IN (SELECT mdl_key FROM occ_tx WHERE eff_default = 'megafauna')")

  # 4. the rule: the D10 defaults, then the sensitivity grid at ratio = 1
  out <- list(
    rule("default", d_default, occ_ratio) |> mutate(run = "default", eff = "default", d = d_default, ratio = occ_ratio))
  for (eff in c("order", "mega")) for (d in d_all)
    out[[length(out) + 1]] <- rule(eff, d, 1) |> mutate(run = "sens", eff = ifelse(eff == "mega", "megafauna", eff), d = d, ratio = 1)
  res_b <- bind_rows(out) |> mutate(batch = b, n_scan = n_in, n_reduced = n_red)
  dbWriteTable(con, "occ_out", res_b, overwrite = TRUE)
  tmp <- glue("{f_out}.tmp")
  dbExecute(con, glue("COPY occ_out TO '{tmp}' (FORMAT parquet, COMPRESSION zstd)"))
  file_move(tmp, f_out)
  for (t in c("occ_out", "occ_present", "occ_records", "occ_n", "occ_effort_order", "occ_effort_mega", "occ_effort_default")) dbExecute(con, glue("DROP TABLE IF EXISTS {t}"))
  message(glue("batch {b}: {nrow(tb)} taxa, {format(n_in, big.mark = ',')} cells -> {format(n_red, big.mark = ',')} kept, ",
               "{nrow(res_b)} rule rows, {round(as.numeric(difftime(Sys.time(), t0, units = 'secs')))} s"))
  invisible(NULL)
}

batch_ids <- sort(unique(tx$batch))
walk(batch_ids, run_batch)
f_counts <- list.files(dir_cnt, "[.]parquet$", full.names = TRUE)
stopifnot("not every batch produced a counts file" = length(f_counts) == length(batch_ids))
res_all <- dbGetQuery(con, glue("SELECT * FROM read_parquet([{q(f_counts)}])")) |> as_tibble()
meta <- tx |> select(mdl_key, taxon_id, scientific_name, common_name, sp_cat, eff_default, src, order_name, class_name)
message(glue("{nrow(res_all)} rule rows over {n_distinct(res_all$mdl_key)} taxa"))

9 Re-derive the ratio grid, and check the derivation

The sensitivity runs used ratio 1. The verdict at any smaller ratio is region_effort_test() on the stored counts (the “unsearched” test does not depend on the ratio) with the stored override flag applied on top. Two checks make the derivation trustworthy: at ratio 1 it must reproduce the stored verdicts, and at the default (buffer, ratio, effort by taxon) it must reproduce the dropped set of the direct occurrence_rule() run.

Code
base_cols <- if (occ_baseline == "zones") c("n_searched_zones", "n_occupied_zones") else c("n_searched_all", "n_occupied_all")
verdict_at <- function(x, ratio, cols = base_cols) {
  v <- region_effort_test(x$n_searched, x$n_occupied, x[[cols[1]]], x[[cols[2]]],
                          n_records = x$n_records, alpha = occ_alpha, ratio = ratio)$verdict
  ifelse(v == "dropped" & !is.na(x$override), "kept", v)
}
res_def  <- res_all |> filter(run == "default") |> left_join(meta, by = "mdl_key")
res_sens <- res_all |> filter(run == "sens")    |> left_join(meta, by = "mdl_key")

stopifnot("derivation at ratio 1 must reproduce the stored verdicts" = identical(verdict_at(res_sens, 1), res_sens$verdict))
# effort by taxon at (d_default, occ_ratio) from the order / megafauna sens rows == the direct default run
mix <- res_sens |> filter(d == d_default, eff == eff_default) |> mutate(verdict = verdict_at(pick(everything()), occ_ratio))
key <- \(x) sort(paste(x$mdl_key, x$zone_key))
stopifnot("derived default must reproduce the direct occurrence_rule() default" =
            identical(key(filter(mix, verdict == "dropped")), key(filter(res_def, verdict == "dropped"))),
          "derived default has other rows than the direct run" = nrow(mix) == nrow(res_def))
message(glue("derivation verified: {sum(res_def$verdict == 'dropped')} dropped pairs at the defaults"))

10 The anchors, first

Two cases the rule must reproduce without any hand-written row: the sea turtles in the East Bering Sea (EBS) and the North Atlantic right whale in the Gulf of America ecoregions EGOA + WCGOA. The Gulf of Alaska (GOA) is shown beside EBS because v7c kept the turtles there; with OBIS alone it is reported, not asserted. Full rule rows (n_cells = modelled cells in the ecoregion; n_searched / n_occupied = 0.5-degree blocks searched / with a record; n_searched_zones / n_occupied_zones = the same over every ecoregion of the set, n_searched_all / n_occupied_all over the species’ whole range; p_core = the baseline record rate (the other ecoregions under OCC_BASELINE=zones); rate = the rate here; n_min = searched blocks needed for zero records to reject).

Code
v7c_turtles <- c("Caretta caretta", "Chelonia mydas", "Dermochelys coriacea", "Lepidochelys olivacea")   # dropped from EBS in v7c
anchor_cols <- c("common_name", "zone_key", "n_cells", "n_searched", "n_occupied", "n_records", "n_searched_all", "n_occupied_all",
                 "p_core", "rate", "n_min", "p_value", "verdict_raw", "override", "verdict", "label")
fmt <- \(x) x |> mutate(across(c(p_core, rate, p_value), \(v) signif(v, 3)), n_min = ifelse(is.finite(n_min), n_min, NA))
turtle_rows <- res_def |> filter(sp_cat == "turtle", zone_key %in% c("EBS", "GOA")) |> arrange(scientific_name, zone_key)
rw_rows     <- res_def |> filter(scientific_name == "Eubalaena glacialis") |> arrange(zone_key)
kable(fmt(turtle_rows)[, anchor_cols], format.args = list(big.mark = ","), caption = glue(
  "Anchor 1: the six sea turtles x East Bering Sea and Gulf of Alaska at the defaults (effort = megafauna, d = {d_default} km, ratio {occ_ratio}, OBIS only). A turtle with no row has no modelled cell in that ecoregion."))
Anchor 1: the six sea turtles x East Bering Sea and Gulf of Alaska at the defaults (effort = megafauna, d = 100 km, ratio 0.25, OBIS only). A turtle with no row has no modelled cell in that ecoregion.
common_name zone_key n_cells n_searched n_occupied n_records n_searched_all n_occupied_all p_core rate n_min p_value verdict_raw override verdict label
Loggerhead Turtle EBS 38,035 238 0 0 58,440 11,696 0.2540 0.00000 11 0.0e+00 dropped NA dropped NA
Loggerhead Turtle GOA 56,418 537 0 0 58,440 11,696 0.2820 0.00000 10 0.0e+00 dropped NA dropped NA
Green Turtle EBS 39,207 254 0 0 48,191 4,248 0.1320 0.00000 22 0.0e+00 dropped NA dropped NA
Green Turtle GOA 56,527 538 0 1 48,191 4,248 0.1460 0.00000 20 0.0e+00 dropped NA dropped documented occurrence only
Leatherback Turtle EBS 39,948 268 0 0 77,780 7,256 0.2650 0.00000 10 0.0e+00 dropped NA dropped NA
Leatherback Turtle GOA 56,528 538 3 4 77,780 7,256 0.2910 0.00558 9 0.0e+00 dropped NA dropped documented occurrence only
Olive Ridley Turtle EBS 24,205 167 0 0 36,365 2,560 0.0685 0.00000 43 7.2e-06 dropped NA dropped NA
Olive Ridley Turtle GOA 56,528 538 0 1 36,365 2,560 0.0794 0.00000 37 0.0e+00 dropped NA dropped documented occurrence only
Code
kable(fmt(rw_rows |> filter(zone_key %in% c("EGOA", "WCGOA")))[, anchor_cols], format.args = list(big.mark = ","), caption = glue(
  "Anchor 2: North Atlantic right whale x the Gulf of America ecoregions (EGOA, WCGOA)."))
Anchor 2: North Atlantic right whale x the Gulf of America ecoregions (EGOA, WCGOA).
common_name zone_key n_cells n_searched n_occupied n_records n_searched_all n_occupied_all p_core rate n_min p_value verdict_raw override verdict label
North Atlantic Right Whale EGOA 5,616 79 3 4 7,099 352 0.261 0.0380 10 2e-07 dropped NA dropped documented occurrence only
North Atlantic Right Whale WCGOA 7,276 103 4 6 7,099 352 0.270 0.0388 10 0e+00 dropped NA dropped documented occurrence only
Code
kable(fmt(rw_rows |> filter(!zone_key %in% c("EGOA", "WCGOA")))[, anchor_cols], format.args = list(big.mark = ","), caption =
  "For context: the right whale in its other ecoregions (the stronghold the Gulf is judged against).")
For context: the right whale in its other ecoregions (the stronghold the Gulf is judged against).
common_name zone_key n_cells n_searched n_occupied n_records n_searched_all n_occupied_all p_core rate n_min p_value verdict_raw override verdict label
North Atlantic Right Whale NECS 25,238 284 116 147 7,099 352 0.109 0.408 26 1.000000 kept NA kept NA
North Atlantic Right Whale SECS 19,361 211 36 42 7,099 352 0.264 0.171 10 0.000906 kept NA kept NA
Code
anchor_ok <- list(
  turtles_ebs = turtle_rows |> filter(scientific_name %in% v7c_turtles, zone_key == "EBS"),
  rw_gulf     = rw_rows |> filter(zone_key %in% c("EGOA", "WCGOA")))

11 Tabulation by component

“Kept” is the test’s own verdict with no override; the two overrides are counted apart (a pair the test would drop but critical habitat / a narrow range keeps), and “unsearched” pairs are kept and flagged (nobody looked). cells is the sum of modelled cells in the dropped species x ecoregion pairs (n_cells).

Code
n_scored <- count(tx, sp_cat, name = "taxa")
tab_comp <- res_def |>
  group_by(sp_cat) |>
  summarise(
    species_with_rows   = n_distinct(mdl_key),
    species_dropped     = n_distinct(mdl_key[verdict == "dropped"]),
    pairs               = n(),
    kept                = sum(verdict == "kept" & is.na(override)),
    dropped             = sum(verdict == "dropped"),
    unsearched          = sum(verdict == "unsearched"),
    override_protected  = sum(override %in% "protected"),
    override_narrow     = sum(override %in% "narrow range"),
    documented_only     = sum(label %in% "documented occurrence only"),
    cells_dropped       = sum(n_cells[verdict == "dropped"]),
    .groups = "drop") |>
  left_join(n_scored, by = "sp_cat") |> relocate(sp_cat, taxa)
tab_total <- tab_comp |> summarise(across(where(is.numeric), sum)) |> mutate(sp_cat = "all", .before = 1)
bind_rows(tab_comp, tab_total) |>
  kable(format.args = list(big.mark = ","), caption = glue("The rule at the defaults, by component. `taxa` = scored taxa run; `species_with_rows` = those with a modelled cell in at least one ecoregion."))
The rule at the defaults, by component. taxa = scored taxa run; species_with_rows = those with a modelled cell in at least one ecoregion.
sp_cat taxa species_with_rows species_dropped pairs kept dropped unsearched override_protected override_narrow documented_only cells_dropped
bird 229 228 79 946 492 118 336 0 0 107 5,342,545
coral 783 783 160 1,979 497 259 1,222 1 0 91 2,595,940
fish 6,286 6,283 1,119 15,515 5,100 1,527 8,888 0 0 918 33,583,006
invertebrate 9,410 9,409 2,456 33,766 8,636 3,616 21,514 0 0 1,732 39,056,672
mammal 75 75 42 366 215 83 65 3 0 64 3,541,834
primary_producer 319 319 77 1,273 300 103 870 0 0 49 547,625
turtle 6 6 5 50 34 15 1 0 0 8 618,457
all 17,108 17,103 3,938 53,895 15,274 5,721 32,896 4 0 2,969 85,286,079
Code
res_def |> filter(verdict == "dropped") |>
  count(zone_key, sp_cat) |> pivot_wider(names_from = sp_cat, values_from = n, values_fill = 0) |>
  right_join(zones |> select(zone_key), by = "zone_key") |> mutate(across(where(is.numeric), \(x) coalesce(x, 0L))) |> arrange(zone_key) |>
  kable(format.args = list(big.mark = ","), caption = "Dropped species x ecoregion pairs by ecoregion and component.")
Dropped species x ecoregion pairs by ecoregion and component.
zone_key bird coral fish invertebrate mammal primary_producer turtle
CAC 2 12 191 248 3 21 0
CBS 7 3 14 113 5 0 0
EBS 38 20 123 260 12 2 4
EGOA 2 16 76 155 3 4 1
GOA 35 16 173 319 9 3 4
HAR 2 0 0 2 2 0 0
NECS 1 77 149 574 3 13 0
PIS 17 17 161 290 11 13 1
PUR 9 12 170 356 16 15 1
SECS 1 32 138 464 13 22 1
WAOR 3 9 129 133 4 3 2
WCGOA 1 45 203 702 2 7 1
Code
res_def |> filter(verdict == "dropped") |>
  group_by(sp_cat, scientific_name, common_name) |>
  summarise(zones = paste(sort(zone_key), collapse = ", "), pairs = n(), cells = sum(n_cells), .groups = "drop") |>
  arrange(desc(cells)) |> head(25) |>
  kable(format.args = list(big.mark = ","), caption = "The 25 taxa losing the most cells to the rule (for eyeballing, not a ranking of importance).")
The 25 taxa losing the most cells to the rule (for eyeballing, not a ranking of importance).
sp_cat scientific_name common_name zones pairs cells
invertebrate Amphicteis gunneri NA CAC, CBS, EBS, GOA, PIS 5 429,158
fish Cyclothone braueri spottail anglemouth CAC, EBS, GOA, PIS, PUR, WAOR 6 401,387
bird Pluvialis squatarola Grey Plover EBS, GOA, PIS 3 390,028
fish Argyropelecus lychnus silvery hatchetfish EBS, GOA, NECS, PIS, SECS, WCGOA 6 362,118
invertebrate Cranchia scabra cockatoo squid EBS, GOA, PIS 3 358,226
fish Arctozenus risso white barracudina EBS, EGOA, PIS, PUR, SECS, WCGOA 6 355,646
fish Electrona risso Electric lantern fish EBS, GOA, NECS, PIS, SECS, WAOR, WCGOA 7 355,184
invertebrate Pyroteuthis margaritifera Jewel enope squid CAC, EBS, PIS 3 326,798
invertebrate Bentheogennema intermedia NA EBS, GOA, PIS 3 325,454
fish Cetorhinus maximus giant basking shark EBS, EGOA, GOA, PIS, WAOR, WCGOA 6 321,097
fish Ceratoscopelus townsendi dogtooth lampfish EBS, EGOA, GOA, NECS, PIS 5 319,987
fish Diaphus metopoclampus Spothead lantern fish EBS, GOA, PIS 3 313,904
mammal Grampus griseus Risso’s Dolphin EBS, GOA, PIS, PUR 4 307,278
fish Notoscopelus resplendens patchwork lampfish EBS, GOA, PIS, PUR, WAOR 5 304,850
mammal Balaenoptera musculus Blue Whale EBS, EGOA, PIS, PUR, SECS 5 303,634
fish Lipolagus ochotensis Eared blacksmelt EBS, GOA, PIS 3 292,565
invertebrate Chiroteuthis veranyi long-armed squid EBS, PIS 2 291,530
invertebrate Hymenodora glacialis northern ambereye EBS, GOA, PIS 3 287,374
fish Cyclothone signata showy bristlemouth EBS, GOA, PIS 3 273,516
fish Brama japonica Pacific pomfret EBS, PIS 2 269,750
invertebrate Hemipenaeus carpenteri NA CAC, EBS, GOA, NECS, PIS, SECS 6 254,908
mammal Balaenoptera edeni Bryde’s Whale NECS, PIS, SECS 3 241,716
invertebrate Dacrydium vitreum NA CAC, CBS, EBS, GOA, PIS, WAOR 6 240,987
bird Calidris alba Sanderling CBS, EBS, HAR 3 238,996
fish Tetragonurus cuvieri smalleye squaretail GOA, NECS, PIS 3 238,915

12 Sensitivity: buffer x effort proxy x ratio

Each row is the whole scored set under one parameter choice; effort is the proxy applied to ALL taxa (order, megafauna) or default (megafauna for air-breathers, order for the rest). The anchor columns say whether the four v7c turtles fall out of EBS and whether the right whale falls out of EGOA and WCGOA. The D10 default row is marked.

Code
sens_one <- function(d_k, eff_k, ratio_k) {
  x <- res_sens |> filter(d == d_k)
  x <- if (eff_k == "default") filter(x, eff == eff_default) else filter(x, eff == eff_k)
  x <- x |> mutate(verdict = verdict_at(pick(everything()), ratio_k))
  dr <- filter(x, verdict == "dropped")
  tibble(d_km = d_k, effort = eff_k, ratio = ratio_k,
         pairs_dropped = nrow(dr), species_dropped = n_distinct(dr$mdl_key), cells_dropped = sum(dr$n_cells),
         unsearched = sum(x$verdict == "unsearched"),
         turtles_ebs = sum(dr$scientific_name %in% v7c_turtles & dr$zone_key == "EBS"),
         rw_gulf = sum(dr$scientific_name == "Eubalaena glacialis" & dr$zone_key %in% c("EGOA", "WCGOA")),
         goa_turtles = sum(dr$sp_cat == "turtle" & dr$zone_key == "GOA"))
}
sens <- expand_grid(d_k = d_all, eff_k = c("order", "megafauna", "default"), ratio_k = ratio_all) |>
  pmap_dfr(sens_one) |>
  mutate(anchors_out = turtles_ebs == length(v7c_turtles) & rw_gulf == 2L,
         is_default  = d_km == d_default & effort == "default" & ratio == occ_ratio)
sens |> transmute(`d (km)` = d_km, effort, ratio, `pairs dropped` = pairs_dropped, `species dropped` = species_dropped,
                  `cells dropped` = cells_dropped, unsearched,
                  `v7c turtles out of EBS (of 4)` = turtles_ebs, `right whale out of Gulf (of 2)` = rw_gulf,
                  `turtles out of GOA` = goa_turtles, `both anchors` = anchors_out, default = ifelse(is_default, "<- D10", "")) |>
  kable(format.args = list(big.mark = ","), caption = "Sensitivity of the rule to the record buffer d, the effort proxy and the ratio (OBIS only).")
Sensitivity of the rule to the record buffer d, the effort proxy and the ratio (OBIS only).
d (km) effort ratio pairs dropped species dropped cells dropped unsearched v7c turtles out of EBS (of 4) right whale out of Gulf (of 2) turtles out of GOA both anchors default
0 order 0.25 5,689 3,922 82,536,798 32,892 0 2 0 FALSE
0 order 0.50 7,205 4,643 107,025,303 32,892 0 2 0 FALSE
0 order 1.00 8,034 4,968 120,937,433 32,892 0 2 0 FALSE
0 megafauna 0.25 7,190 4,634 136,270,374 32,819 4 2 4 TRUE
0 megafauna 0.50 8,734 5,205 163,906,043 32,819 4 2 4 TRUE
0 megafauna 1.00 9,353 5,392 175,530,508 32,819 4 2 4 TRUE
0 default 0.25 5,721 3,938 85,286,079 32,896 4 2 4 TRUE
0 default 0.50 7,241 4,655 110,668,503 32,896 4 2 4 TRUE
0 default 1.00 8,051 4,970 124,128,954 32,896 4 2 4 TRUE
100 order 0.25 5,689 3,922 82,536,798 32,892 0 2 0 FALSE
100 order 0.50 7,205 4,643 107,025,303 32,892 0 2 0 FALSE
100 order 1.00 8,034 4,968 120,937,433 32,892 0 2 0 FALSE
100 megafauna 0.25 7,190 4,634 136,270,374 32,819 4 2 4 TRUE
100 megafauna 0.50 8,734 5,205 163,906,043 32,819 4 2 4 TRUE
100 megafauna 1.00 9,353 5,392 175,530,508 32,819 4 2 4 TRUE
100 default 0.25 5,721 3,938 85,286,079 32,896 4 2 4 TRUE <- D10
100 default 0.50 7,241 4,655 110,668,503 32,896 4 2 4 TRUE
100 default 1.00 8,051 4,970 124,128,954 32,896 4 2 4 TRUE
250 order 0.25 5,689 3,922 82,536,798 32,892 0 2 0 FALSE
250 order 0.50 7,205 4,643 107,025,303 32,892 0 2 0 FALSE
250 order 1.00 8,034 4,968 120,937,433 32,892 0 2 0 FALSE
250 megafauna 0.25 7,190 4,634 136,270,374 32,819 4 2 4 TRUE
250 megafauna 0.50 8,734 5,205 163,906,043 32,819 4 2 4 TRUE
250 megafauna 1.00 9,353 5,392 175,530,508 32,819 4 2 4 TRUE
250 default 0.25 5,721 3,938 85,286,079 32,896 4 2 4 TRUE
250 default 0.50 7,241 4,655 110,668,503 32,896 4 2 4 TRUE
250 default 1.00 8,051 4,970 124,128,954 32,896 4 2 4 TRUE

13 Sensitivity: the baseline the record rate is judged against

Not written to the CSV: the same counts judged against the OTHER baseline. The default (OCC_BASELINE=zones, msens 0.63.0) compares an ecoregion with the species’ record rate across its other ecoregions of the set (the 12 BOEM ecoregions, Tim’s “US denominator”); the rule as first written (range) used the species’ WHOLE modelled range. For a species whose modelled range is far wider than where it is recorded (the right whale: IUCN range x AquaMaps suitability covers the whole North Atlantic, records are on the shelf) the whole-range baseline is diluted (7,099 blocks, 352 with a record) and an ecoregion cannot be significantly below it, while the other-ecoregions baseline (41 % of blocks recorded on the Northeast shelf) is what the anchor needs. Both are computed from the stored counts (no extra run; the CH / narrow-range overrides are NOT re-derived, so the columns are “before overrides”).

Code
alt_cols <- if (occ_baseline == "zones") c("n_searched_all", "n_occupied_all") else c("n_searched_zones", "n_occupied_zones")
alt_name <- if (occ_baseline == "zones") "whole range" else "other ecoregions"
def_name <- if (occ_baseline == "zones") "other ecoregions" else "whole range"
t_alt <- region_effort_test(res_def$n_searched, res_def$n_occupied, res_def[[alt_cols[1]]], res_def[[alt_cols[2]]],
                            n_records = res_def$n_records, alpha = occ_alpha, ratio = occ_ratio)
us <- res_def |> mutate(p_core_alt = t_alt$p_core, p_value_alt = t_alt$p_value, verdict_alt = t_alt$verdict)

us |> group_by(sp_cat) |>
  summarise(pairs = n(), !!glue("dropped, {def_name} baseline (default, before overrides)") := sum(verdict_raw == "dropped"),
            !!glue("dropped, {alt_name} baseline (before overrides)") := sum(verdict_alt == "dropped"),
            !!glue("unsearched, {alt_name} baseline") := sum(verdict_alt == "unsearched"), .groups = "drop") |>
  kable(format.args = list(big.mark = ","), caption = "Pairs dropped by the rule under the two baselines (default buffer, effort and ratio).")
Pairs dropped by the rule under the two baselines (default buffer, effort and ratio).
sp_cat pairs dropped, other ecoregions baseline (default, before overrides) dropped, whole range baseline (before overrides) unsearched, whole range baseline
bird 946 118 104 350
coral 1,979 260 129 1,353
fish 15,515 1,527 1,450 8,342
invertebrate 33,766 3,616 2,274 23,766
mammal 366 86 27 123
primary_producer 1,273 103 75 899
turtle 50 15 14 1
Code
us |> filter((sp_cat == "turtle" & zone_key %in% c("EBS", "GOA")) | (scientific_name == "Eubalaena glacialis" & zone_key %in% c("EGOA", "WCGOA", "NECS", "SECS"))) |>
  arrange(scientific_name, zone_key) |>
  transmute(common_name, zone_key, n_searched, n_occupied, `rate here` = signif(rate, 3),
            !!glue("p_core, {def_name}") := signif(p_core, 3), !!glue("verdict, {def_name}") := verdict_raw,
            !!glue("p_core, {alt_name}") := signif(p_core_alt, 3), !!glue("p, {alt_name}") := signif(p_value_alt, 3), !!glue("verdict, {alt_name}") := verdict_alt) |>
  kable(format.args = list(big.mark = ","), caption = glue("The anchors under both baselines (default = {def_name})."))
The anchors under both baselines (default = other ecoregions).
common_name zone_key n_searched n_occupied rate here p_core, other ecoregions verdict, other ecoregions p_core, whole range p, whole range verdict, whole range
Loggerhead Turtle EBS 238 0 0.00000 0.2540 dropped 0.2010 0.00e+00 dropped
Loggerhead Turtle GOA 537 0 0.00000 0.2820 dropped 0.2020 0.00e+00 dropped
Green Turtle EBS 254 0 0.00000 0.1320 dropped 0.0886 0.00e+00 dropped
Green Turtle GOA 538 0 0.00000 0.1460 dropped 0.0891 0.00e+00 dropped
Leatherback Turtle EBS 268 0 0.00000 0.2650 dropped 0.0936 0.00e+00 dropped
Leatherback Turtle GOA 538 3 0.00558 0.2910 dropped 0.0939 0.00e+00 dropped
North Atlantic Right Whale EGOA 79 3 0.03800 0.2610 dropped 0.0497 4.43e-01 kept
North Atlantic Right Whale NECS 284 116 0.40800 0.1090 kept 0.0346 1.00e+00 kept
North Atlantic Right Whale SECS 211 36 0.17100 0.2640 kept 0.0459 1.00e+00 kept
North Atlantic Right Whale WCGOA 103 4 0.03880 0.2700 dropped 0.0497 4.14e-01 kept
Olive Ridley Turtle EBS 167 0 0.00000 0.0685 dropped 0.0707 4.80e-06 dropped
Olive Ridley Turtle GOA 538 0 0.00000 0.0794 dropped 0.0715 0.00e+00 dropped

14 Output: the gate and the weights the merge consumes

D11, “gate + weight”: msens::occurrence_exclusions(gate = "zero") of the default run — a species leaves an ecoregion only where it has NO record under adequate effort (OCC_GATE=all = every dropped pair, the rule as first written). A species that IS recorded but at a rate well below its other ecoregions is not excluded: the first full run dropped 1,904 such pairs, among them the bowhead whale from the Bering Sea (23 of 458 searched blocks against 44 % elsewhere — its wintering ground, surveyed mostly in summer when the whales are north), the beluga (51 of 604; coastal stocks), the sperm whale and the common eider — seasonal or coastal presence the block rate cannot tell from absence. Those pairs, and every kept pair below its reference rate, get msens::encounter_weight() instead: w = min(1, rate / p_core), a multiplier on the merged value inside the ecoregion under REGION_WEIGHT=1 (default off; it inherits the same survey-season bias, so it is a flag for the 2026-11-12 review, not a default). The shape and the extra columns follow data/v7c/zone_exclusions.csv (zone_fld, the evidence). The full verdict table (kept / unsearched / dropped, every pair) is cached beside the counts as rule_default.parquet for review.

Code
ex  <- occurrence_exclusions(res_def, gate = occ_gate)
out <- ex |>
  left_join(res_def, by = c("mdl_key", "zone_key")) |>
  transmute(
    mdl_key, zone_fld = "ecoregion_key", zone_key, taxon_id, scientific_name, common_name, sp_cat,
    effort = eff_default, d_km = d_default, ratio = occ_ratio, alpha = occ_alpha, block_cells = occ_block,
    n_cells, n_searched, n_occupied, n_records, n_searched_all, n_occupied_all,
    p_core = signif(p_core, 8), rate = signif(rate, 8), n_min, p_value = signif(p_value, 8),
    verdict, label,
    reason = as.character(glue("occurrence rule E: {n_occupied} of {n_searched} searched 0.5-degree blocks hold a record (rate {signif(rate, 3)}), against {signif(p_core, 3)} in the species' {if (occ_baseline == 'zones') 'other ecoregions' else 'whole range'} (p = {signif(p_value, 2)})")),
    source = as.character(glue("OBIS {obis_h3_release}"))) |>
  arrange(mdl_key, zone_key)
stopifnot("every exclusion row must be a dropped pair" = all(out$verdict == "dropped"), !anyDuplicated(out[c("mdl_key", "zone_key")]),
          "under the zero gate every exclusion has no record" = occ_gate == "all" || all(out$n_occupied == 0))

# the weights: a pair the rule dropped on the RATE (records exist) is kept with its ratio; dropped-with-zero stays 0
# (redundant with the gate, by design); unsearched / overridden = 1 (unsampled is unknown, critical habitat untouched)
wt <- res_def |>
  mutate(verdict = ifelse(verdict == "dropped" & n_occupied > 0 & occ_gate == "zero", "kept", verdict)) |>
  encounter_weight() |>
  filter(w < 1) |>
  transmute(mdl_key, zone_fld = "ecoregion_key", zone_key, taxon_id, scientific_name, common_name, sp_cat,
            effort = eff_default, d_km = d_default, block_cells = occ_block, n_cells, n_searched, n_occupied, n_records,
            rate = signif(rate, 8), p_core = signif(p_core, 8), w = signif(w, 6), w_reason,
            reason = as.character(glue("encounter weight: rate {signif(rate, 3)} here vs {signif(p_core, 3)} in the species' {if (occ_baseline == 'zones') 'other ecoregions' else 'whole range'} -> w = {signif(w, 3)}")),
            source = as.character(glue("OBIS {obis_h3_release}"))) |>
  arrange(mdl_key, zone_key)
stopifnot("a gated pair must weigh 0 and a weighted pair must have records" =
            all((wt$w == 0) == (paste(wt$mdl_key, wt$zone_key) %in% paste(out$mdl_key, out$zone_key))) || occ_gate == "all",
          !anyDuplicated(wt[c("mdl_key", "zone_key")]))

# the full verdict table, for review (cache, not a deliverable)
dbWriteTable(con, "tmp_df", res_def |> select(-any_of(c("run", "eff"))), overwrite = TRUE)
dbExecute(con, glue("COPY tmp_df TO '{dir_occ}/rule_default_{sig}.parquet' (FORMAT parquet, COMPRESSION zstd)")); dbExecute(con, "DROP TABLE tmp_df")
[1] 53895
[1] 0
Code
if (occ_test_n > 0) {
  message("OCC_TEST_N smoke test: data/v11/zone_exclusions_occ.csv and the manifest are NOT written")
} else {
  write_csv(out, f_csv, na = "")
  write_csv(wt, f_wcsv, na = "")
}
kable(head(out |> select(mdl_key, scientific_name, zone_key, n_cells, n_searched, n_occupied, n_records, p_core, p_value, label), 15),
      format.args = list(big.mark = ","), caption = glue("First rows of data/v11/zone_exclusions_occ.csv ({nrow(out)} rows, gate = {occ_gate})."))
First rows of data/v11/zone_exclusions_occ.csv (3817 rows, gate = zero).
mdl_key scientific_name zone_key n_cells n_searched n_occupied n_records p_core p_value label
ms_merge|BOTW:22679946 Branta bernicla GOA 84 17 0 23 0.3333333 0.0010150 documented occurrence only
ms_merge|BOTW:22680405 Somateria mollissima GOA 15,396 238 0 1 0.0919831 0.0000000 documented occurrence only
ms_merge|BOTW:22680441 Melanitta perspicillata CBS 23 17 0 3 0.3316750 0.0010587 documented occurrence only
ms_merge|BOTW:22693178 Numenius phaeopus EBS 79 27 0 6 0.1376812 0.0183245 documented occurrence only
ms_merge|BOTW:22693178 Numenius phaeopus GOA 194 35 0 4 0.1461538 0.0039654 documented occurrence only
ms_merge|BOTW:22693369 Calidris alba HAR 47,797 59 0 0 0.0560036 0.0333619 NA
ms_merge|BOTW:22693396 Calidris minutilla CBS 3,555 69 0 6 0.0878143 0.0017609 documented occurrence only
ms_merge|BOTW:22693427 Calidris alpina PUR 4,467 53 0 0 0.0556765 0.0480178 NA
ms_merge|BOTW:22693735 Pluvialis fulva GOA 200 35 0 12 0.1625000 0.0020159 documented occurrence only
ms_merge|BOTW:22694240 Stercorarius pomarinus PUR 6,873 78 0 0 0.1773667 0.0000002 NA
ms_merge|BOTW:22694455 Larus atricilla PIS 242 12 0 1 0.6244344 0.0000079 documented occurrence only
ms_merge|BOTW:22694455 Larus atricilla PUR 281 14 0 0 0.6301370 0.0000009 NA
ms_merge|BOTW:22694479 Xema sabini EBS 64,009 358 0 16 0.1501272 0.0000000 documented occurrence only
ms_merge|BOTW:22694502 Rissa brevirostris GOA 24,214 197 0 5 0.0792193 0.0000001 documented occurrence only
ms_merge|BOTW:22694629 Sterna paradisaea GOA 200 35 0 60 0.1075269 0.0186565 documented occurrence only
Code
wt |> filter(w > 0) |> group_by(sp_cat) |>
  summarise(pairs_weighted = n(), species = n_distinct(mdl_key), `w median` = round(median(w), 3), `w < 0.25` = sum(w < 0.25), `w < 0.5` = sum(w < 0.5), .groups = "drop") |>
  kable(format.args = list(big.mark = ","), caption = glue("data/v11/zone_weights_occ.csv: pairs weighted below 1 by component ({sum(wt$w > 0)} rows; {sum(wt$w == 0)} more are the gated pairs at 0)."))
data/v11/zone_weights_occ.csv: pairs weighted below 1 by component (8335 rows; 3817 more are the gated pairs at 0).
sp_cat pairs_weighted species w median w < 0.25 w < 0.5
bird 249 123 0.346 92 165
coral 277 178 0.460 62 153
fish 2,987 1,668 0.500 721 1,491
invertebrate 4,488 2,811 0.480 1,034 2,335
mammal 131 50 0.305 55 90
primary_producer 185 118 0.405 40 102
turtle 18 6 0.428 5 11
Code
wt |> filter(w > 0, sp_cat %in% c("mammal", "turtle")) |> arrange(w) |>
  select(common_name, zone_key, n_occupied, n_searched, rate, p_core, w) |> head(25) |>
  mutate(across(c(rate, p_core, w), \(v) signif(v, 3))) |>
  kable(caption = "The 25 most downweighted mammal / turtle pairs (recorded, but far below the species' rate elsewhere).")
The 25 most downweighted mammal / turtle pairs (recorded, but far below the species’ rate elsewhere).
common_name zone_key n_occupied n_searched rate p_core w
Blue Whale PIS 2 1121 0.00178 0.1230 0.0145
Leatherback Turtle GOA 3 538 0.00558 0.2910 0.0192
Killer Whale CBS 1 393 0.00254 0.1180 0.0216
Loggerhead Turtle WAOR 1 137 0.00730 0.2450 0.0298
California Sea Lion GOA 3 133 0.02260 0.7340 0.0307
Harbor Porpoise CBS 7 359 0.01950 0.4200 0.0465
Blue Whale EBS 2 443 0.00451 0.0951 0.0475
Baird’s Beaked Whale EBS 4 1036 0.00386 0.0705 0.0547
Beluga Whale HAR 1 57 0.01750 0.3180 0.0552
Green Turtle WAOR 1 137 0.00730 0.1260 0.0578
Fin Whale PIS 12 702 0.01710 0.2780 0.0614
Short-Finned Pilot Whale WAOR 1 137 0.00730 0.1050 0.0697
Risso’s Dolphin GOA 7 538 0.01300 0.1860 0.0701
Killer Whale PIS 12 1121 0.01070 0.1410 0.0761
Striped Dolphin PUR 1 83 0.01200 0.1530 0.0785
Pantropical Spotted Dolphin PUR 1 83 0.01200 0.1530 0.0786
Pacific White-Sided Dolphin EBS 6 341 0.01760 0.2180 0.0806
Cuvier’s Beaked Whale GOA 4 538 0.00743 0.0766 0.0970
Spotted Seal GOA 2 42 0.04760 0.4810 0.0991
Sei Whale GOA 3 538 0.00558 0.0549 0.1020
Dwarf Sperm Whale CAC 2 283 0.00707 0.0678 0.1040
Ribbon Seal CBS 18 408 0.04410 0.4150 0.1060
Minke Whale PIS 16 1121 0.01430 0.1330 0.1070
Humpback Whale EGOA 3 136 0.02210 0.2050 0.1080
Olive Ridley Turtle EGOA 1 136 0.00735 0.0673 0.1090

15 Manifest

Code
if (occ_test_n == 0) {
  h <- digest::digest(file = as.character(f_csv), algo = "xxhash64")
  by_comp <- tab_comp |> select(sp_cat, taxa, species_dropped, dropped, unsearched, override_protected, override_narrow, cells_dropped)
  write_manifest(
    manifest, target = "explore_occurrence_rule", content_hash = h,
    stats = list(
      version          = ver,
      source_version   = ver_src,
      msens_version    = as.character(packageVersion("msens")),
      obis_release     = obis_h3_release,
      obis_snapshot    = obis_info$obis_snapshot,
      worms_version    = obis_info$worms_version,
      channels         = list("obis"),                      # GBIF (speciesgrids), iNat, strandings: later additions
      parameters       = list(effort = "megafauna for air-breathers (mammal, turtle, bird), order otherwise", d_km = d_default,
                              ratio = occ_ratio, alpha = occ_alpha, block_cells = occ_block, min_cells = occ_min_cells,
                              year_min = occ_year_min, d_sensitivity = as.list(d_all), ratio_sensitivity = as.list(ratio_all)),
      n_taxa           = nrow(tx),
      n_taxa_no_surface= n_nosurface,
      n_rule_rows      = nrow(res_def),
      gate             = occ_gate,
      n_pairs_dropped  = nrow(out),
      n_species_dropped= n_distinct(out$mdl_key),
      cells_dropped    = sum(out$n_cells),
      n_pairs_rule_dropped = sum(res_def$verdict == "dropped"),
      n_pairs_weighted = sum(wt$w > 0),
      n_species_weighted = n_distinct(wt$mdl_key[wt$w > 0]),
      weights_csv      = list(path = "data/v11/zone_weights_occ.csv", rows = nrow(wt), xxhash64 = digest::digest(file = as.character(f_wcsv), algo = "xxhash64")),
      n_pairs_unsearched = sum(res_def$verdict == "unsearched"),
      by_component     = by_comp |> split(by_comp$sp_cat) |> map(\(x) as.list(select(x, -sp_cat))),
      anchors          = list(turtles_ebs_dropped = nrow(filter(anchor_ok$turtles_ebs, verdict == "dropped")),
                              turtles_ebs_rows    = nrow(anchor_ok$turtles_ebs),
                              right_whale_gulf_dropped = nrow(filter(anchor_ok$rw_gulf, verdict == "dropped"))),
      baseline         = occ_baseline,
      sensitivity_other_baseline = list(
        baseline = alt_name,
        pairs_dropped_before_overrides = sum(us$verdict_alt == "dropped"),
        turtles_ebs_dropped = sum(us$verdict_alt == "dropped" & us$scientific_name %in% v7c_turtles & us$zone_key == "EBS"),
        right_whale_gulf_dropped = sum(us$verdict_alt == "dropped" & us$scientific_name == "Eubalaena glacialis" & us$zone_key %in% c("EGOA", "WCGOA"))),
      exclusions_csv   = list(path = "data/v11/zone_exclusions_occ.csv", rows = nrow(out), xxhash64 = h),
      cache_signature  = sig),
    force = force_target("explore_occurrence_rule"))
  message(glue("explore_occurrence_rule: {nrow(out)} exclusion rows -> {basename(f_csv)} ({h})"))
}
dbDisconnect(con, shutdown = TRUE)

16 Assertion: both anchors fall out at the defaults

The rule is only adopted if it reproduces, with no hand-written row, what v7c did by hand. A failure means the parameters, the effort definition or (most likely at this stage) the channels are wrong, not that the anchor is wrong: the printed rows above say which of the three.

Code
run_anchors <- occ_test_n == 0 || nrow(anchor_ok$rw_gulf) > 0
if (run_anchors) {
  stopifnot(
    "the v7c turtles (loggerhead, green, leatherback, olive ridley) must each have an EBS row" =
      setequal(anchor_ok$turtles_ebs$scientific_name, v7c_turtles),
    "right whale needs a row in both EGOA and WCGOA" = setequal(anchor_ok$rw_gulf$zone_key, c("EGOA", "WCGOA")))
  gated <- paste(out$mdl_key, out$zone_key)
  rw_w  <- wt |> semi_join(anchor_ok$rw_gulf, by = c("mdl_key", "zone_key"))
  # the turtles must be GATED (zero records); the right whale is gated or, with its handful of Gulf records, weighted
  # at or below the ratio (3 of 79 blocks vs 26 % on its other ecoregions -> w 0.14): Tim's "downweight, not drop"
  bad <- bind_rows(
    anchor_ok$turtles_ebs |> filter(!paste(mdl_key, zone_key) %in% gated),
    anchor_ok$rw_gulf |> filter(!paste(mdl_key, zone_key) %in% gated,
                                !paste(mdl_key, zone_key) %in% paste(rw_w$mdl_key, rw_w$zone_key)[rw_w$w <= occ_ratio]))
  if (nrow(rw_w)) message(glue("right whale Gulf weights: {paste(rw_w$zone_key, signif(rw_w$w, 3), sep = ' = ', collapse = ', ')}"))
  if (nrow(bad) > 0) {
    v_alt <- us$verdict_alt[match(paste(bad$mdl_key, bad$zone_key), paste(us$mdl_key, us$zone_key))]
    stop("ANCHOR NOT DROPPED at the defaults (effort = megafauna, d = ", d_default, " km, ratio ", occ_ratio, ", baseline ", occ_baseline, ", OBIS only):\n",
         paste0("  ", bad$scientific_name, " x ", bad$zone_key, ": ", bad$verdict, " (", bad$n_occupied, " of ", bad$n_searched,
                " blocks have a record against ", signif(bad$p_core, 3), " in the ", def_name, ", p = ", signif(bad$p_value, 2),
                "; need ", bad$n_min, " searched; ", alt_name, " baseline: ", v_alt, ")", collapse = "\n"),
         "\nOutside OCC_TEST_N the exclusions CSV and the manifest above were written regardless. Read the anchor and baseline tables: a failure means the baseline, ",
         "the effort definition or the channels (OBIS only) are wrong for this species, not necessarily the anchor.", call. = FALSE)
  }
  message(glue("anchors: the four v7c turtles are gated out of EBS; the right whale x EGOA + WCGOA is ",
               "{if (all(paste(anchor_ok$rw_gulf$mdl_key, anchor_ok$rw_gulf$zone_key) %in% gated)) 'gated' else 'weighted at or below the ratio'}"))
}