Ingest SWFSC California Current cetacean densities (cce)

Becker et al. 2020: 13 species, summer–fall habitat-based density on 0.1° cells, area-weighted onto the global 0.05° grid → population-percentile suitability [1,100]

Published

2026-10-29

NOAA Southwest Fisheries Science Center (SWFSC) habitat-based density models for 13 cetacean species in the California Current Ecosystem (CCE), summer–fall (Becker et al. 2020), put on the MarineSensitivity global 0.05° cell grid (global05) as dataset cce, and mapped onto the merge’s [1,100] suitability scale by the population-percentile transform (msens::density_to_suit(method = "ud"), v11 Q6 / D12), the same recipe as the gm and nc density ingests.

cce is registered but not merged by default: like gm and nc, its annual models enter the merge only under FOLD_DENSITY=1 (the interval models are published for the species app and never max()ed into a year), and merge_models_prep excludes the dataset otherwise.

1 Source

The models come from line-transect ship surveys by SWFSC in the CCE, nine summer–fall surveys between 1991 and 2018. Habitat-based density models were fitted to those surveys using dynamic ocean covariates from a model calibrated to the CCE. The authors averaged the predictions over the survey seasons and assigned them to a 0.1° grid, clipped at the coast and the study-area edge. The delivery is an Esri file geodatabase with one layer per species, holding 12,257 cells each. Every cell carries DENSITY (animals km⁻²), UNCERTAINTY, AREA_SQKM and ABUNDANCE (DENSITY × AREA_SQKM). The geodatabase lives at ~/_big/msens/raw/sdm/swfsc/ (cce_gdb in libs/paths.R; CCE_GDB overrides it).

Two points from the InPort metadata (item 64349 and its attribute entity 64350) matter here:

  • UNCERTAINTY is a coefficient of variation. The attribute definition (quoted in Credits and use constraints) calls it “Numerical uncertainty value (CV)”, with -99999 where no estimate exists. No layer here uses that sentinel. The values run from 0.12 to 6.4, and a CV above 1 is legitimate for a sparse species.
  • AREA_SQKM is the true ellipsoidal area of each clipped cell. The source chunk shows that it matches sf::st_area() on WGS84 to within 0.1 %. Because the 0.05° cell areas below are also ellipsoidal, the abundance check can be held to 1 %.

The record’s abstract also lists sperm whale and a small-beaked-whale guild (Mesoplodon spp. and Cuvier’s beaked whale). Those surfaces are not in this geodatabase, which holds 13 layers.

2 What this notebook does

  1. Reads the 13 layers and asserts what it relies on: 12,257 cells per layer, identical geometry across layers, one species and one season per layer, and ABUNDANCE = DENSITY × AREA_SQKM.
  2. Resolves each SPECIES_2 to a WoRMS AphiaID from the pipeline’s own WoRMS snapshot (spp.duckdb worms), with a live worrms cross-check when the network is available.
  3. Area-weighted regrid. For each 0.05° cell c: \(\hat d_c = \sum_p d_p\,A(p \cap c) \,/\, \sum_p A(p \cap c)\). Here \(A\) is the exact overlap area in km², computed as the exactextractr coverage fraction times the cell’s WGS84 ellipsoidal area, which depends on latitude. The same weighting gives the CV and the covered fraction of each cell. The rule lives in msens (poly_cell_overlap(), cells_area_mean()), and test-ingest.R checks it against a synthetic fixture. The polygon-cell weights are computed once, because all 13 layers share the same geometry.
  4. Checks every species: the regridded abundance \(\sum_c \hat d_c \cdot \text{covered km}^2\) is within 1 % of \(\sum\) ABUNDANCE, no output cell lies outside the source extent, and every density is ≥ 0.
  5. Value transform (v11 Q6, D12). Per model, after regridding, val = density_to_suit(d, "ud", area = cell area_km2): 100 minus the percent of the modelled population in cells strictly denser than this one, so the densest cell is 100 and the cells with val >= 100 - p are exactly the p % core. Cells with val < 1 are dropped (the merge’s floor). The transform is scale-free. The old recipe (CCE_TRANSFORM=cap: linear to the species’ p99.5 of positive density) stays available and is compared per model in data/cce_transform_compare.csv.
  6. Interval and annual models. CCE models one interval, summer-fall, so the annual model is that interval: msens::density_annual(n_intervals = 1) is the identity on the density (asserted), and the annual surface is the same ud transform of the same cells. Both keys are written (cce|WORMS:{id}|summer-fall for the species app, cce|WORMS:{id} for the merge) so cce has the same two-part / three-part key shape as gm and nc. They describe summer–fall conditions only; the annual name does not mean the model says anything about winter–spring.
  7. Writes the long Parquet (mdl_key, cell_id, val, plus dens, cv, frac) to the version’s dist/dataset=cce/, model_cce.csv beside it, and the manifest. CCE_COG=1 also writes one 2-band Float32 COG per species (density, CV).
NoteThe CV band is an approximation

An area-weighted mean is right for a density, which is intensive: the regridded abundance equals the source abundance. It is not right for a CV, because the CVs of the parts of a cell do not average linearly. The CV of a mixed cell’s density would need the covariance between its parts, which the delivery does not carry. The cv column is therefore an area-weighted average of the source CVs. It is exact only where an output cell lies inside a single source cell, and the regrid section counts how many cells do.

Code
flowchart LR
  gdb["swfsc_cce_becker_et_al_2020b.gdb<br/>13 layers x 12,257 cells (0.1 deg)<br/>DENSITY, UNCERTAINTY (CV)"] --> w["msens::poly_cell_overlap()<br/>overlap km2 per (polygon, cell)<br/>computed once: shared geometry"]
  grid["r_cellid_global.tif<br/>global05, 0.05 deg"] --> w
  w --> m["msens::cells_area_mean()<br/>per species: density, cv, frac"]
  worms[("spp.duckdb worms<br/>+ worrms cross-check")] --> key["mdl_key = cce, WORMS id<br/>(summer-fall | annual)"]
  m --> chk{"checks<br/>abundance within 1 pct<br/>extent, counts, density >= 0"}
  chk --> ud["msens::density_to_suit(ud)<br/>area = cell table area_km2<br/>msens::density_annual(n = 1)"]
  key --> ud
  ud --> pq[("dist/dataset=cce/*.parquet<br/>mdl_key, cell_id, val, dens, cv, frac")]
  ud --> csv["model_cce.csv<br/>+ data/swfsc_cce_models.csv"]
  chk -.-> cog["CCE_COG=1: 2-band Float32 COG"]
flowchart LR
  gdb["swfsc_cce_becker_et_al_2020b.gdb<br/>13 layers x 12,257 cells (0.1 deg)<br/>DENSITY, UNCERTAINTY (CV)"] --> w["msens::poly_cell_overlap()<br/>overlap km2 per (polygon, cell)<br/>computed once: shared geometry"]
  grid["r_cellid_global.tif<br/>global05, 0.05 deg"] --> w
  w --> m["msens::cells_area_mean()<br/>per species: density, cv, frac"]
  worms[("spp.duckdb worms<br/>+ worrms cross-check")] --> key["mdl_key = cce, WORMS id<br/>(summer-fall | annual)"]
  m --> chk{"checks<br/>abundance within 1 pct<br/>extent, counts, density >= 0"}
  chk --> ud["msens::density_to_suit(ud)<br/>area = cell table area_km2<br/>msens::density_annual(n = 1)"]
  key --> ud
  ud --> pq[("dist/dataset=cce/*.parquet<br/>mdl_key, cell_id, val, dens, cv, frac")]
  ud --> csv["model_cce.csv<br/>+ data/swfsc_cce_models.csv"]
  chk -.-> cog["CCE_COG=1: 2-band Float32 COG"]
Figure 1: SWFSC CCE geodatabase → exact overlap weights (once) → per-species area-weighted density + CV → checks → population-percentile val (ud) → interval + annual Parquet, model table and manifest

3 Setup

Code
librarian::shelf(
  arrow, DBI, digest, dplyr, duckdb, fs, ggplot2, glue, here, jsonlite, knitr, logger, patchwork, purrr,
  readr, rnaturalearth, sf, stringr, terra, tibble, tidyr, worrms, xml2, quiet = T)
library(msens)                      # the installed msens (poly_cell_overlap / density_to_suit / density_annual); never via shelf(), which can reinstall a stale main
source(here("libs/paths.R"))
source(here("libs/vars.R"))
source(here("libs/duckdb_budget.R"))
options(readr.show_col_types = FALSE)
stopifnot(
  "msens >= 0.64.1 needed (poly_cell_overlap, cells_area_mean, density_to_suit, density_annual)" =
    packageVersion("msens") >= "0.64.1")

ds_key <- "cce"
season <- "summer-fall"     # the SEASON field ("Summer-Fall"), slugged for keys and file names

# source geodatabase (read-only): libs/paths.R `cce_gdb` (~/_big/msens/raw/sdm/swfsc/...); CCE_GDB overrides it
gdb <- path_expand(cce_gdb)
stopifnot("source gdb not found; set CCE_GDB or hydrate raw/sdm/swfsc (scripts/pull_from_laptop.sh)" = dir_exists(gdb))

# outputs: the version's dist/ (the merge and build_registry read it), model_cce.csv beside it
dir_atlas  <- glue("{dir_big_v}/marine-atlas")
dir_dist   <- path_expand(glue("{dir_atlas}/dist/dataset={ds_key}")); dir_create(dir_dist)
mdl_csv    <- path_expand(glue("{dir_atlas}/dist/model_{ds_key}.csv"))
dir_cog    <- path_expand(glue("{dir_atlas}/cce_cog"))             # CCE_COG=1 only
dir_inport <- path_expand(glue("{dir_raw}/sdm/swfsc/inport_cce")); dir_create(dir_inport)
repo_csv   <- here("data/swfsc_cce_models.csv")
cmp_csv    <- here("data/cce_transform_compare.csv")
manifest   <- here("data/manifests/ingest_swfsc_cce.json"); dir_create(path_dir(manifest))
p_cap      <- 0.995                                                # the density percentile the OLD recipe used as the 100 point

cellid_tif <- path_expand(cellid_tif)          # GDAL does not expand "~"
stopifnot(file_exists(cellid_tif))
grid <- msens::grid_spec_for("global05", cellid_tif)

# flags (this notebook's own; default = the v11 recipe) ----
cce_transform <- tolower(Sys.getenv("CCE_TRANSFORM", "ud"))        # ud (v11) | cap (the linear-to-p99.5 recipe, for comparison)
stopifnot("CCE_TRANSFORM must be 'ud' or 'cap'" = cce_transform %in% c("ud", "cap"))
cce_cog   <- .flag("CCE_COG")                  # also write one 2-band (density, CV) Float32 COG per species
cce_fetch <- .flag("CCE_FETCH")                # re-download the InPort metadata records
log_info("cce: transform = {cce_transform}; COG = {cce_cog}; redo = {redo_ingest}")
log_info("source: {gdb}")
log_info("outputs: {dir_dist}")

# REDO_INGEST starts the dataset clean; otherwise the 26 files are simply overwritten in place (the
# parquet chunk asserts that exactly 26 are there afterwards)
if (redo_ingest) { dir_delete(dir_dist); dir_create(dir_dist) }
if (cce_cog) { if (dir_exists(dir_cog)) dir_delete(dir_cog); dir_create(dir_cog) }

4 Cell areas

The ud transform weights each cell by its area (the population in a cell is density × area). The cell table is a property of the grid, not of the release: this version’s sdm.duckdb is used when build_cell_grid has written it, else ver_prev’s (which build_cell_grid copies unchanged). It is opened read-only.

Code
sdm_cell_db <- c(sdm_db, glue("{dir_big}/{ver_prev}/sdm.duckdb")) |> path_expand() |> keep(file_exists) |> first()
stopifnot("no sdm.duckdb with a cell table (this version's or ver_prev's)" = !is.null(sdm_cell_db))
log_info("cell areas from {sdm_cell_db}")
dir_create(glue("{dir_big_v}/_tmp/cce"))
con_sdm <- dbConnect(duckdb(sdm_cell_db, read_only = TRUE))
duckdb_tune(con_sdm, glue("{dir_big_v}/_tmp/cce"))
ca <- dbGetQuery(con_sdm, "SELECT cell_id, area_km2 FROM cell")
dbDisconnect(con_sdm, shutdown = TRUE)
area_by_id <- rep(NA_real_, 7200 * 3600); area_by_id[ca$cell_id] <- ca$area_km2
# the cell table holds the OCEAN cells only, while the regridded surfaces fade into land cells along the
# coast (whole range, no land mask): those take the area of their latitude row (a cell's area depends on
# its row alone; the table's rows are constant to 1e-9 relative)
row_of <- \(id) (id - 1L) %/% 7200L + 1L
a_row  <- ca |> mutate(row = row_of(cell_id)) |> group_by(row) |>
  summarise(a = first(area_km2), spread = max(area_km2) / min(area_km2) - 1, .groups = "drop")
stopifnot("cell area is not constant within a row" = max(a_row$spread) < 1e-6)
area_by_row <- rep(NA_real_, 3600); area_by_row[a_row$row] <- a_row$a
cell_area <- function(id) {
  a <- area_by_id[id]; miss <- is.na(a)
  if (any(miss)) a[miss] <- area_by_row[row_of(id[miss])]
  stopifnot("a cell id has no area (no ocean cell in its row)" = !anyNA(a), all(a > 0))
  a }
log_info("cell table: {nrow(ca)} ocean cells, area {round(min(ca$area_km2), 3)}-{round(max(ca$area_km2), 1)} km2; ",
         "land cells take their row's area")
rm(ca)

5 Read the source

Code
lyrs <- st_layers(gdb)
src  <- set_names(lyrs$name) |> map(\(l) read_sf(gdb, l))

# the delivery we rely on: 13 layers x 12,257 cells, one species + season + study per layer
need <- c("SPECIES", "SPECIES_2", "SEASON", "STUDY", "STRATUM", "MODEL_TYPE",
          "DENSITY", "UNCERTAINTY", "AREA_SQKM", "ABUNDANCE")
stopifnot(
  "expected 13 layers"                 = length(src) == 13,
  "expected 12,257 cells per layer"    = all(map_int(src, nrow) == 12257L),
  "missing fields"                     = all(map_lgl(src, \(x) all(need %in% names(x)))),
  "one species per layer"              = all(map_int(src, \(x) n_distinct(x$SPECIES_2)) == 1L),
  "season is Summer-Fall"              = all(map_lgl(src, \(x) all(x$SEASON == "Summer-Fall"))),
  "stratum is CCE"                     = all(map_lgl(src, \(x) all(x$STRATUM == "CCE"))),
  "no NA density"                      = all(map_lgl(src, \(x) !anyNA(x$DENSITY))),
  "ABUNDANCE = DENSITY x AREA_SQKM"    = all(map_lgl(src, \(x)
    max(abs(x$ABUNDANCE - x$DENSITY * x$AREA_SQKM) / pmax(x$ABUNDANCE, 1e-12)) < 1e-4)))

# every layer carries the SAME cells in the SAME order, so the polygon->cell weights are computed once
geom_hash <- map_chr(src, \(x) digest::digest(st_as_binary(st_geometry(x))))
stopifnot("layers do not share one geometry" = n_distinct(geom_hash) == 1L)

# AREA_SQKM is the true (ellipsoidal) area: what lets the abundance check below be held to 1 %
geom   <- st_sf(geometry = st_geometry(src[[1]]))
op     <- sf_use_s2(FALSE)                     # planar GEOS predicate engine -> st_area on the ellipsoid
a_ell  <- as.numeric(st_area(geom)) / 1e6
sf_use_s2(op)
r_area <- a_ell / src[[1]]$AREA_SQKM
bb_src <- st_bbox(geom)

# the source lattice: full (unclipped) cells are 0.1 x 0.1 deg; how far are their edges from the
# 0.05-degree grid lines? (an offset makes output cells straddle two source cells)
full    <- abs(src[[1]]$Shape_Area - 0.01) < 1e-9
bb_full <- do.call(rbind, lapply(st_geometry(geom)[full], st_bbox))
off_05  <- \(v) v - round(v / 0.05) * 0.05
lat_off <- unique(round(off_05(bb_full[, "ymin"]), 6))
lon_off <- unique(round(off_05(bb_full[, "xmin"]), 6))
stopifnot("source cells are not one regular 0.1-degree lattice" =
            length(lon_off) == 1, length(lat_off) == 1,
            all(abs(bb_full[, "xmax"] - bb_full[, "xmin"] - 0.1) < 1e-6),
            all(abs(bb_full[, "ymax"] - bb_full[, "ymin"] - 0.1) < 1e-6))
log_info("source lattice: {sum(full)} full 0.1-degree cells, edges offset {lon_off} deg (lon), {lat_off} deg (lat) from the 0.05 grid lines")
log_info("AREA_SQKM vs ellipsoidal area: ratio {round(min(r_area[src[[1]]$AREA_SQKM > 1]), 4)}-{round(max(r_area[src[[1]]$AREA_SQKM > 1]), 4)} (cells > 1 km2); totals {round(sum(src[[1]]$AREA_SQKM))} vs {round(sum(a_ell))} km2")
stopifnot(abs(sum(a_ell) / sum(src[[1]]$AREA_SQKM) - 1) < 1e-3)

d_src <- imap_dfr(src, \(x, l) tibble(
  layer           = l,
  species         = x$SPECIES[1],
  scientific_name = x$SPECIES_2[1],
  n_src           = nrow(x),
  model_type      = x$MODEL_TYPE[1],
  density_min     = min(x$DENSITY),
  density_max     = max(x$DENSITY),
  cv_min          = min(x$UNCERTAINTY),
  cv_max          = max(x$UNCERTAINTY),
  n_cv_sentinel   = sum(x$UNCERTAINTY <= -99999),
  abundance_src   = sum(x$ABUNDANCE)))
kable(d_src |> mutate(across(c(density_min, density_max), \(v) formatC(v, format = "g", digits = 3))),
      digits = 4, format.args = list(big.mark = ","),
      caption = glue("Source layers ({unique(src[[1]]$STUDY)}): extent ",
                     "{paste(round(bb_src, 4), collapse = ', ')} (xmin, ymin, xmax, ymax)"))
Source layers (Becker et al 2020 NOAA Tech Memo 638): extent -131, 30.05, -117.0976, 48.5061 (xmin, ymin, xmax, ymax)
layer species scientific_name n_src model_type density_min density_max cv_min cv_max n_cv_sentinel abundance_src
Minke_whale_summer_fall Minke whale Balaenoptera acutorostrata 12,257 Habitat based density model 5.02e-05 0.00491 0.1216 0.2731 0 889.0718
Bairds_beaked_whale_summer_fall Bairds beaked whale Berardius bairdii 12,257 Habitat based density model 1.65e-09 0.0932 0.3770 1.7321 0 846.3933
Blue_whale_summer_fall Blue whale Balaenoptera musculus 12,257 Habitat based density model 9.67e-06 0.0117 0.3540 1.6233 0 1,239.0082
Fin_whale_summer_fall Fin whale Balaenoptera physalus 12,257 Habitat based density model 3.12e-06 0.0821 0.3773 6.3171 0 12,014.3889
Long_beaked_common_dolphin_summer_fall Long beaked common dolphin Delphinus capensis 12,257 Habitat based density model 1.21e-09 4.76 0.2721 2.0479 0 62,506.9965
Short_beaked_common_dolphin_summer_fall Short beaked common dolphin Delphinus delphis 12,257 Habitat based density model 1.46e-05 2.95 0.3616 1.7976 0 580,258.8352
Rissos_dolphin_summer_fall Rissos dolphin Grampus griseus 12,257 Habitat based density model 0.000409 0.224 0.3127 0.9516 0 12,536.1352
Northern_right_whale_dolphin_summer_fall Northern right whale dolphin Lissodelphis borealis 12,257 Habitat based density model 1.04e-09 3.07 0.6041 1.6799 0 32,379.6738
Pacific_white_sided_dolphin_summer_fall Pacific white sided dolphin Lagenorhynchus obliquidens 12,257 Habitat based density model 1.75e-14 0.622 0.2848 1.5376 0 36,936.5912
Humpback_whale_summer_fall Humpback whale Megaptera novaeangliae 12,257 Habitat based density model 1.83e-14 0.194 0.1503 0.5362 0 5,195.0948
Dalls_porpoise_summer_fall Dalls porpoise Phocoenoides dalli 12,257 Habitat based density model 4.56e-06 0.176 0.3569 2.3664 0 34,150.2788
Striped_dolphin_summer_fall Striped dolphin Stenella coeruleoalba 12,257 Habitat based density model 1.36e-07 0.435 0.4935 1.0155 0 39,612.2402
Bottlenose_dolphin_summer_fall Bottlenose dolphin Tursiops truncatus 12,257 Habitat based density model 6.48e-08 1.55 0.5959 6.4140 0 4,726.9914

6 Taxa → WoRMS

Each delivered name (SPECIES_2) is matched exactly against the pipeline’s WoRMS snapshot. Where a name has several WoRMS records (homonyms and synonym records), the rule picks one in this order:

  1. the record that is itself accepted;
  2. otherwise, a synonym whose accepted taxon is accepted and in the same genus;
  3. otherwise, a synonym whose accepted taxon is accepted.

The render stops if more than one record ties at the top, or if any accepted target is not itself accepted.

Code
con_spp   <- dbConnect(duckdb(), path_expand(spp_db), read_only = TRUE)
worms_ver <- dbGetQuery(con_spp, "SELECT worms_ver, source FROM worms_meta")
nm        <- unique(d_src$scientific_name)

w_rec <- tbl(con_spp, "worms") |>
  filter(scientificName %in% !!nm) |>
  select(taxonID, scientificName, scientificNameAuthorship, taxonRank, taxonomicStatus,
         acceptedNameUsageID) |>
  collect()
w_acc <- tbl(con_spp, "worms") |>
  filter(taxonID %in% !!unique(na.omit(w_rec$acceptedNameUsageID))) |>
  select(acc_id = taxonID, acc_name = scientificName, acc_status = taxonomicStatus, acc_genus = genus) |>
  collect()
dbDisconnect(con_spp, shutdown = TRUE)

w_pick <- w_rec |>
  left_join(w_acc, by = c(acceptedNameUsageID = "acc_id")) |>
  mutate(
    src_genus = word(scientificName, 1),
    tier      = case_when(
      taxonomicStatus == "accepted"                             ~ 1L,
      acc_status %in% "accepted" & acc_genus %in% src_genus     ~ 2L,
      acc_status %in% "accepted"                                ~ 3L,
      .default = NA_integer_)) |>
  filter(!is.na(tier)) |>
  group_by(scientificName) |>
  filter(tier == min(tier)) |>
  ungroup()

stopifnot(
  "a name did not resolve to WoRMS"         = setequal(w_pick$scientificName, nm),
  "a name resolved to more than one record" = !any(duplicated(w_pick$scientificName)),
  "an accepted target is not accepted"      = all(w_pick$acc_status == "accepted"),
  "the record's own id must be unique (mdl_key)" = !any(duplicated(w_pick$taxonID)))

taxa <- d_src |>
  select(layer, species, scientific_name) |>
  left_join(
    w_pick |> transmute(
      scientific_name          = scientificName,
      worms_id                 = as.integer(taxonID),
      worms_status             = taxonomicStatus,
      worms_id_accepted        = as.integer(acceptedNameUsageID),
      scientific_name_accepted = acc_name),
    by = "scientific_name") |>
  mutate(
    sp_id      = glue("WORMS:{worms_id}") |> as.character(),
    mdl_key    = glue("{ds_key}|{sp_id}|{season}") |> as.character(),   # the interval model
    mdl_key_an = glue("{ds_key}|{sp_id}") |> as.character(),            # the annual model (= the interval: one interval)
    cog        = glue("{ds_key}_{worms_id}_{season}.tif") |> as.character(),
    parquet    = glue("{ds_key}_{worms_id}_{season}.parquet") |> as.character(),
    parquet_an = glue("{ds_key}_{worms_id}.parquet") |> as.character())
stopifnot(nrow(taxa) == 13, !anyNA(taxa$worms_id), !any(duplicated(taxa$mdl_key)), !any(duplicated(taxa$mdl_key_an)))

# live cross-check against the WoRMS web service: informative only (an offline render still passes)
live <- tryCatch(
  worrms::wm_record(taxa$worms_id) |>
    transmute(worms_id = as.integer(AphiaID), live_status = status,
              live_valid_id = as.integer(valid_AphiaID)),
  error = \(e) { log_warn("worrms live cross-check skipped: {conditionMessage(e)}"); NULL })
if (!is.null(live)) {
  taxa <- taxa |> left_join(live, by = "worms_id")
  n_disagree <- sum(taxa$live_status != taxa$worms_status |
                    taxa$live_valid_id != taxa$worms_id_accepted, na.rm = TRUE)
  if (n_disagree > 0)
    log_warn("{n_disagree} taxa differ between the {worms_ver$worms_ver} snapshot and live WoRMS")
}

kable(taxa |> select(any_of(c("species", "scientific_name", "worms_id", "worms_status",
                              "worms_id_accepted", "scientific_name_accepted", "live_status",
                              "mdl_key"))),
      caption = glue("WoRMS: snapshot {worms_ver$worms_ver} ({worms_ver$source}); ",
                     "live = worrms::wm_record() at render time"))
WoRMS: snapshot 2026-07-01 (WoRMS_download_2026-07-01); live = worrms::wm_record() at render time
species scientific_name worms_id worms_status worms_id_accepted scientific_name_accepted live_status mdl_key
Minke whale Balaenoptera acutorostrata 137087 accepted 137087 Balaenoptera acutorostrata accepted cce|WORMS:137087|summer-fall
Bairds beaked whale Berardius bairdii 242608 accepted 242608 Berardius bairdii accepted cce|WORMS:242608|summer-fall
Blue whale Balaenoptera musculus 137090 accepted 137090 Balaenoptera musculus accepted cce|WORMS:137090|summer-fall
Fin whale Balaenoptera physalus 137091 accepted 137091 Balaenoptera physalus accepted cce|WORMS:137091|summer-fall
Long beaked common dolphin Delphinus capensis 137093 unaccepted 137094 Delphinus delphis unaccepted cce|WORMS:137093|summer-fall
Short beaked common dolphin Delphinus delphis 137094 accepted 137094 Delphinus delphis accepted cce|WORMS:137094|summer-fall
Rissos dolphin Grampus griseus 137098 accepted 137098 Grampus griseus accepted cce|WORMS:137098|summer-fall
Northern right whale dolphin Lissodelphis borealis 254975 accepted 254975 Lissodelphis borealis accepted cce|WORMS:254975|summer-fall
Pacific white sided dolphin Lagenorhynchus obliquidens 254981 junior objective synonym 1571909 Sagmatias obliquidens junior objective synonym cce|WORMS:254981|summer-fall
Humpback whale Megaptera novaeangliae 137092 accepted 137092 Megaptera novaeangliae accepted cce|WORMS:137092|summer-fall
Dalls porpoise Phocoenoides dalli 254987 accepted 254987 Phocoenoides dalli accepted cce|WORMS:254987|summer-fall
Striped dolphin Stenella coeruleoalba 137107 accepted 137107 Stenella coeruleoalba accepted cce|WORMS:137107|summer-fall
Bottlenose dolphin Tursiops truncatus 137111 accepted 137111 Tursiops truncatus accepted cce|WORMS:137111|summer-fall
Code
n_syn <- sum(taxa$worms_status != "accepted")
acc_dup <- taxa |> filter(worms_id_accepted %in% worms_id_accepted[duplicated(worms_id_accepted)])

11 of the 13 delivered names are accepted in WoRMS, and 2 are synonyms:

  • Delphinus capensis, the long-beaked common dolphin, is unaccepted in WoRMS and placed under Delphinus delphis. The InPort abstract itself calls this population Delphinus delphis bairdii, but WoRMS lists that subspecies as nomen dubium, so no accepted WoRMS taxon is specific to the CCE long-beaked form.
  • Lagenorhynchus obliquidens, the Pacific white-sided dolphin, is a junior objective synonym of Sagmatias obliquidens.

Key choice. mdl_key and the file names use the AphiaID of the name as delivered (worms_id), not the accepted one. A raw model key identifies the source’s own species, in the same way that AquaMaps keys use its species code. Using the accepted id would collide for the two Delphinus layers: Long beaked common dolphin and Short beaked common dolphin share accepted AphiaID 137094. The accepted id is kept in worms_id_accepted. A per-taxon merge would fold both layers into one D. delphis surface, and that is a decision for whoever promotes this dataset.

7 Regrid onto the 0.05° grid

Code
# exact overlap (km2) of every source cell with every 0.05-degree grid cell, once for all 13 layers
t0 <- Sys.time()
w  <- msens::poly_cell_overlap(geom, cellid_tif)
log_info("poly_cell_overlap: {nrow(w)} (polygon, cell) rows over {n_distinct(w$cell_id)} cells in {round(difftime(Sys.time(), t0, units = 'secs'), 1)} s")

# how much each output cell mixes source cells: share of its covered area from its largest polygon
mixing <- w |>
  group_by(cell_id) |>
  summarise(n_poly = n(), dom = max(area_km2) / sum(area_km2), .groups = "drop")

# per species: area-weighted density and CV (a -99999 CV would be NA, i.e. drop out of the CV only)
cells <- imap(src, \(x, l) msens::cells_area_mean(
  w, tibble(density = x$DENSITY,
            cv      = if_else(x$UNCERTAINTY <= -99999, NA_real_, x$UNCERTAINTY))))
stopifnot("layers must regrid to the same cell set" =
            all(map_lgl(cells, \(d) identical(d$cell_id, cells[[1]]$cell_id))))

n_out    <- nrow(cells[[1]])
n_single <- sum(mixing$dom >= 0.999)
pct      <- \(n) round(100 * n / n_out, 1)
med_dom  <- round(100 * median(mixing$dom[mixing$dom < 0.999]), 1)
kable(tibble(
  output_cells        = n_out,
  partial_cells       = sum(cells[[1]]$frac < 1 - 1e-6),
  frac_min            = signif(min(cells[[1]]$frac), 3),
  in_one_source_cell  = n_single,
  mixed_cells         = n_out - n_single,
  dom_median_mixed    = round(median(mixing$dom[mixing$dom < 0.999]), 4),
  dom_min             = round(min(mixing$dom), 4)),
  format.args = list(big.mark = ","),
  caption = paste(
    "Output cells. partial = covered fraction < 1 (coast, Canada/Mexico and offshore edges);",
    "in_one_source_cell = the largest source cell supplies >= 99.9 % of the covered area;",
    "dom = that share in the mixed cells (median, minimum)"))
Output cells. partial = covered fraction < 1 (coast, Canada/Mexico and offshore edges); in_one_source_cell = the largest source cell supplies >= 99.9 % of the covered area; dom = that share in the mixed cells (median, minimum)
output_cells partial_cells frac_min in_one_source_cell mixed_cells dom_median_mixed dom_min
48,118 1,493 1e-07 12,241 35,877 0.9345 0.3402

The source’s 0.1° lattice is regular, but its edges sit -0.002719° (longitude) and -0.003275° (latitude) off the 0.05° grid lines. That is 5.4 % and 6.6 % of a grid cell. So every other output column and every other output row straddles a source edge. 25.4 % of output cells lie inside a single source cell and carry its values unchanged. In the other 74.6 %, the largest source cell supplies a median 93.5 % of the covered area, and the result is an area-weighted blend across a sliver of the neighbour. That is harmless for the density, since the abundance is conserved (next section). It is the approximation for the CV described in the callout above.

8 Checks

Code
ctr <- msens::cell_lonlat(cells[[1]]$cell_id, grid)     # cell centres
h   <- grid$resx / 2                                      # a cell intersects the bbox iff its centre is within h

chk <- imap_dfr(cells, \(d, l) {
  x <- src[[l]]
  tibble(
    layer               = l,
    n_src               = nrow(x),
    n_cells             = nrow(d),
    abundance_source    = sum(x$ABUNDANCE),
    abundance_regridded = sum(d$density * d$area_km2),
    covered_km2         = sum(d$area_km2),
    area_sqkm_src       = sum(x$AREA_SQKM),
    density_min         = min(d$density),
    n_outside_extent    = sum(ctr$lon < bb_src[["xmin"]] - h | ctr$lon > bb_src[["xmax"]] + h |
                              ctr$lat < bb_src[["ymin"]] - h | ctr$lat > bb_src[["ymax"]] + h),
    frac_max            = max(d$frac),
    n_na_density        = sum(is.na(d$density)))
}) |>
  mutate(abundance_rel_diff = abundance_regridded / abundance_source - 1,
         ok = n_src == 12257 & abs(abundance_rel_diff) < 0.01 & n_outside_extent == 0 &
              density_min >= 0 & frac_max <= 1 + 1e-6 & n_na_density == 0)

kable(chk |>
        select(layer, n_src, n_cells, abundance_source, abundance_regridded, abundance_rel_diff,
               covered_km2, area_sqkm_src, density_min, n_outside_extent, frac_max, ok) |>
        mutate(density_min = formatC(density_min, format = "g", digits = 3),
               abundance_rel_diff = formatC(abundance_rel_diff, format = "e", digits = 1)),
      digits = c(0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 6, 0), format.args = list(big.mark = ","),
      caption = "Per species: regridded abundance (sum of density x covered km2) vs the source's sum of ABUNDANCE (must be within 1 %), cells outside the source extent (must be 0), density >= 0")
Per species: regridded abundance (sum of density x covered km2) vs the source’s sum of ABUNDANCE (must be within 1 %), cells outside the source extent (must be 0), density >= 0
layer n_src n_cells abundance_source abundance_regridded abundance_rel_diff covered_km2 area_sqkm_src density_min n_outside_extent frac_max ok
Minke_whale_summer_fall 12,257 48,118 889.07 889.07 -5.1e-07 1,140,913 1,140,913 5.06e-05 0 1 TRUE
Bairds_beaked_whale_summer_fall 12,257 48,118 846.39 846.39 4.0e-08 1,140,913 1,140,913 1.65e-09 0 1 TRUE
Blue_whale_summer_fall 12,257 48,118 1,239.01 1,239.01 -5.8e-07 1,140,913 1,140,913 9.67e-06 0 1 TRUE
Fin_whale_summer_fall 12,257 48,118 12,014.39 12,014.39 -1.4e-07 1,140,913 1,140,913 3.19e-06 0 1 TRUE
Long_beaked_common_dolphin_summer_fall 12,257 48,118 62,507.00 62,506.82 -2.8e-06 1,140,913 1,140,913 1.31e-09 0 1 TRUE
Short_beaked_common_dolphin_summer_fall 12,257 48,118 580,258.84 580,258.77 -1.0e-07 1,140,913 1,140,913 1.46e-05 0 1 TRUE
Rissos_dolphin_summer_fall 12,257 48,118 12,536.14 12,536.12 -1.3e-06 1,140,913 1,140,913 0.00041 0 1 TRUE
Northern_right_whale_dolphin_summer_fall 12,257 48,118 32,379.67 32,379.59 -2.6e-06 1,140,913 1,140,913 1.19e-09 0 1 TRUE
Pacific_white_sided_dolphin_summer_fall 12,257 48,118 36,936.59 36,936.58 -3.5e-07 1,140,913 1,140,913 2.24e-14 0 1 TRUE
Humpback_whale_summer_fall 12,257 48,118 5,195.09 5,195.09 -1.4e-06 1,140,913 1,140,913 1.85e-14 0 1 TRUE
Dalls_porpoise_summer_fall 12,257 48,118 34,150.28 34,150.27 -3.5e-07 1,140,913 1,140,913 4.8e-06 0 1 TRUE
Striped_dolphin_summer_fall 12,257 48,118 39,612.24 39,612.26 6.0e-07 1,140,913 1,140,913 1.36e-07 0 1 TRUE
Bottlenose_dolphin_summer_fall 12,257 48,118 4,726.99 4,727.00 1.9e-06 1,140,913 1,140,913 6.48e-08 0 1 TRUE
Code
stopifnot(
  "13 species x 12,257 source cells"           = nrow(chk) == 13 && all(chk$n_src == 12257L),
  "regridded abundance not within 1 % of source" = all(abs(chk$abundance_rel_diff) < 0.01),
  "an output cell lies outside the source extent" = all(chk$n_outside_extent == 0),
  "negative density"                             = all(chk$density_min >= 0),
  "covered fraction > 1 (overlapping sources?)"  = all(chk$frac_max <= 1 + 1e-6),
  "NA density in an output cell"                 = all(chk$n_na_density == 0),
  "every output cell is covered"                 = all(cells[[1]]$frac > 0))

9 Value transform: density → population percentile

Per species, on the regridded cells, after the checks above. val is msens::density_to_suit(density, "ud", area = cell area_km2): 100 minus the percent of the modelled population (density × the cell table’s area_km2) held by cells strictly denser than this one. The densest cell is 100 and val >= 100 - p is exactly the p % core of the population, whatever the units or the skew of the model. Cells below val 1 are the tail holding the last percent of the population and are not written (the merge’s floor).

The annual surface is msens::density_annual(n_intervals = 1) of the one interval: the identity on the density, asserted below, so the annual model has exactly the interval model’s cells and val. The two keys exist so cce has the same key shape as gm and nc; the merge reads only the annual one.

Code
to_val <- function(dens, cell_id, how, cap = NA_real_) {
  if (how == "ud") msens::density_to_suit(dens, "ud", area = cell_area(cell_id), digits = 2)
  else             round(100 * pmin(dens / cap, 1), 2)
}

# per species: the interval surface and the annual surface (density_annual, n_intervals = 1), each
# transformed on its own cells under BOTH recipes; `val` is the selected one
surf <- imap(cells, \(d, l) {
  pos <- d$density[d$density > 0]
  cap <- as.numeric(quantile(pos, p_cap, names = FALSE))
  ann <- msens::density_annual(tibble(cell_id = d$cell_id, dens = d$density), n_intervals = 1)
  stopifnot("annual (one interval) is not the interval's density" =
              identical(ann$cell_id, d$cell_id), isTRUE(all(ann$dens == d$density)))
  mk <- \(dens) tibble(cell_id = d$cell_id, dens = dens, cv = d$cv, frac = d$frac,
                       v_ud = to_val(dens, d$cell_id, "ud"), v_cap = to_val(dens, d$cell_id, "cap", cap)) |>
    mutate(val = if (cce_transform == "ud") v_ud else v_cap)
  list(cap = cap, interval = mk(d$density), annual = mk(ann$dens))
})
stopifnot("annual val != interval val" =
            all(map_lgl(surf, \(s) identical(s$interval$val, s$annual$val))))

# what the transform did, per species (interval model; the annual is identical)
pop_share <- \(s, v, thr) sum((s$dens * cell_area(s$cell_id))[v >= thr]) / sum(s$dens * cell_area(s$cell_id))
tf <- imap_dfr(surf, \(s, l) {
  x <- s$interval
  tibble(layer = l, n_cells = nrow(x), n_kept = sum(x$val >= 1), val_max = max(x$val),
         n_at_100 = sum(x$val == 100),
         pop_in_val_ge_50 = pop_share(x, x$v_ud, 50), pop_dropped_val_lt_1 = 1 - pop_share(x, x$v_ud, 1),
         q10 = quantile(x$val[x$val >= 1], .1, names = FALSE), q50 = median(x$val[x$val >= 1]),
         q90 = quantile(x$val[x$val >= 1], .9, names = FALSE))
})
kable(tf |> mutate(across(starts_with("pop_"), \(v) round(100 * v, 2))),
      digits = 1, format.args = list(big.mark = ","),
      caption = glue("{cce_transform} transform per species (interval = annual): cells kept (val >= 1), cells at 100, ",
                     "% of the population in cells with ud val >= 50 (>= 50 by construction) and % dropped below val 1 (< 1), ",
                     "quantiles of the kept val"))
ud transform per species (interval = annual): cells kept (val >= 1), cells at 100, % of the population in cells with ud val >= 50 (>= 50 by construction) and % dropped below val 1 (< 1), quantiles of the kept val
layer n_cells n_kept val_max n_at_100 pop_in_val_ge_50 pop_dropped_val_lt_1 q10 q50 q90
Minke_whale_summer_fall 48,118 43,422 100 1 50.0 1 2.4 17.6 68.2
Bairds_beaked_whale_summer_fall 48,118 23,733 100 1 50.0 1 1.8 11.9 60.0
Blue_whale_summer_fall 48,118 38,395 100 3 50.0 1 2.1 12.0 59.0
Fin_whale_summer_fall 48,118 39,680 100 1 50.0 1 3.2 20.0 69.4
Long_beaked_common_dolphin_summer_fall 48,118 4,372 100 3 50.1 1 1.4 7.0 47.4
Short_beaked_common_dolphin_summer_fall 48,118 32,687 100 6 50.0 1 2.9 25.2 74.8
Rissos_dolphin_summer_fall 48,118 42,491 100 3 50.0 1 2.3 14.8 53.2
Northern_right_whale_dolphin_summer_fall 48,118 25,144 100 1 50.0 1 1.6 8.5 41.0
Pacific_white_sided_dolphin_summer_fall 48,118 15,518 100 1 50.0 1 1.7 11.7 61.0
Humpback_whale_summer_fall 48,118 16,484 100 3 50.0 1 1.4 6.7 47.9
Dalls_porpoise_summer_fall 48,118 31,479 100 1 50.0 1 2.1 18.0 70.9
Striped_dolphin_summer_fall 48,118 27,120 100 1 50.0 1 1.8 13.1 65.1
Bottlenose_dolphin_summer_fall 48,118 20,414 100 1 50.0 1 1.4 5.3 26.0
Code
stopifnot(
  "no model reaches 100"                        = all(tf$val_max == 100),
  "a model has no kept cells"                   = all(tf$n_kept > 0),
  "ud: the 50 % core holds < 50 % of the population" = all(tf$pop_in_val_ge_50 >= 0.5 - 1e-9),
  "ud: dropped tail holds > 1 % of the population"   = all(tf$pop_dropped_val_lt_1 <= 0.01 + 1e-9))

# the two recipes side by side, per model (cells written = val >= 1)
q3  <- \(v) quantile(v, c(.1, .5, .9), names = FALSE)
cmp <- imap_dfr(surf, \(s, l) {
  x <- s$interval
  tibble(sp_id = taxa$sp_id[taxa$layer == l], layer = l, interval = c(season, "annual"),
         n_cells = nrow(x), n_ud = sum(x$v_ud >= 1), n_cap = sum(x$v_cap >= 1),
         ud_q10 = q3(x$v_ud[x$v_ud >= 1])[1], ud_q50 = q3(x$v_ud[x$v_ud >= 1])[2], ud_q90 = q3(x$v_ud[x$v_ud >= 1])[3],
         cap_q10 = q3(x$v_cap[x$v_cap >= 1])[1], cap_q50 = q3(x$v_cap[x$v_cap >= 1])[2], cap_q90 = q3(x$v_cap[x$v_cap >= 1])[3],
         dens_cap = s$cap)
}) |> arrange(sp_id, interval)
write_csv(cmp |> mutate(across(where(is.double), \(v) signif(v, 5))), cmp_csv)
kable(cmp |> filter(interval == season) |> select(-layer, -interval, -sp_id) |>
        mutate(across(where(is.double), \(v) signif(v, 3))),
      caption = glue("ud vs the linear-to-p99.5 recipe (cap) per species: cells kept and val quantiles. ",
                     "written to data/cce_transform_compare.csv; the written surface is {cce_transform}"))
ud vs the linear-to-p99.5 recipe (cap) per species: cells kept and val quantiles. written to data/cce_transform_compare.csv; the written surface is ud
n_cells n_ud n_cap ud_q10 ud_q50 ud_q90 cap_q10 cap_q50 cap_q90 dens_cap
48118 43422 48118 2.43 17.60 68.2 2.42 11.90 41.2 0.00425
48118 38395 40848 2.08 12.00 59.0 1.69 6.24 39.3 0.00867
48118 39680 43286 3.17 20.00 69.4 4.58 14.80 56.5 0.04920
48118 16484 12543 1.40 6.74 47.9 1.39 7.03 36.7 0.11800
48118 4372 4011 1.43 6.98 47.4 1.44 7.08 66.5 3.00000
48118 32687 36715 2.86 25.20 74.8 3.42 23.80 58.6 2.27000
48118 42491 43122 2.34 14.80 53.2 1.33 4.79 15.6 0.14200
48118 27120 28852 1.81 13.10 65.1 1.74 11.60 48.8 0.28500
48118 20414 12429 1.44 5.29 26.0 1.14 2.94 28.2 0.12300
48118 23733 24519 1.81 11.90 60.0 1.68 8.72 51.8 0.00790
48118 25144 17569 1.60 8.54 41.0 1.26 3.56 15.5 0.91800
48118 15518 15780 1.71 11.70 61.0 1.75 9.45 58.4 0.49600
48118 31479 34790 2.08 18.00 70.9 2.22 17.60 66.7 0.16500

10 Write COGs (CCE_COG=1)

Off by default. With CCE_COG=1 each species gets one COG, cce_cog/cce_<worms_id>_summer-fall.tif beside dist/: the delivered density, not val. Band 1 is density (animals km⁻²) and band 2 is cv. Both are Float32 with nodata −9999 outside the modelled cells, DEFLATE-compressed with the floating-point predictor, and in 256 × 256 blocks. There are no internal overviews, because titiler decimates from full resolution. The window is cut from the cell-id raster by row and column, so its origin and pixel size are the grid’s own, including the ~5 × 10⁻⁶° float drift. Each output pixel is a global05 cell.

Code
if (!cce_cog) {
  log_info("CCE_COG not set: no COGs written")
} else {
  # the data window in grid rows/cols (arithmetic, row-major, 1-based, top-left origin)
  ids <- as.double(cells[[1]]$cell_id)
  row <- ((ids - 1) %/% grid$nc) + 1; col <- ((ids - 1) %% grid$nc) + 1
  r0 <- min(row); r1 <- max(row); c0 <- min(col); c1 <- max(col)

  # cut that window from the cell-id raster itself: exact grid geometry, and a lookup check for free
  r_id   <- rast(cellid_tif)[r0:r1, c0:c1, drop = FALSE]
  win_id <- values(r_id, mat = FALSE)
  win_rc <- expand_grid(rr = r0:r1, cc = c0:c1)               # row-major, same order as values()
  stopifnot("cell-id window != row-major arithmetic" =
              all(win_id == (win_rc$rr - 1) * grid$nc + win_rc$cc))
  win_idx <- match(win_id, cells[[1]]$cell_id)                  # pixel -> row of cells[[l]] (NA = no data)
  log_info("COG window: rows {r0}-{r1}, cols {c0}-{c1} ({nrow(r_id)} x {ncol(r_id)} px), {sum(!is.na(win_idx))} data px")

  write_cog <- function(d, tx) {
    r <- rast(r_id, nlyrs = 2)
    values(r) <- cbind(d$density[win_idx], d$cv[win_idx])
    names(r)  <- c("density", "cv")
    tmp <- file_temp(ext = "tif"); on.exit(file_delete(tmp))
    writeRaster(r, tmp, datatype = "FLT4S", NAflag = -9999, overwrite = TRUE)
    # COG via gdal_translate: -stats writes real band statistics (terra's own COG path writes
    # STATISTICS_MEAN = -9999), -mo carries what a viewer needs to read the file on its own
    sf::gdal_utils("translate", tmp, path(dir_cog, tx$cog), options = c(
      "-of", "COG", "-co", "COMPRESS=DEFLATE", "-co", "PREDICTOR=YES", "-co", "BLOCKSIZE=256",
      "-co", "OVERVIEWS=NONE", "-stats",
      "-mo", glue("MDL_KEY={tx$mdl_key}"),
      "-mo", glue("SPECIES={tx$species}"),
      "-mo", glue("SCIENTIFIC_NAME={tx$scientific_name}"),
      "-mo", glue("WORMS_ID={tx$worms_id}"),
      "-mo", glue("WORMS_ID_ACCEPTED={tx$worms_id_accepted}"),
      "-mo", "SEASON=summer-fall",
      "-mo", "GRID=global05 (0.05 deg, -180..180; pixel = cell_id of r_cellid_global.tif)",
      "-mo", "BAND_1=density: animals per km2, area-weighted mean of the source 0.1 deg cells",
      "-mo", "BAND_2=cv: coefficient of variation of density, same weighting (an approximation for a CV)",
      "-mo", "SOURCE=Becker et al. 2020, NOAA-TM-NMFS-SWFSC-638, https://doi.org/10.25923/3znq-yx13",
      "-mo", "INPORT=https://www.fisheries.noaa.gov/inport/item/64349"))
    invisible(path(dir_cog, tx$cog))
  }
  walk(seq_len(nrow(taxa)), \(i) write_cog(cells[[taxa$layer[i]]], taxa[i, ]))

  # validate: gdalinfo says COG, 2 Float32 bands named density/cv with nodata, on the grid; then reopen
  # and compare EVERY pixel with what was written (float32 rounding only), plus a few cells by location
  set.seed(42)
  cog_chk <- map_dfr(seq_len(nrow(taxa)), \(i) {
    tx <- taxa[i, ]; f <- path(dir_cog, tx$cog); d <- cells[[tx$layer]]
    info <- fromJSON(sf::gdal_utils("info", f, options = "-json", quiet = TRUE), simplifyVector = FALSE)
    b    <- info$bands
    gt   <- unlist(info$geoTransform)
    off_x <- (gt[1] - grid$xmin) / grid$resx; off_y <- (grid$ymax - gt[4]) / grid$resy
    r <- rast(f)
    v <- values(r, mat = TRUE)
    exp_d <- d$density[win_idx]; exp_cv <- d$cv[win_idx]
    rel <- function(a, e) max(abs(a - e) / pmax(abs(e), 1e-30), na.rm = TRUE)
    # a few cells looked up by LOCATION (cell centre -> pixel), incl. the densest one
    k  <- c(which.max(d$density), sample(nrow(d), 5))
    ll <- msens::cell_lonlat(d$cell_id[k], grid)
    ex <- terra::extract(r, as.matrix(ll[, c("lon", "lat")]))
    tibble(
      cog          = tx$cog,
      layout       = info$metadata$IMAGE_STRUCTURE$LAYOUT %||% NA,
      compression  = info$metadata$IMAGE_STRUCTURE$COMPRESSION %||% NA,
      bands        = length(b),
      type         = paste(unique(map_chr(b, "type")), collapse = ","),
      descriptions = paste(map_chr(b, \(x) x$description %||% ""), collapse = ","),
      nodata       = paste(unique(map_dbl(b, \(x) x$noDataValue %||% NA_real_)), collapse = ","),
      overviews    = sum(map_int(b, \(x) length(x$overviews))),
      on_grid      = abs(off_x - round(off_x)) < 1e-6 && abs(off_y - round(off_y)) < 1e-6 &&
                     abs(gt[2] - grid$resx) < 1e-12 && abs(-gt[6] - grid$resy) < 1e-12,
      n_data_px    = sum(!is.na(v[, 1])),
      max_rel_density = rel(v[, 1], exp_d),
      max_rel_cv      = rel(v[, 2], exp_cv),
      same_na      = identical(is.na(v[, 1]), is.na(exp_d)),
      pts_rel_max  = max(abs(ex$density - d$density[k]) / pmax(d$density[k], 1e-30)))
  })
  print(kable(cog_chk, digits = 9, format.args = list(big.mark = ","),
        caption = "COG validation: gdalinfo layout/bands, alignment to the grid, and every pixel read back vs what was written (float32: relative error < 1e-6)"))
  stopifnot(
    all(cog_chk$layout == "COG"), all(cog_chk$compression == "DEFLATE"), all(cog_chk$bands == 2),
    all(cog_chk$type == "Float32"), all(cog_chk$descriptions == "density,cv"),
    all(cog_chk$nodata == "-9999"), all(cog_chk$overviews == 0), all(cog_chk$on_grid),
    all(cog_chk$n_data_px == nrow(cells[[1]])), all(cog_chk$same_na),
    all(cog_chk$max_rel_density < 1e-6), all(cog_chk$max_rel_cv < 1e-6), all(cog_chk$pts_rel_max < 1e-6))
}

11 Write Parquet

The long table has one row per (model, cell): mdl_key, cell_id, val (the transformed value in [1,100]), and beside it dens (the area-weighted density, animals km⁻², full double precision), cv and frac (the covered fraction of the cell). It lives in dist/dataset=cce/, the version’s dist/ layout. The merge reads mdl_key, cell_id and val only. 26 files: for each species the interval model (cce|WORMS:{id}|summer-fall) and the annual model (cce|WORMS:{id}), which has the same rows.

Code
walk(seq_len(nrow(taxa)), \(i) {
  tx <- taxa[i, ]; s <- surf[[tx$layer]]
  one <- \(x, key, f) msens::write_atlas_parquet(
    x |> filter(val >= 1) |>
      transmute(mdl_key = key, cell_id = as.integer(cell_id), val, dens, cv, frac),
    path(dir_dist, f))
  one(s$interval, tx$mdl_key,    tx$parquet)
  one(s$annual,   tx$mdl_key_an, tx$parquet_an)
})
stopifnot("not exactly 26 parquet files in dist/dataset=cce (stale files? REDO_INGEST=1)" =
            length(dir_ls(dir_dist, glob = "*.parquet")) == 26)

# read back through DuckDB: one mdl_key per file, the expected rows and range
con <- dbConnect(duckdb())
duckdb_tune(con, glue("{dir_big_v}/_tmp/cce"))
pq  <- dbGetQuery(con, glue(
  "SELECT mdl_key, count(*) AS n_cells, count(DISTINCT cell_id) AS n_distinct, min(val) AS val_min,
          max(val) AS val_max, min(dens) AS dens_min, max(frac) AS frac_max
   FROM read_parquet('{dir_dist}/*.parquet') GROUP BY mdl_key ORDER BY mdl_key"))
dbDisconnect(con, shutdown = TRUE)
pq_hash <- msens::hash_parquet(glue("{dir_dist}/*.parquet"))
n_exp   <- bind_rows(
  tibble(mdl_key = taxa$mdl_key,    n_exp = map_int(taxa$layer, \(l) sum(surf[[l]]$interval$val >= 1))),
  tibble(mdl_key = taxa$mdl_key_an, n_exp = map_int(taxa$layer, \(l) sum(surf[[l]]$annual$val >= 1))))
pq_chk  <- pq |> left_join(n_exp, by = "mdl_key")
stopifnot(
  "26 models"                      = nrow(pq) == 26,
  "model set != 13 interval + 13 annual" = setequal(pq$mdl_key, n_exp$mdl_key),
  "row counts != the transform's"  = all(pq_chk$n_cells == pq_chk$n_exp),
  "duplicate cell in a model"      = all(pq$n_distinct == pq$n_cells),
  "val outside [1,100]"            = all(pq$val_min >= 1 & pq$val_max <= 100),
  "a model's max val is not 100"   = all(pq$val_max == 100),
  "negative density"               = all(pq$dens_min >= 0))
kable(pq, digits = 6, format.args = list(big.mark = ","),
      caption = glue("dist/dataset={ds_key}/ read back (content hash {pq_hash})"))
dist/dataset=cce/ read back (content hash 767beac5af801645)
mdl_key n_cells n_distinct val_min val_max dens_min frac_max
cce|WORMS:137087 43,422 43,422 1 100 0.000102 1
cce|WORMS:137087|summer-fall 43,422 43,422 1 100 0.000102 1
cce|WORMS:137090 38,395 38,395 1 100 0.000122 1
cce|WORMS:137090|summer-fall 38,395 38,395 1 100 0.000122 1
cce|WORMS:137091 39,680 39,680 1 100 0.001887 1
cce|WORMS:137091|summer-fall 39,680 39,680 1 100 0.001887 1
cce|WORMS:137092 16,484 16,484 1 100 0.000462 1
cce|WORMS:137092|summer-fall 16,484 16,484 1 100 0.000462 1
cce|WORMS:137093 4,372 4,372 1 100 0.021646 1
cce|WORMS:137093|summer-fall 4,372 4,372 1 100 0.021646 1
cce|WORMS:137094 32,687 32,687 1 100 0.087908 1
cce|WORMS:137094|summer-fall 32,687 32,687 1 100 0.087908 1
cce|WORMS:137098 42,491 42,491 1 100 0.001488 1
cce|WORMS:137098|summer-fall 42,491 42,491 1 100 0.001488 1
cce|WORMS:137107 27,120 27,120 1 100 0.003990 1
cce|WORMS:137107|summer-fall 27,120 27,120 1 100 0.003990 1
cce|WORMS:137111 20,414 20,414 1 100 0.000390 1
cce|WORMS:137111|summer-fall 20,414 20,414 1 100 0.000390 1
cce|WORMS:242608 23,733 23,733 1 100 0.000094 1
cce|WORMS:242608|summer-fall 23,733 23,733 1 100 0.000094 1
cce|WORMS:254975 25,144 25,144 1 100 0.002815 1
cce|WORMS:254975|summer-fall 25,144 25,144 1 100 0.002815 1
cce|WORMS:254981 15,518 15,518 1 100 0.005475 1
cce|WORMS:254981|summer-fall 15,518 15,518 1 100 0.005475 1
cce|WORMS:254987 31,479 31,479 1 100 0.003529 1
cce|WORMS:254987|summer-fall 31,479 31,479 1 100 0.003529 1

12 Model table

Code
mm <- taxa |>
  left_join(chk |> select(layer, abundance_source, abundance_regridded), by = "layer") |>
  mutate(
    density_min = map_dbl(layer, \(l) min(cells[[l]]$density)),
    density_p98 = map_dbl(layer, \(l) quantile(cells[[l]]$density, 0.98, names = FALSE)),
    density_max = map_dbl(layer, \(l) max(cells[[l]]$density)),
    cv_median   = map_dbl(layer, \(l) median(cells[[l]]$cv, na.rm = TRUE)),
    dens_cap    = map_dbl(layer, \(l) surf[[l]]$cap))

# one row per written model: the interval and the annual
model_cce <- bind_rows(
  mm |> mutate(interval = season, mdl_key = mdl_key,    parquet = parquet),
  mm |> mutate(interval = "annual", mdl_key = mdl_key_an, parquet = parquet_an)) |>
  inner_join(pq |> select(mdl_key, n_cells, val_min, val_max), by = "mdl_key") |>
  transmute(
    mdl_key, interval, sp_id, layer, common_name = species, scientific_name,
    is_guild = FALSE, worms_id, response_type = "density", transform = cce_transform,
    dens_cap = signif(dens_cap, 6), val_min, val_max, n_cells,
    abundance_source = round(abundance_source, 3), abundance_regridded = round(abundance_regridded, 3),
    density_min = signif(density_min, 6), density_p98 = signif(density_p98, 6),
    density_max = signif(density_max, 6), cv_median = signif(cv_median, 6),
    worms_status, worms_id_accepted, scientific_name_accepted, parquet) |>
  arrange(sp_id, interval)
stopifnot("model table != 26 rows" = nrow(model_cce) == 26,
          "val outside [1,100]"    = all(model_cce$val_min >= 1 & model_cce$val_max <= 100),
          "no guild here"          = !any(model_cce$is_guild))

write_csv(model_cce, mdl_csv)                         # dist/model_cce.csv: what build_registry + merge_models_prep read
write_csv(model_cce, repo_csv)                        # the committed copy
kable(model_cce |> filter(interval == season) |>
        select(common_name, worms_id, n_cells, abundance_source, abundance_regridded, density_p98, density_max,
               cv_median, val_min, val_max),
      format.args = list(big.mark = ","),
      caption = glue("model_cce.csv ({mdl_csv}; committed copy data/swfsc_cce_models.csv): 13 interval rows shown, plus 13 annual"))
model_cce.csv (/Users/bbest/_big/msens/derived/v11/marine-atlas/dist/model_cce.csv; committed copy data/swfsc_cce_models.csv): 13 interval rows shown, plus 13 annual
common_name worms_id n_cells abundance_source abundance_regridded density_p98 density_max cv_median val_min val_max
Minke whale 137,087 43,422 889.072 889.071 0.0031013 0.0049051 0.184706 1 100
Blue whale 137,090 38,395 1,239.008 1,239.007 0.0064010 0.0116938 0.802209 1 100
Fin whale 137,091 39,680 12,014.389 12,014.387 0.0407739 0.0821337 0.791035 1 100
Humpback whale 137,092 16,484 5,195.095 5,195.087 0.0508462 0.1944910 0.347684 1 100
Long beaked common dolphin 137,093 4,372 62,506.996 62,506.820 0.7731890 4.7559000 0.627283 1 100
Short beaked common dolphin 137,094 32,687 580,258.835 580,258.774 1.9612300 2.9494400 0.670987 1 100
Rissos dolphin 137,098 42,491 12,536.135 12,536.119 0.0845284 0.2238830 0.409093 1 100
Striped dolphin 137,107 27,120 39,612.240 39,612.264 0.2031490 0.4349590 0.661173 1 100
Bottlenose dolphin 137,111 20,414 4,726.991 4,727.000 0.0474415 1.5201700 1.091870 1 100
Bairds beaked whale 242,608 23,733 846.393 846.393 0.0059818 0.0931500 0.938705 1 100
Northern right whale dolphin 254,975 25,144 32,379.674 32,379.590 0.2337290 3.0678100 0.946678 1 100
Pacific white sided dolphin 254,981 15,518 36,936.591 36,936.578 0.3696830 0.6221270 0.626089 1 100
Dalls porpoise 254,987 31,479 34,150.279 34,150.267 0.1500300 0.1756970 0.808118 1 100

13 Humpback whale: source vs regridded

Code
hb_l <- "Humpback_whale_summer_fall"
hb   <- src[[hb_l]]
hb_c <- cells[[hb_l]]
hb_r <- bind_cols(msens::cell_lonlat(hb_c$cell_id, grid) |> transmute(x = lon, y = lat), density = hb_c$density)
lims <- max(hb$DENSITY) * c(1e-4, 1)          # four orders of magnitude; lower values take the bottom colour
land <- ne_countries(scale = "medium", returnclass = "sf",
                     country = c("United States of America", "Mexico", "Canada"))
fill <- scale_fill_viridis_c(
  "animals / km²", trans = "log10", limits = lims, oob = scales::squish,
  breaks = scales::breaks_log(n = 6), labels = \(v) formatC(v, format = "g", digits = 2))
bb   <- st_bbox(geom)
zoom <- c(xmin = -123.1, xmax = -121.7, ymin = 36.3, ymax = 37.3)

panel <- function(p, title, b) p + fill +
  geom_sf(data = land, fill = "grey85", color = "grey40", linewidth = 0.2, inherit.aes = FALSE) +
  coord_sf(xlim = b[c("xmin", "xmax")], ylim = b[c("ymin", "ymax")], expand = FALSE) +
  labs(title = title, x = NULL, y = NULL) + theme_minimal(base_size = 10)

p_src  <- panel(ggplot() + geom_sf(data = hb, aes(fill = DENSITY), color = NA),
                "source: 0.1° cells (DENSITY)", bb)
p_rg   <- panel(ggplot() + geom_tile(data = hb_r, aes(x, y, fill = density)),
                "regridded: 0.05° cells (dens)", bb)
hb_z   <- st_crop(hb, zoom)
p_src_z <- panel(ggplot() + geom_sf(data = hb_z, aes(fill = DENSITY), color = "white", linewidth = 0.15),
                 "source, Monterey Bay (cell outlines)", zoom)
p_rg_z  <- panel(ggplot() + geom_tile(data = hb_r |> filter(between(x, zoom[["xmin"]], zoom[["xmax"]]),
                                                            between(y, zoom[["ymin"]], zoom[["ymax"]])),
                                      aes(x, y, fill = density), color = "white", linewidth = 0.1),
                 "regridded, Monterey Bay (0.05° cells)", zoom)

(p_src | p_rg) / (p_src_z | p_rg_z) + plot_layout(guides = "collect", heights = c(1.6, 1))
Figure 2: Humpback whale summer–fall density (animals km⁻², log scale over four orders of magnitude below the maximum; lower densities, down to 10⁻¹⁴ offshore, take the bottom colour): the source 0.1° cells (left) and the regridded 0.05° cells (right). The bottom row zooms to Monterey Bay. Each source cell maps onto about 2 × 2 grid cells; its edges sit ~0.003° off the grid lines, so alternate rows and columns blend a sliver of the neighbouring cell. Cells clipped by the coast keep the source density over the part of the grid cell they cover.
Code
hb_v <- bind_cols(hb_r |> select(x, y), val = surf[[hb_l]]$interval$val) |> filter(val >= 1)
ggplot() +
  geom_tile(data = hb_v, aes(x, y, fill = val)) +
  scale_fill_viridis_c("val (ud)", limits = c(1, 100), option = "magma") +
  geom_sf(data = land, fill = "grey85", color = "grey40", linewidth = 0.2, inherit.aes = FALSE) +
  coord_sf(xlim = bb[c("xmin", "xmax")], ylim = bb[c("ymin", "ymax")], expand = FALSE) +
  labs(x = NULL, y = NULL) + theme_minimal(base_size = 10)
Figure 3: Humpback whale summer–fall, the written val: the population-percentile (ud) transform of the density above, on the 0.05° cells. The brightest cells are the densest 1 %, val >= 50 holds half of the modelled population, and the dark tail is the last few percent of it down to the floor of 1.

14 Credits and use constraints

The quotes below are read from the InPort metadata records at render time. The XML is cached under raw/sdm/swfsc/inport_cce/, and CCE_FETCH=1 refreshes it.

Code
inport_xml <- function(id) {
  f <- path(dir_inport, glue("{id}.xml"))
  if (cce_fetch || !file_exists(f))
    download.file(glue("https://www.fisheries.noaa.gov/inport/item/{id}/inport-xml"), f,
                  quiet = TRUE, mode = "wb")
  read_xml(f)
}
x_ds  <- inport_xml(64349)
x_att <- inport_xml(64350)
txt1  <- \(x, xp) xml_text(xml_find_first(x, xp)) |> str_squish()
md    <- \(s) str_replace_all(s, "([*_\"'])", "\\\\\\1")   # quote verbatim: escape emphasis + smart quotes

ip <- list(
  title       = txt1(x_ds, "//item-identification/title"),
  published   = txt1(x_ds, "//item-identification/publication-date"),
  credit      = txt1(x_ds, "//data-set-information/data-set-credit"),
  constraints = txt1(x_ds, "//access-information/data-use-constraints"),
  security    = txt1(x_ds, "//access-information/security-class"),
  download    = txt1(x_ds, "//distribution-information/distribution/download-url"),
  modified    = txt1(x_ds, "//catalog-details/metadata-record-last-modified"),
  cv_def      = txt1(x_att, "//data-attribute[name='UNCERTAINTY']/description"),
  area_def    = txt1(x_att, "//data-attribute[name='AREA_SQKM']/description"))
stopifnot(map_lgl(ip, \(s) !is.na(s) && nzchar(s)))

Citation. Becker EA, Forney KA, Miller DL, Fiedler PC, Barlow J, Moore JE (2020). Habitat-based density estimates for cetaceans in the California Current Ecosystem based on 1991–2018 survey data. U.S. Department of Commerce, NOAA Technical Memorandum NMFS-SWFSC-638. https://doi.org/10.25923/3znq-yx13 (Becker et al. 2020). The InPort record, Predictive Models of Cetacean Densities in the California Current Ecosystem, 2020b (published 2020-12-01; metadata last modified 2026-03-29T23:00:34), gives this credit:

CREDIT: Elizabeth A. Becker, Karin A. Forney, David L. Miller, Paul C. Fiedler, Jay Barlow, and Jeff E. Moore. 2020. Habitat-based density estimates for cetaceans in the California Current Ecosystem based on 1991-2018 survey data, U.S. Department of Commerce, NOAA Technical Memorandum NMFS-SWFSC-638. https://doi.org/10.25923/3znq-yx13 ORIGINATORS: Southwest Fisheries Science Center;

Data use constraints (InPort, verbatim; security class Unclassified):

*** No Warranty*** The user assumes the entire risk related to its use of these data. NMFS is providing these data "as is," and NMFS disclaims any and all warranties, whether express or implied, including (without limitation) any implied warranties of merchantability or fitness for a particular purpose. No warranty expressed or implied is made regarding the accuracy or utility of the data on any other system or for general or scientific purposes, nor shall the act of distribution constitute any such warranty. It is strongly recommended that careful attention be paid to the contents of the metadata file associated with these data to evaluate dataset limitations, restrictions or intended use. In no event will NMFS be liable to you or to any third party for any direct, indirect, incidental, consequential, special or exemplary damages or lost profit resulting from any use or misuse of these data.

Attribute definitions relied on above (InPort entity 64350):

UNCERTAINTY: Numerical uncertainty value (CV). When the models for a species/guild do not have dynamic predictors, uncertainty info is not available. In this case the field has a value of -99999.; Source: From model

AREA_SQKM: Area in square kilometers. Features must be projected, calculated and then reprojected to WGS84. Projection must be documented in metadata; Source: Calculated from shapefile

The data were downloaded from the ArcGIS item https://noaa.maps.arcgis.com/home/item.html?id=566b4ad31f1d40eeb65b8cf3a4f087ca (NOAA Fisheries Office of Science and Technology). Point of contact: Karin A. Forney (SWFSC). Credit SWFSC and Becker et al. (2020) wherever these surfaces are shown. The constraint above also asks users to read the metadata before use. The models describe summer–fall (July–November survey) conditions averaged over 1991–2018, and carry no information about winter–spring distribution.

15 Manifest

Code
# content-addressed, deterministic manifest (Phase A) -- no wall-clock, so an identical re-ingest
# produces byte-identical bytes and does NOT invalidate downstream targets
smry <- arrow::open_dataset(dir_dist) |>
  summarise(n_rows = n(), n_mdl = n_distinct(mdl_key),
            val_min = round(min(val), 2), val_max = round(max(val), 2)) |> collect()
msens::report_table(smry, caption = glue("cce density model_cell surface (density → population percentile [1,100], {cce_transform})"))
cce density model_cell surface (density → population percentile [1,100], ud)
n_rows n_mdl val_min val_max
721878 26 1 100
Code
msens::write_manifest(
  manifest, target = "ingest_swfsc_cce", content_hash = pq_hash,
  stats = list(
    ds_key = ds_key, n_species = nrow(taxa), n_mdl = nrow(model_cce), n_guild = 0L, transform = cce_transform,
    p_cap = p_cap, season = season, source_gdb = path_file(gdb), source_geometry_md5 = unname(geom_hash[1]),
    worms_snapshot = worms_ver$worms_ver, msens = as.character(packageVersion("msens")),
    note = "13 CCE species, one summer-fall interval -> population percentile [1,100]; annual = that interval (one interval); registered, merged only under FOLD_DENSITY"),
  force = msens::force_target("ingest_swfsc_cce"))

kable(tibble(output = c(dir_dist, mdl_csv, repo_csv, cmp_csv, manifest, if (cce_cog) dir_cog),
             n_files = map_int(output, \(p) if (dir_exists(p)) length(dir_ls(p)) else as.integer(file_exists(p)))),
      caption = "Outputs")
Outputs
output n_files
/Users/bbest/_big/msens/derived/v11/marine-atlas/dist/dataset=cce 26
/Users/bbest/_big/msens/derived/v11/marine-atlas/dist/model_cce.csv 1
/Users/bbest/Github/MarineSensitivity/workflows/data/swfsc_cce_models.csv 1
/Users/bbest/Github/MarineSensitivity/workflows/data/cce_transform_compare.csv 1
/Users/bbest/Github/MarineSensitivity/workflows/data/manifests/ingest_swfsc_cce.json 1

References

Becker, Elizabeth A., Karin A. Forney, David L. Miller, Paul C. Fiedler, Jay Barlow, and Jeff E. Moore. 2020. Habitat-Based Density Estimates for Cetaceans in the California Current Ecosystem Based on 1991–2018 Survey Data. NOAA Technical Memorandum NMFS-SWFSC-638. U.S. Department of Commerce, NOAA, National Marine Fisheries Service, Southwest Fisheries Science Center. https://doi.org/10.25923/3znq-yx13.