diff --git "a/code-windows/earth_terrain.py" "b/code-windows/earth_terrain.py" new file mode 100644--- /dev/null +++ "b/code-windows/earth_terrain.py" @@ -0,0 +1,2048 @@ +"""Band-by-band global terrain features for Earth on the latband5km-v1 grid. + +Source: Copernicus DEM GLO-30 Public, streamed from ``s3://copernicus-dem-30m`` +and described by ``source_manifest.json`` in this pipeline's Earth raw +directory. No tile is ever downloaded whole: each band is a windowed read of a +virtual mosaic (a GDAL VRT over ``/vsis3`` COGs) written to a temporary folder +that is deleted when the band group finishes. + +The grid is the permanent latitude-band index from :mod:`planetary_grid`; this +module never changes cell IDs, band edges or column counts. The feature maths - +block averaging, Horn slope, the 1 km relief window, the per-cell reductions, +the ``terrain-v0.2`` definitions, the shared quality-flag vocabulary and the +Parquet assembly - is :mod:`terrain_features`, shared verbatim with +:mod:`mars_terrain`. What lives here is Earth: the tile index, the per-zone +pixel geometry, the mosaics, the read window, WGS84 ground spacing and the +coverage semantics of a product whose ocean is simply absent. + +Usage: + python earth_terrain.py --bands 2000-2009 + python earth_terrain.py --bands 0-4000 --resume --workers 4 --out DIR + +What is specific to GLO-30 and matters for interpretation: + +* **Tiles are 1 deg x 1 deg with 3600 rows always, but the column count changes + by latitude zone** (3600 / 2400 / 1800 / 1200 / 720 / 360). The zone is keyed + on the tile edge nearest the equator, so the tile named ``S50`` spans + latitudes 49-50 and is a 3600-column tile; keying on ``abs(lat_sw)`` instead + misclassifies every southern tile by one zone. See :func:`zone_columns`. +* **Registration is Point.** A tile's geotransform origin sits half a pixel + outside its corner, so pixel centres land on exact multiples of the pixel + size, same-zone tiles abut with no gap or overlap, and the longitude ring + closes exactly - unlike the Mars product, whose seam is 0.46 pixels short. +* **Ground spacing is equalized in both directions.** ``k_ns`` native rows and + ``k_ew`` native columns are averaged together so an analysis pixel is ~200 m + on the ellipsoid. Both factors are recorded (``ns_samples_averaged``, + ``ew_samples_averaged``). Mars needs only ``k_ew`` because its source is already + 200 m square. +* **A missing tile is ocean, not an error.** Tiles are filtered against + ``tileList.txt`` before a mosaic is built, so a band pays no failed HTTP + request for the sea. Area with no tile reads as NaN, and a grid cell with no + pixels at all is still written: ``n_native_samples = 0``, ``valid_frac_200m = + 0``, NaN features, flag ``ocean_only``. One row per grid cell is what lets the + Earth and Mars tables join on ``region_id``. +* **A genuine read failure is an error.** Reads are retried with backoff and + then raised, so a band group fails loudly rather than publishing NaN that is + indistinguishable from ocean. +* **Bands that share a COG block row are read together.** The COGs are tiled + 1024 rows deep and a 5 km band is ~163 native rows, so a band read alone + fetches a whole block row to use a sixth of it. Reading one band at a time + measured 1,509 MiB over HTTP for 564.5 MiB decoded, and six bands cost + 10,448 MiB - six times as much, i.e. nothing survived in cache between + bands. ``process_band_batch`` therefore puts the longitude chunk on the + outside and the batch's bands on the inside. The reads change; the output + does not, and ``--bands-in-flight 1`` restores the old order byte for byte. +* Ten bands straddle a pixel-width zone boundary and are reduced as two + analysis segments with their own block factors and column grid; 134 bands + (3867-4000) lie entirely above latitude 84, where GLO-30 has no tiles at all, + and are written as ocean. + +Water +----- + +GLO-30 ships a Water Body Mask (``AUXFILES/_WBM.tif``) on exactly the +same pixel grid as the DEM: a Byte raster whose value codes are recorded, with +the evidence for each, under ``water_body_mask`` in ``source_manifest.json``. +It is read through a second VRT per tile row in the same band pass and the same +longitude chunks as the DEM, so the two reads share one piece of window +arithmetic and the planet is still crossed exactly once. + +It contributes exactly one feature column, ``water_mask_frac``: native water +pixels over ``n_native_samples``, counted with the same block-to-grid-column +accounting ``n_valid_native_samples`` uses, and NaN where ``n_native_samples`` is zero. +Two advisory flags come with it, ``water_only`` and ``water_partial``. + +**Water pixels are not removed from any other feature.** ``elev_*``, +``slope_*``, ``roughness_detrended_std`` and ``local_relief_1km`` are shared +``terrain-v0.2`` columns computed by :mod:`terrain_features` over every valid +native pixel, water included, exactly as on Mars. Masking water out of them +would change what those columns mean, would require a ``feature_version`` bump +and would break comparability with the Mars table. ``water_mask_frac`` is the +column a consumer filters on; it is published beside the elevation statistics +rather than baked into them. + +A tile whose DEM exists but whose WBM does not is an anomaly, not dry land: the +cells it touches get ``water_mask_frac`` NaN and the ``wbm_missing`` flag, never +a fabricated zero. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import logging +import math +import re +import shutil +import sys +import tempfile +import time +import urllib.request +from concurrent.futures import ProcessPoolExecutor, as_completed +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path + +import numpy as np +import rasterio +from rasterio.windows import Window + +import terrain_features as tf +import quarter_cells as qc +from planetary_grid import PLANETS, VERSION as GRID_VERSION, PlanetBandGrid # noqa: F401 +from terrain_features import ( # noqa: F401 (re-exported for callers and tests) + ANALYSIS_SPACING_M, BANDS_PER_GROUP, BLOCK_HALO, COUNT_FEATURES, FEATURE_VERSION, + FLOAT_FEATURES, LOW_COVERAGE_FRACTION, RELIEF_WINDOW, AnalysisSegment, + block_average, block_factor, group_is_complete, group_path, horn_slope_deg, + local_relief, parse_band_range, plan_groups, write_atomic, +) + +PLANET = 'earth' +DEFAULT_SOURCE_DIR = Path('data/raw/earth/copernicus_glo30') +DEFAULT_OUT_DIR = Path('data/processed/earth/terrain') + +# --- GLO-30 pixel geometry ------------------------------------------------- +TILE_DEG = 1 # tiles are 1 deg x 1 deg +TILE_ROWS = 3600 # 1 arcsec north-south, in every zone +NS_RES_DEG = float(TILE_DEG) / TILE_ROWS +GLOBAL_ROWS = 180 * TILE_ROWS # global pixel row g <-> centre latitude 90 - g/3600 +TOP_TILE_LAT_SW = 89 # the tile row that would hold latitude 90 +# (abs_lat_from, abs_lat_to, tile_columns), keyed on the tile edge nearest the +# equator. This rule reproduces all six published per-zone tile counts exactly. +ZONES = ((0, 50, 3600), (50, 60, 2400), (60, 70, 1800), + (70, 80, 1200), (80, 85, 720), (85, 90, 360)) +FINEST_TILE_COLUMNS = ZONES[0][2] +TILE_LAT_SW_MIN, TILE_LAT_SW_MAX = -90, 83 # tile rows that exist in the bucket + +# GLO-30 COGs are tiled 1024 x 1024, and a 5 km band is only ~163 native rows, +# so a band read on its own fetches a whole 1024-row block row to use a sixth of +# it. Measured on bands 2000-2005: six bands read one after another cost +# 10,448 MiB over HTTP, almost exactly six times the 1,509 MiB one band costs, +# i.e. no block row survived in cache from one band to the next. Processing the +# bands that share a block row together is what removes that factor. +COG_BLOCK_ROWS = 1024 +DEFAULT_GDAL_CACHE_MB = 512 + +DEFAULT_BUCKET = 'copernicus-dem-30m' +TILE_STEM = 'Copernicus_DSM_COG_10_{ns}{lat:02d}_00_{ew}{lon:03d}_00_DEM' + +# Anonymous streaming. AWS_NO_SIGN_REQUEST is what makes the bucket readable at +# all; with no credentials of any kind GDAL raises InvalidCredentials. +GDAL_ENV = { + 'AWS_NO_SIGN_REQUEST': 'YES', + 'AWS_DEFAULT_REGION': 'eu-central-1', + 'GDAL_DISABLE_READDIR_ON_OPEN': 'EMPTY_DIR', + 'VSI_CACHE': 'TRUE', + 'GDAL_HTTP_MAX_RETRY': '0', # retrying is this module's job, with logging +} +# rasterio forwards GDAL's own CPL messages to Python logging, splitting them +# over several submodule loggers; /vsicurl's byte-range notices land on +# rasterio._err. Counting on the parent catches them wherever they are raised. +GDAL_LOGGER = 'rasterio' + +EXTRA_FLOAT_FEATURES = ('ns_samples_averaged', 'water_mask_frac') + +# --- water body mask ------------------------------------------------------- +# The WBM lives beside the DEM in the same tile folder, on the same pixel grid. +WBM_SUBDIR = 'AUXFILES' +WBM_DTYPE = 'Byte' +# Value codes decoded from the pixels themselves, not from the product +# specification; the probes and their histograms are recorded under +# ``water_body_mask`` in source_manifest.json, which load_source_manifest +# checks against these constants. +WBM_NO_WATER = 0 +WBM_OCEAN = 1 +WBM_LAKE = 2 +WBM_RIVER = 3 +WATER_VALUES = (WBM_OCEAN, WBM_LAKE, WBM_RIVER) +# A cell at or above this is water for practical purposes; below the lower +# bound a stray pond is not worth a flag. Both are advisory only and neither +# touches a feature value. +WATER_ONLY_FRACTION = 0.99 +WATER_PARTIAL_FRACTION = 0.01 + +# Advisory flags this module adds to the shared vocabulary. Additive only: no +# existing feature column changes meaning. +FLAG_OCEAN_ONLY = 'ocean_only' +FLAG_COASTAL_PARTIAL = 'coastal_partial' +FLAG_HIGH_LAT_EW = 'high_lat_ew_distortion' +FLAG_MISSING_NEIGHBOUR = 'tile_missing_neighbour' +FLAG_ZONE_SPLIT = 'zone_split' +FLAG_ZONE_HALO = 'zone_boundary_halo' +FLAG_WATER_ONLY = 'water_only' +FLAG_WATER_PARTIAL = 'water_partial' +FLAG_WBM_MISSING = 'wbm_missing' + + +# -------------------------------------------------------------------------- +# provenance +# -------------------------------------------------------------------------- + +def code_version(path: Path | None = None) -> str: + """SHA-256 over this driver and ``terrain_features.py``, in that order. + + The feature maths lives in the shared module, so hashing the driver alone + would let a redefined feature ship under an unchanged provenance stamp. + """ + driver = Path(path) if path else Path(__file__).resolve() + return tf.code_version(driver, Path(tf.__file__).resolve()) + + +# -------------------------------------------------------------------------- +# zones, rows, columns, ground spacing +# -------------------------------------------------------------------------- + +def zone_columns(lat_sw: int, zones=ZONES) -> int: + """Tile column count for the tile row with south-west corner ``lat_sw``. + + The zone is selected by the tile's minimum ``|latitude|``: a tile named + ``S50`` covers centres in ``(-50, -49]``, i.e. ``|lat|`` in ``[49, 50)``, so + it belongs to the 3600-column zone. + """ + key = lat_sw if lat_sw >= 0 else -lat_sw - 1 + for low, high, columns in zones: + if low <= key < high: + return columns + raise ValueError(f'no GLO-30 zone covers a tile row at lat_sw={lat_sw}') + + +def tile_lat_sw(row: int) -> int: + """Tile row holding global pixel row ``row``; exact integer arithmetic. + + Global row ``g`` has centre latitude ``90 - g/3600`` and a tile with corner + ``L`` holds centres in ``(L, L+1]``, so there is no floating-point edge case + at integer latitudes - where ``floor(|lat|)`` would pick the wrong tile. + """ + return TOP_TILE_LAT_SW - row // TILE_ROWS + + +def tile_row_end(row: int) -> int: + """First global row after the tile row that contains ``row``.""" + return (TOP_TILE_LAT_SW - tile_lat_sw(row) + 1) * TILE_ROWS + + +def row_center_lat(rows) -> np.ndarray: + return 90.0 - np.asarray(rows, dtype=np.float64) / TILE_ROWS + + +def col_center_lon(cols, tile_columns: int) -> np.ndarray: + """Centre longitude of native column ``c``: exactly ``-180 + c * ew_res``.""" + return -180.0 + np.asarray(cols, dtype=np.float64) * (float(TILE_DEG) / tile_columns) + + +def prime_vertical_radius(lat_deg): + """WGS84 radius of curvature in the prime vertical, N(phi), metres.""" + a, b = PLANETS[PLANET]['a_m'], PLANETS[PLANET]['b_m'] + e2 = 1.0 - (b / a) ** 2 + s = np.sin(np.deg2rad(lat_deg)) + return a / np.sqrt(1.0 - e2 * s * s) + + +def meridional_radius(lat_deg): + """WGS84 meridional radius of curvature, M(phi), metres.""" + a, b = PLANETS[PLANET]['a_m'], PLANETS[PLANET]['b_m'] + e2 = 1.0 - (b / a) ** 2 + s = np.sin(np.deg2rad(lat_deg)) + return a * (1.0 - e2) / (1.0 - e2 * s * s) ** 1.5 + + +def pixel_ground_m(lat_deg: float, tile_columns: int) -> tuple[float, float]: + """True (east-west, north-south) ground size of one native pixel, metres.""" + ew_deg = float(TILE_DEG) / tile_columns + dx = (math.radians(ew_deg) * float(prime_vertical_radius(lat_deg)) + * math.cos(math.radians(lat_deg))) + dy = math.radians(NS_RES_DEG) * float(meridional_radius(lat_deg)) + return dx, dy + + +def ew_block_factor(lat_deg: float, tile_columns: int, max_factor: int | None = None) -> int: + """Native columns to average for a ~200 m analysis pixel east-west.""" + dx, _ = pixel_ground_m(lat_deg, tile_columns) + return block_factor(ANALYSIS_SPACING_M / dx if dx > 0 else math.inf, max_factor) + + +def ns_block_factor(lat_deg: float, max_factor: int | None = None) -> int: + """Native rows to average for a ~200 m analysis pixel north-south.""" + _, dy = pixel_ground_m(lat_deg, TILE_ROWS) + return block_factor(ANALYSIS_SPACING_M / dy, max_factor) + + +def local_metres(d_lon, lat, center_lat): + """East/north offsets in metres on the WGS84 ellipsoid. + + This callback is the only place the body's shape enters the shared per-cell + reduction; :mod:`mars_terrain` passes the spherical version. + """ + x_m = np.radians(d_lon) * prime_vertical_radius(lat) * np.cos(np.deg2rad(lat)) + y_m = np.radians(np.asarray(lat, dtype=np.float64) - center_lat) * float( + meridional_radius(center_lat)) + return x_m, y_m + + +def band_row_range(grid: PlanetBandGrid, band: int) -> tuple[int, int]: + """Global pixel rows whose CENTRE latitude lies in a band, half open. + + Row sets partition the 648000-row global grid exactly - adjacent bands abut + with no gap and no overlap. The north-pole band keeps latitude 90 itself, + mirroring :meth:`PlanetBandGrid.lat_band`. + """ + n_bands = len(grid.column_counts) + lat_min = float(grid.edges_deg[band]) + lat_max = float(grid.edges_deg[band + 1]) + start = 0 if band == n_bands - 1 else max(math.floor((90.0 - lat_max) * TILE_ROWS) + 1, 0) + stop = min(math.floor((90.0 - lat_min) * TILE_ROWS) + 1, GLOBAL_ROWS) + return start, stop + + +def zone_runs(row_start: int, row_stop: int, zones=ZONES) -> list[tuple[int, int, int]]: + """Split a row range into maximal runs sharing one tile column count. + + Returns ``(tile_columns, start, stop)`` north to south. All but ten of the + 4001 Earth bands give a single run. + """ + runs: list[tuple[int, int, int]] = [] + row = row_start + while row < row_stop: + columns = zone_columns(tile_lat_sw(row), zones) + stop = row + while stop < row_stop and zone_columns(tile_lat_sw(stop), zones) == columns: + stop = min(row_stop, tile_row_end(stop)) + runs.append((columns, row, stop)) + row = stop + return runs + + +# -------------------------------------------------------------------------- +# tile index and virtual mosaics +# -------------------------------------------------------------------------- + +def tile_stem(lat_sw: int, lon_sw: int) -> str: + return TILE_STEM.format(ns='N' if lat_sw >= 0 else 'S', lat=abs(lat_sw), + ew='E' if lon_sw >= 0 else 'W', lon=abs(lon_sw)) + + +_STEM_RE = re.compile(r'Copernicus_DSM_COG_10_([NS])(\d{2})_00_([EW])(\d{3})_00_DEM') + + +def parse_tile_stem(stem: str) -> tuple[int, int] | None: + match = _STEM_RE.fullmatch(stem.strip()) + if not match: + return None + ns, lat, ew, lon = match.groups() + return (int(lat) if ns == 'N' else -int(lat), + int(lon) if ew == 'E' else -int(lon)) + + +def _read_index_bytes(source: str) -> bytes: + if str(source).startswith(('http://', 'https://')): + with urllib.request.urlopen(str(source), timeout=120) as response: # noqa: S310 + return response.read() + return Path(source).read_bytes() + + +def load_tile_index(source: str) -> frozenset[tuple[int, int]]: + """Read ``tileList.txt`` (local path or URL) into a set of tile corners. + + A tile absent from this index does not exist in the bucket, which means + ocean. Filtering against the index before building a mosaic is what keeps a + band from paying for hundreds of failed HTTP requests. + """ + tiles = {parsed for line in _read_index_bytes(source).decode('ascii').splitlines() + if (parsed := parse_tile_stem(line)) is not None} + if not tiles: + raise ValueError(f'no GLO-30 tile names found in {source}') + return frozenset(tiles) + + +def tile_index_sha256(source: str) -> str: + """Digest of the index bytes; GLO-30 publishes no single product checksum.""" + return hashlib.sha256(_read_index_bytes(source)).hexdigest() + + +def tile_url(root: str, lat_sw: int, lon_sw: int) -> str: + stem = tile_stem(lat_sw, lon_sw) + return f'{root.rstrip("/")}/{stem}/{stem}.tif' + + +def wbm_url(root: str, lat_sw: int, lon_sw: int) -> str: + """Water Body Mask of the same tile: the DEM stem with ``_DEM`` -> ``_WBM``. + + Confirmed by listing a tile folder rather than assumed: the AUXFILES masks + keep the ``COG_10`` stem of the DEM, while the XML, the previews and the + KMLs drop it. + """ + stem = tile_stem(lat_sw, lon_sw) + return f'{root.rstrip("/")}/{stem}/{WBM_SUBDIR}/{stem[:-len("DEM")]}WBM.tif' + + +def vrt_xml(root: str, lat_sw: int, tile_columns: int, + lon_sws, nodata: float | None, *, + data_type: str = 'Float32', url=tile_url) -> str: + """A full-width virtual mosaic of one tile row of one zone. + + One tile row per VRT keeps every source on a shared integer pixel grid: + ``DstRect`` offsets are exact integers, there is no resampling and no gap. A + VRT spanning a zone boundary gets fractional offsets instead and silently + nearest-neighbour shifts the finer zone, so mosaics are never + mixed-resolution; rows of another zone are stitched by :func:`read_native`. + Absent tiles are left out entirely and the area they would have covered is + set to NaN by the caller, rather than read as the VRT's own fill value. + """ + ew_res = float(TILE_DEG) / tile_columns + width = 360 * tile_columns + parts = [ + f'', + ' EPSG:4326', + ' {:.17g}, {:.17g}, 0, {:.17g}, 0, {:.17g}'.format( + -180.0 - 0.5 * ew_res, ew_res, lat_sw + TILE_DEG + 0.5 * NS_RES_DEG, -NS_RES_DEG), + f' ', + ] + if nodata is not None: + parts.append(f' {nodata:.17g}') + for lon_sw in lon_sws: + parts += [ + ' ', + ' ' + f'{url(root, lat_sw, int(lon_sw))}', + ' 1', + f' ', + f' ', + f' ', + ' ', + ] + parts += [' ', '', ''] + return '\n'.join(parts) + + +# -------------------------------------------------------------------------- +# configuration, statistics, reads +# -------------------------------------------------------------------------- + +@dataclass(frozen=True) +class EarthSource: + """Everything a worker needs to read GLO-30. Picklable; no open handles.""" + root: str + tiles: frozenset + nodata: float | None = None + zones: tuple = ZONES + max_tiles_in_flight: int = 8 + retries: int = 4 + retry_backoff_s: float = 1.0 + use_gdal_env: bool = True + skip_empty_chunks: bool = True + debug_http: bool = False + read_water: bool = True + # Bands held in flight together. 1 reproduces the band-at-a-time read + # order exactly, which is how the reordering is pinned as bit-identical. + bands_in_flight: int = 0 # 0 = as many as share one COG block row + gdal_cache_mb: int = DEFAULT_GDAL_CACHE_MB + water_values: tuple = WATER_VALUES + # Tiles whose WBM exists. ``None`` means "wherever the DEM exists", which + # is what the bucket listing shows (26,450 DEM and 26,450 WBM objects) and + # what a 420-tile HEAD sample confirmed with no exception. An explicit set + # is how a caller - or a test - describes a DEM that has lost its mask. + water_tiles: frozenset | None = None + + def has(self, lat_sw: int, lon_sw: int) -> bool: + return (lat_sw, lon_sw) in self.tiles + + def has_water(self, lat_sw: int, lon_sw: int) -> bool: + if not self.has(lat_sw, lon_sw): + return False + return self.water_tiles is None or (lat_sw, lon_sw) in self.water_tiles + + def row_tiles(self, lat_sw: int) -> list[int]: + if not (TILE_LAT_SW_MIN <= lat_sw <= TILE_LAT_SW_MAX): + return [] + return [lon for lon in range(-180, 180) if (lat_sw, lon) in self.tiles] + + def row_water_tiles(self, lat_sw: int) -> list[int]: + return [lon for lon in self.row_tiles(lat_sw) if self.has_water(lat_sw, lon)] + + def env(self): + if not self.use_gdal_env: + return rasterio.Env() + options = dict(GDAL_ENV) + # The block cache has to hold the block rows a whole batch of bands + # walks across, or reordering the reads buys nothing: one chunk of 8 + # tiles is ~236 MiB of decoded DEM blocks plus ~59 MiB of mask. + # rasterio forwards this one to GDALSetCacheMax64, which wants a byte + # count as an int, not the "512MB" string GDAL's own parser accepts + options['GDAL_CACHEMAX'] = int(self.gdal_cache_mb) * 2 ** 20 + if self.debug_http: + # asked for per-range accounting, which only GDAL's debug log reports + options['CPL_DEBUG'] = 'ON' + return rasterio.Env(**options) + + +@dataclass +class ReadStats: + """Per-group accounting for the log line.""" + tiles: set = field(default_factory=set) + mosaics: int = 0 + pixels: int = 0 + water_pixels: int = 0 + reads: int = 0 + http_bytes: int = 0 + http_ranges: int = 0 + retried: int = 0 + + +_RANGE_RE = re.compile(r'[Dd]ownloading (\d+)-(\d+)') + + +class _ByteCounter(logging.Handler): + """Lower bound on HTTP bytes, from GDAL's own ``/vsicurl`` debug messages. + + GDAL exposes no counter for bytes transferred, but ``CPL_DEBUG`` makes + ``/vsicurl`` announce every byte range it fetches (``S3: Downloading + 16384-32767 (...)``) and rasterio forwards those messages to Python logging. + + **This is a lower bound, and often a wild one.** Reads issued through a + VRT's sources are performed on GDAL worker threads whose CPL messages + never reach Python logging, so they are invisible here. Measured on band + 2000: this counter reported 0.4 MiB over 19 ranges while the network + interface recorded 1,509 MiB - a 3,500x undercount. Neither ``CPL_LOG`` + nor capturing fd 2 recovers them, because rasterio installs its own CPL + error handler. + + So ``--debug-http`` is useful only for the direct, main-thread reads, and + the figure is printed with a ``>=`` to say so. For a real number, measure + at the interface (``netstat -ib`` deltas) around the run. + """ + + def __init__(self, stats: ReadStats): + super().__init__(level=logging.DEBUG) + self.stats = stats + + def emit(self, record): + try: + match = _RANGE_RE.search(record.getMessage()) + except Exception: # noqa: BLE001 - a log handler must not raise + return + if match: + low, high = int(match.group(1)), int(match.group(2)) + self.stats.http_bytes += max(high - low + 1, 0) + self.stats.http_ranges += 1 + + +class _OpenMosaics: + """Per-group cache of open VRT datasets. + + A band is read in many longitude chunks, and re-parsing a 360-source VRT + (and re-opening its COG headers) for every chunk costs more than the pixels + do. Entries are evicted on error so a retry starts from a fresh handle. + """ + + def __init__(self): + self._open: dict[str, object] = {} + + def get(self, path: Path): + key = str(path) + if key not in self._open: + self._open[key] = rasterio.open(path) + return self._open[key] + + def evict(self, path: Path) -> None: + dataset = self._open.pop(str(path), None) + if dataset is not None: + try: + dataset.close() + except Exception: # noqa: BLE001 + pass + + def close(self) -> None: + for key in list(self._open): + self.evict(Path(key)) + + +def _read_mosaic_window(mosaics: _OpenMosaics, path: Path, row_off: int, n_rows: int, + col_off: int, n_cols: int) -> np.ndarray: + """The single seam where raster bytes enter this module. + + Deliberately tiny and free of retry logic, so a test can replace it to + simulate a flaky or permanently broken network. + """ + return mosaics.get(path).read(1, window=Window(col_off, row_off, n_cols, n_rows)) + + +def read_with_retries(mosaics: _OpenMosaics, path: Path, row_off: int, n_rows: int, + col_off: int, n_cols: int, source: EarthSource, stats: ReadStats, + what: str) -> np.ndarray: + """Windowed read with bounded retries; a permanent failure is raised. + + Transient S3 trouble is normal and worth retrying. A read that keeps failing + is *not* turned into NaN: NaN already means ocean here, so swallowing the + error would quietly publish a continent as sea. + """ + delay = source.retry_backoff_s + attempts = max(source.retries, 1) + for attempt in range(1, attempts + 1): + stats.reads += 1 + try: + return _read_mosaic_window(mosaics, path, row_off, n_rows, col_off, n_cols) + except Exception as exc: # noqa: BLE001 - GDAL raises broadly + mosaics.evict(path) + if attempt == attempts: + raise RuntimeError( + f'{what}: read failed after {attempt} attempt(s); refusing to write ' + f'NaN for a region that may be land') from exc + stats.retried += 1 + print(f' retry {attempt}/{attempts - 1} after ' + f'{exc.__class__.__name__} on {what}', flush=True) + if delay: + time.sleep(delay) + delay *= 2 + raise AssertionError('unreachable') + + +def _mosaic_path(source: EarthSource, tmp_dir: Path, lat_sw: int, tile_columns: int, + stats: ReadStats, layer: str = 'dem') -> Path | None: + """Write (and cache for the group) the VRT of one tile row, or None. + + ``layer`` picks the DEM or its Water Body Mask. The two mosaics are built + from the same tile row, the same zone column count and the same + geotransform, so one window serves both; the WBM VRT lists only the tiles + whose mask actually exists, because a VRT over a missing source raises on + read rather than yielding a fill value. + """ + if layer == 'dem': + lon_sws = source.row_tiles(lat_sw) + else: + lon_sws = source.row_water_tiles(lat_sw) + if not lon_sws: + return None + path = Path(tmp_dir) / f'row_{lat_sw:+03d}_{tile_columns}_{layer}.vrt' + if not path.exists(): + if layer == 'dem': + xml = vrt_xml(source.root, lat_sw, tile_columns, lon_sws, source.nodata) + else: + # no NoDataValue: coverage is tracked per pixel from the tile index, + # never inferred from a mask code + xml = vrt_xml(source.root, lat_sw, tile_columns, lon_sws, None, + data_type=WBM_DTYPE, url=wbm_url) + path.write_text(xml, encoding='utf8') + stats.mosaics += 1 + return path + + +def readable_rows(source: EarthSource, row_start: int, row_stop: int, + tile_columns: int) -> tuple[np.ndarray, bool]: + """Which rows of a window this zone's mosaics can supply, and why not. + + A row is unreadable when it lies off the planet, when its tile row is + outside the bucket's coverage (no tiles exist above latitude 84), or when it + belongs to a different pixel-width zone - whose pixels could only be had by + resampling, which would shift the mosaic. Only the second flag is worth + reporting, so the boolean says whether a *zone change* cost us rows. + """ + out = np.zeros(row_stop - row_start, dtype=bool) + zone_dropped = False + row = max(row_start, 0) + while row < min(row_stop, GLOBAL_ROWS): + stop = min(row_stop, GLOBAL_ROWS, tile_row_end(row)) + lat_sw = tile_lat_sw(row) + same_zone = zone_columns(lat_sw, source.zones) == tile_columns + zone_dropped = zone_dropped or not same_zone + out[row - row_start:stop - row_start] = ( + same_zone and TILE_LAT_SW_MIN <= lat_sw <= TILE_LAT_SW_MAX) + row = stop + return out, zone_dropped + + +def read_native(source: EarthSource, mosaics: _OpenMosaics, tmp_dir: Path, tile_columns: int, + row_start: int, row_stop: int, col_start: int, n_cols: int, + stats: ReadStats, water: bool = False) -> tuple: + """Read a rectangle of native pixels from this zone's mosaics. + + Returns ``(values, covered, wet, water_known)``. ``values`` is float32, NaN + wherever no tile exists, the row belongs to another zone or lies off the + planet, or the pixel is nodata. ``covered`` is per-pixel tile existence - + the exact native-pixel accounting the feature table publishes - and is + deliberately independent of the values, because GLO-30's sea is a real + ``0.0 m`` inside a coastal tile and absence only ever means "no tile". + + With ``water`` set, the Water Body Mask of the same tile row is read + through its own VRT over the *same* window, in the same pass: ``wet`` marks + native pixels whose mask code is one of ``source.water_values`` and + ``water_known`` marks pixels whose mask was actually available. Both are + intersected with ``covered``, so a pixel with no DEM tile is never counted + as wet or as dry. Without it, both come back ``None`` and not one byte of + WBM is fetched - which is what makes the two paths comparable column by + column. + """ + width = 360 * tile_columns + if col_start < 0 or col_start + n_cols > width: + raise ValueError(f'column window [{col_start}, {col_start + n_cols}) ' + f'is outside the {width}-column mosaic') + shape = (row_stop - row_start, n_cols) + values = np.full(shape, np.nan, dtype=np.float32) + covered = np.zeros(shape, dtype=bool) + wet = np.zeros(shape, dtype=bool) if water else None + water_known = np.zeros(shape, dtype=bool) if water else None + first_tile_col = col_start // tile_columns + last_tile_col = (col_start + n_cols - 1) // tile_columns + tile_of_col = np.arange(col_start, col_start + n_cols) // tile_columns - first_tile_col + + row = max(row_start, 0) + while row < min(row_stop, GLOBAL_ROWS): + lat_sw = tile_lat_sw(row) + stop = min(row_stop, GLOBAL_ROWS, tile_row_end(row)) + if (TILE_LAT_SW_MIN <= lat_sw <= TILE_LAT_SW_MAX + and zone_columns(lat_sw, source.zones) == tile_columns): + rows = slice(row - row_start, stop - row_start) + columns = f'{col_start}-{col_start + n_cols}' + present = np.array( + [source.has(lat_sw, t - 180) for t in range(first_tile_col, last_tile_col + 1)], + dtype=bool) + here = present[tile_of_col] + covered[rows] = here + if here.any(): + path = _mosaic_path(source, tmp_dir, lat_sw, tile_columns, stats) + stats.tiles.update( + (lat_sw, int(t) + first_tile_col - 180) + for t in np.unique(tile_of_col[here])) + block = read_with_retries( + mosaics, path, row % TILE_ROWS, stop - row, col_start, n_cols, + source, stats, what=f'tile row {lat_sw:+d}, columns {columns}') + stats.pixels += block.size + values[rows] = block + if water: + masked = np.array( + [source.has_water(lat_sw, t - 180) + for t in range(first_tile_col, last_tile_col + 1)], dtype=bool) + known = masked[tile_of_col] + water_known[rows] = known + if known.any(): + path = _mosaic_path(source, tmp_dir, lat_sw, tile_columns, stats, + layer='wbm') + codes = read_with_retries( + mosaics, path, row % TILE_ROWS, stop - row, col_start, n_cols, + source, stats, what=f'WBM row {lat_sw:+d}, columns {columns}') + stats.water_pixels += codes.size + wet[rows] = np.isin(codes, source.water_values) & known + + row = stop + + values[~covered] = np.nan + if source.nodata is not None and np.isfinite(source.nodata): + values[values == np.float32(source.nodata)] = np.nan + if water: + # a mask code without a DEM pixel behind it is not part of the + # denominator, so it must not be part of the numerator either + water_known &= covered + wet &= covered + return values, covered, wet, water_known + + +# -------------------------------------------------------------------------- +# one zone run of one band +# -------------------------------------------------------------------------- + +def block_pieces(first: int, last: int, n_blocks: int) -> list[tuple[int, int, float]]: + """Global block ranges covering ``[first - 2, last + 2)`` with wrap. + + Returned as ``(block_lo, block_hi, lon_offset_deg)`` in ascending output + order, each range contiguous in the mosaic so it reads as one window. The + halo is taken in whole *blocks* of the global block grid - not by widening + the native read - because the last global block is short whenever ``k_ew`` + does not divide the mosaic width, and a native-column halo would silently + give that block a full-width neighbour drawn from the wrong side of the + seam. + """ + pieces: list[tuple[int, int, float]] = [] + low, high = first - BLOCK_HALO, last + BLOCK_HALO + if low < 0: + pieces.append((n_blocks + low, n_blocks, -360.0)) + low = 0 + tail = None + if high > n_blocks: + tail = (0, high - n_blocks, 360.0) + high = n_blocks + pieces.append((low, high, 0.0)) + if tail: + pieces.append(tail) + return pieces + + +def _row_blocks(pad_row_start: int, row_start: int, row_stop: int, + k_ns: int) -> tuple[np.ndarray, slice, np.ndarray]: + """Analysis row blocks of a band: halo, interior, halo. + + The interior blocks must partition the band's own rows exactly, so the last + one is short whenever ``k_ns`` does not divide the band height - letting it + run on into the next band would count rows that belong to a neighbour and + inflate ``n_native_samples``. The halo blocks are full blocks either side, + which is all a Horn stencil and a relief window need. + """ + height = row_stop - row_start + offset = row_start - pad_row_start + interior_starts = np.arange(offset, offset + height, k_ns, dtype=np.int64) + before = np.arange(0, offset, k_ns, dtype=np.int64) + after = np.arange(offset + height, offset + height + BLOCK_HALO * k_ns, k_ns, + dtype=np.int64) + row_starts = np.concatenate([before, interior_starts, after]) + total = offset + height + BLOCK_HALO * k_ns + next_start = np.append(row_starts[1:], total) + first = pad_row_start + row_starts + last = pad_row_start + next_start - 1 + interior = slice(len(before), len(before) + len(interior_starts)) + return row_starts, interior, row_center_lat((first + last) / 2.0) + + +def _piece_arrays(source: EarthSource, mosaics: _OpenMosaics, tmp_dir: Path, + tile_columns: int, pad_row_start: int, pad_row_stop: int, + row_starts: np.ndarray, rows_per_block: np.ndarray, + low: int, high: int, offset: float, k_ew: int, + stats: ReadStats) -> tuple: + """Read one contiguous run of global blocks and reduce it to block arrays. + + The water counts ride along on the same window: ``wet_count`` is native + water pixels per block and ``unknown_count`` is covered native pixels whose + mask was absent. Both are ``None`` when the WBM is not being read. + """ + width = 360 * tile_columns + col_start = low * k_ew + col_stop = min(high * k_ew, width) + values, covered, wet, water_known = read_native( + source, mosaics, tmp_dir, tile_columns, pad_row_start, pad_row_stop, + col_start, col_stop - col_start, stats, water=source.read_water) + col_starts = np.arange(0, col_stop - col_start, k_ew, dtype=np.int64) + mean, valid = block_average(values, row_starts, col_starts) + del values + + def blocks(mask): + return np.add.reduceat( + np.add.reduceat(mask.astype(np.int64), row_starts, axis=0), col_starts, axis=1) + + present = blocks(covered) + if wet is None: + wet_count = unknown_count = None + else: + wet_count = blocks(wet) + unknown_count = blocks(covered & ~water_known) + del covered, wet, water_known + cols_per_block = np.diff(np.append(col_starts, col_stop - col_start)) + total = np.outer(rows_per_block, cols_per_block) + block_first = col_start + col_starts + block_last = np.minimum(block_first + k_ew, col_stop) - 1 + lons = col_center_lon((block_first + block_last) / 2.0, tile_columns) + offset + return mean, valid, present, total, lons, wet_count, unknown_count + + +def _chunk_has_tiles(source: EarthSource, tile_rows, tile_columns: int, + col_start: int, col_stop: int, k_ew: int) -> bool: + """Does any tile overlap a chunk's interior columns? + + Only the interior matters: if no tile covers the columns a chunk owns, its + analysis pixels are NaN whatever the halo holds, so the cells it feeds are + ocean and no flag of theirs depends on a neighbour. + """ + for tile_col in range(col_start // tile_columns, (col_stop - 1) // tile_columns + 1): + for lat_sw in tile_rows: + if source.has(lat_sw, tile_col - 180): + return True + return False + + +@dataclass +class ZoneRunPlan: + """Everything about one zone run of one band that needs no pixels. + + Separating the plan from the reads is what lets the group reorder its + chunks. The plan fixes the block grid, the halo, the row blocks and the + chunk boundaries; :func:`zone_run_chunk` then reads any one chunk in any + order, and :func:`zone_run_finish` folds the chunks back together in + ascending order so the arrays handed to the shared reduction are assembled + exactly as a single in-order pass would have assembled them. + """ + band: int + tile_columns: int + row_start: int + row_stop: int + n_cells: int + lon_step: float + width: int + center_lat: float + k_ns: int + k_ew: int + n_blocks: int + pad_row_start: int + pad_row_stop: int + row_starts: np.ndarray + interior: slice + block_lats: np.ndarray + n_row_blocks: int + rows_per_block: np.ndarray + zone_dropped: bool + all_lons: np.ndarray + all_columns: np.ndarray + tile_rows: list + chunks: list + # None unless --quarters: {'center_lat': band centre, 'n_cells_anchor': int | None} + quarters: dict | None = None + + def chunk_lon(self, index: int) -> float: + """West edge of a chunk in degrees: the key the group sorts reads by.""" + return -180.0 + 360.0 * (self.chunks[index][0] * self.k_ew) / self.width + + +def zone_run_plan(source: EarthSource, band: int, tile_columns: int, row_start: int, + row_stop: int, n_cells: int, lon_step: float, + quarters: dict | None = None) -> ZoneRunPlan: + """Block geometry of one band's rows that share a tile column count. + + Stages follow Mars: wrap east-west, nodata to NaN (done in the read), + equalize ground spacing, Horn slope and 1 km relief on the padded array, + drop the halos, assign analysis pixels to grid columns by centre longitude. + Two things the source forces are different. North-south is block averaged + too, so the halo is ``BLOCK_HALO`` whole *analysis* rows - ``2 * k_ns`` + native rows - which keeps the halo on the same block grid as the interior. + And the band is read in longitude chunks, because a full-width strip of 30 m + pixels is hundreds of megabytes; ``--max-tiles-in-flight`` sets the chunk + width in tile columns. + """ + width = 360 * tile_columns + center_lat = float(np.mean(row_center_lat([row_start, row_stop - 1]))) + k_ns = ns_block_factor(center_lat, max_factor=max(row_stop - row_start, 1)) + # cap k_ew so the block grid always has room for the 1 km relief window + k_ew = ew_block_factor(center_lat, tile_columns, + max_factor=max(width // RELIEF_WINDOW, 1)) + n_blocks = -(-width // k_ew) + + pad = BLOCK_HALO * k_ns + pad_row_start = row_start - pad + pad_row_stop = row_stop + pad + row_starts, interior, block_lats = _row_blocks(pad_row_start, row_start, row_stop, k_ns) + n_row_blocks = interior.stop - interior.start + + supplied, zone_dropped = readable_rows(source, pad_row_start, pad_row_stop, tile_columns) + rows_per_block = np.add.reduceat(supplied.astype(np.int64), row_starts) + + # The global block grid, computed once: both paths below index into it, so a + # chunk that is skipped and a chunk that is read cannot disagree about which + # grid column a block belongs to. + first_col = np.arange(n_blocks, dtype=np.int64) * k_ew + last_col = np.minimum(first_col + k_ew, width) - 1 + all_lons = (col_center_lon((first_col + last_col) / 2.0, tile_columns) + 180.0) % 360.0 - 180.0 + all_columns = np.clip(((all_lons + 180.0) / lon_step).astype(np.int64), 0, n_cells - 1) + tile_rows = sorted({tile_lat_sw(int(r)) for r in + np.flatnonzero(supplied) + pad_row_start}, reverse=True) + + per_chunk = max(1, (source.max_tiles_in_flight * tile_columns) // k_ew) + chunks = [(first, min(first + per_chunk, n_blocks)) + for first in range(0, n_blocks, per_chunk)] + return ZoneRunPlan( + band=band, tile_columns=tile_columns, row_start=row_start, row_stop=row_stop, + n_cells=n_cells, lon_step=lon_step, width=width, center_lat=center_lat, + k_ns=k_ns, k_ew=k_ew, n_blocks=n_blocks, pad_row_start=pad_row_start, + pad_row_stop=pad_row_stop, row_starts=row_starts, interior=interior, + block_lats=block_lats, n_row_blocks=n_row_blocks, rows_per_block=rows_per_block, + zone_dropped=zone_dropped, all_lons=all_lons, all_columns=all_columns, + tile_rows=tile_rows, chunks=chunks, quarters=quarters) + + +def _quarter_grids(plan: ZoneRunPlan): + """``(name, n_cells, lon_step, quarter rows, n_slots)`` of each quarter indexing. + + ``own`` is the band's own column edges, both quarter rows. ``anchor`` is + the next band's (``band + 1``, the one to the north) column edges, + northern quarter row only; the north-pole band has none. + """ + grids = [('own', plan.n_cells, plan.lon_step, (0, 1), 4 * plan.n_cells)] + anchor = plan.quarters['n_cells_anchor'] + if anchor is not None: + grids.append(('anchor', anchor, 360.0 / anchor, (0,), 2 * anchor)) + return grids + + +_QUARTER_COUNTS = ('native', 'valid', 'water', 'unknown', 'skipped') + + +def _chunk_quarters(plan: ZoneRunPlan, block_lons: np.ndarray, row_lats: np.ndarray, + arrays: dict | None) -> dict: + """One chunk's additive per-quarter counts, for the own and anchor indexings. + + ``arrays`` holds the interior-sliced per-block count arrays (rows x blocks) + of a chunk that was read. ``None`` marks an open-ocean chunk that was + skipped: there the only thing to count is the analysis pixels it would have + had, which :func:`band_rows` adds back exactly as it does per cell. + """ + north = qc.qrow_of_row(row_lats, plan.quarters['center_lat']) == 0 + result = {} + for name, n_cells, lon_step, qrows, n_slots in _quarter_grids(plan): + cell = qc.cell_of_block(block_lons, lon_step, n_cells) + qcol = qc.qcol_of_block(block_lons, lon_step) + counts = {key: np.zeros(n_slots) for key in _QUARTER_COUNTS} + for qrow in qrows: + rows = north if qrow == 0 else ~north + slots = qc.slot_index(qrow, cell, qcol, n_cells) + if arrays is None: + counts['skipped'] += (np.bincount(slots, minlength=n_slots)[:n_slots] + * int(rows.sum())) + continue + for key, array in arrays.items(): + if array is not None: + counts[key] += np.bincount( + slots, weights=array[rows].sum(axis=0), + minlength=n_slots)[:n_slots] + result[name] = counts + return result + + +def zone_run_chunk(source: EarthSource, mosaics: _OpenMosaics, tmp_dir: Path, + plan: ZoneRunPlan, index: int, stats: ReadStats) -> dict: + """Read and reduce one longitude chunk of one zone run. + + Returns only this chunk's contribution; nothing here depends on any other + chunk, which is precisely what makes the group free to choose the order. + """ + first, last = plan.chunks[index] + n_cells, k_ew, width = plan.n_cells, plan.k_ew, plan.width + interior, block_lats = plan.interior, plan.block_lats + + if source.skip_empty_chunks and not _chunk_has_tiles( + source, plan.tile_rows, plan.tile_columns, first * k_ew, + min(last * k_ew, width), k_ew): + # Open ocean: no tile overlaps these columns, so every analysis pixel + # here is NaN. Skipping the read and the arrays is what keeps a job + # over a planet that is 71 per cent sea affordable; the one thing the + # shared reduction then cannot see is how many analysis pixels the + # chunk would have had, so it is accumulated and added back. + skipped = (np.bincount(plan.all_columns[first:last], minlength=n_cells)[:n_cells] + * plan.n_row_blocks) + out = {'segment': None, 'n_samples_200m_skipped': skipped} + if plan.quarters is not None: + out['quarter'] = _chunk_quarters( + plan, plan.all_lons[first:last], block_lats[interior], None) + return out + + read = [_piece_arrays(source, mosaics, tmp_dir, plan.tile_columns, plan.pad_row_start, + plan.pad_row_stop, plan.row_starts, plan.rows_per_block, low, high, + offset, k_ew, stats) + for low, high, offset in block_pieces(first, last, plan.n_blocks)] + padded = np.concatenate([r[0] for r in read], axis=1) + valid_per_block = np.concatenate([r[1] for r in read], axis=1) + present_per_block = np.concatenate([r[2] for r in read], axis=1) + total_per_block = np.concatenate([r[3] for r in read], axis=1) + lon_unwrapped = np.concatenate([r[4] for r in read]) + wet_per_block = (np.concatenate([r[5] for r in read], axis=1) + if source.read_water else None) + unknown_per_block = (np.concatenate([r[6] for r in read], axis=1) + if source.read_water else None) + del read + + # True stencil spacing on the ellipsoid, per output row and column. + # Unwrapping the halo longitudes rather than assuming 2*k_ew pixels is + # what keeps the short final block and the seam honest. + span_deg = lon_unwrapped[2:] - lon_unwrapped[:-2] + lat_mid = block_lats[1:-1] + dx_m = np.outer(prime_vertical_radius(lat_mid) * np.cos(np.deg2rad(lat_mid)), + span_deg) * (math.radians(1.0) / 2.0) + dy_m = (np.radians((block_lats[:-2] - block_lats[2:]) / 2.0) + * meridional_radius(lat_mid))[:, None] + + slope = horn_slope_deg(padded, dx_m, dy_m)[1:-1, 1:-1] # 2 blocks off each side + del dx_m, dy_m + relief = local_relief(padded) # also 2 off each side + elevation = padded[interior, BLOCK_HALO:padded.shape[1] - BLOCK_HALO] + del padded + + keep = slice(BLOCK_HALO, BLOCK_HALO + (last - first)) + normalized = plan.all_lons[first:last] + column_of_block = plan.all_columns[first:last] + segment = AnalysisSegment( + elevation=elevation, slope=slope, relief=relief, + column_of_block=column_of_block, block_lons=normalized, + row_lats=block_lats[interior]) + + inside = (interior, keep) + out = { + 'segment': segment, + 'n_native_samples': np.bincount( + column_of_block, weights=present_per_block[inside].sum(axis=0), + minlength=n_cells)[:n_cells].astype(np.int64), + 'n_valid_native_samples': np.bincount( + column_of_block, weights=valid_per_block[inside].sum(axis=0), + minlength=n_cells)[:n_cells].astype(np.int64), + } + if wet_per_block is not None: + # exactly the accounting n_valid_native_samples uses, over the same interior + # rows and the same owned blocks, so the fraction has a denominator + # it genuinely divides + out['n_source_water'] = np.bincount( + column_of_block, weights=wet_per_block[inside].sum(axis=0), + minlength=n_cells)[:n_cells].astype(np.int64) + out['water_unknown'] = np.bincount( + column_of_block, weights=unknown_per_block[inside].sum(axis=0), + minlength=n_cells)[:n_cells] > 0 + + if plan.quarters is not None: + # the per-block counts are about to be freed, so the per-quarter + # reduction has to happen here, against the same interior and the + # same owned blocks the per-column counts above use + out['quarter'] = _chunk_quarters( + plan, normalized, block_lats[interior], + {'native': present_per_block[inside], 'valid': valid_per_block[inside], + 'water': None if wet_per_block is None else wet_per_block[inside], + 'unknown': None if unknown_per_block is None else unknown_per_block[inside]}) + + # a block short of a tile anywhere in the window, dilated by the block + # halo the stencils actually use (already present in this chunk) + gap = (present_per_block < total_per_block).any(axis=0) + near = np.zeros(last - first, dtype=bool) + for shift in range(2 * BLOCK_HALO + 1): + near |= gap[shift:shift + (last - first)] + out['missing_near'] = np.bincount(column_of_block, weights=near.astype(np.float64), + minlength=n_cells)[:n_cells] > 0 + return out + + +def zone_run_finish(plan: ZoneRunPlan, pieces: dict) -> dict: + """Fold a zone run's chunks back together in ascending chunk order. + + The order matters even though every accumulator here is exact: the + segments are concatenated by the shared reduction, and concatenation order + decides the order of the floating-point sums inside it. Folding by index + rather than by arrival is what makes a reordered read bit-identical to an + in-order one, which a test pins. + """ + n_cells = plan.n_cells + segments: list[AnalysisSegment] = [] + n_native_samples = np.zeros(n_cells, dtype=np.int64) + n_valid_native_samples = np.zeros(n_cells, dtype=np.int64) + n_source_water = np.zeros(n_cells, dtype=np.int64) + water_unknown = np.zeros(n_cells, dtype=bool) + n_samples_200m_skipped = np.zeros(n_cells, dtype=np.float64) + missing_near = np.zeros(n_cells, dtype=bool) + quarters = None + if plan.quarters is not None: + quarters = {name: {key: np.zeros(n_slots) for key in _QUARTER_COUNTS} + for name, _, _, _, n_slots in _quarter_grids(plan)} + for index in range(len(plan.chunks)): + piece = pieces[index] + if quarters is not None: + for name, counts in piece['quarter'].items(): + for key, value in counts.items(): + quarters[name][key] += value + if piece['segment'] is None: + n_samples_200m_skipped += piece['n_samples_200m_skipped'] + continue + segments.append(piece['segment']) + n_native_samples += piece['n_native_samples'] + n_valid_native_samples += piece['n_valid_native_samples'] + if 'n_source_water' in piece: + n_source_water += piece['n_source_water'] + water_unknown |= piece['water_unknown'] + missing_near |= piece['missing_near'] + return {'segments': segments, 'n_native_samples': n_native_samples, + 'n_valid_native_samples': n_valid_native_samples, 'missing_near': missing_near, + 'n_source_water': n_source_water, 'water_unknown': water_unknown, + 'n_samples_200m_skipped': n_samples_200m_skipped, + 'k_ew': plan.k_ew, 'k_ns': plan.k_ns, 'tile_columns': plan.tile_columns, + 'n_rows': plan.row_stop - plan.row_start, 'n_blocks': plan.n_blocks, + 'zone_dropped': plan.zone_dropped, 'center_lat': plan.center_lat, + 'quarters': quarters} + + +def process_zone_run(source: EarthSource, mosaics: _OpenMosaics, tmp_dir: Path, band: int, + tile_columns: int, row_start: int, row_stop: int, + n_cells: int, lon_step: float, stats: ReadStats) -> dict: + """One zone run, planned, read in order and folded - the single-run path.""" + plan = zone_run_plan(source, band, tile_columns, row_start, row_stop, n_cells, lon_step) + pieces = {index: zone_run_chunk(source, mosaics, tmp_dir, plan, index, stats) + for index in range(len(plan.chunks))} + return zone_run_finish(plan, pieces) + + +# -------------------------------------------------------------------------- +# one band +# -------------------------------------------------------------------------- + +def band_context(grid: PlanetBandGrid, band: int) -> dict: + """Everything about a band that does not need pixels.""" + lat_min = float(grid.edges_deg[band]) + lat_max = float(grid.edges_deg[band + 1]) + n_cells = int(grid.column_counts[band]) + row_start, row_stop = band_row_range(grid, band) + return {'band': band, 'lat_min': lat_min, 'lat_max': lat_max, + 'center_lat': 0.5 * (lat_min + lat_max), 'n_cells': n_cells, + 'lon_step': 360.0 / n_cells, 'row_start': row_start, 'row_stop': row_stop, + 'runs': zone_runs(row_start, row_stop)} + + +def band_tile_rows(runs) -> list[int]: + """Tile rows a band's interior touches, north to south.""" + rows = [] + for _, start, stop in runs: + row = start + while row < stop: + rows.append(tile_lat_sw(row)) + row = tile_row_end(row) + return rows + + +def _run_block_grid(tile_columns: int, row_start: int, row_stop: int) -> dict: + """Block factors and block geometry of a zone run, without reading pixels.""" + width = 360 * tile_columns + center_lat = float(np.mean(row_center_lat([row_start, row_stop - 1]))) + k_ns = ns_block_factor(center_lat, max_factor=max(row_stop - row_start, 1)) + k_ew = ew_block_factor(center_lat, tile_columns, + max_factor=max(width // RELIEF_WINDOW, 1)) + n_blocks = -(-width // k_ew) + first_col = np.arange(n_blocks, dtype=np.int64) * k_ew + last_col = np.minimum(first_col + k_ew, width) - 1 + lons = col_center_lon((first_col + last_col) / 2.0, tile_columns) + return {'k_ew': k_ew, 'k_ns': k_ns, 'n_blocks': n_blocks, + 'n_row_blocks': -(-(row_stop - row_start) // k_ns), + 'block_lons': (lons + 180.0) % 360.0 - 180.0} + + +def _ocean_band_row(meta: dict) -> tuple[dict, dict]: + """An all-ocean band, without materialising arrays of NaN for it. + + Produced by the shared reduction with no segments, then given the only two + numbers that reduction cannot know without them: the analysis-pixel count + the band would have had, and the zero valid fraction that follows from it. + Every feature stays NaN and ``n_native_samples`` stays 0, exactly as the + general path leaves an ocean cell - a property the test suite pins by + running both paths over the same empty band. + """ + n_cells = meta['n_cells'] + zeros = np.zeros(n_cells, dtype=np.int64) + # the same initial state terrain_features.cell_features produces for input + # with no finite elevation anywhere + row = {name: np.full(n_cells, np.nan) for name in tf.FLOAT_FEATURES} + row['n_native_samples'] = zeros + row['n_valid_native_samples'] = zeros + row['n_rows_read'] = 0 + n_samples_200m = np.zeros(n_cells, dtype=np.float64) + grids = [(_run_block_grid(columns, start, stop), stop - start) + for columns, start, stop in meta['runs']] + for grid_info, _ in grids: + columns = np.clip(((grid_info['block_lons'] + 180.0) / meta['lon_step']).astype(np.int64), + 0, n_cells - 1) + n_samples_200m += (np.bincount(columns, minlength=n_cells)[:n_cells] + * grid_info['n_row_blocks']) + main = max(grids, key=lambda item: item[1])[0] + row['n_samples_200m'][:] = n_samples_200m + row['valid_frac_200m'][:] = np.where(n_samples_200m > 0, 0.0, np.nan) + row['ew_samples_averaged'][:] = main['k_ew'] + row['ns_samples_averaged'] = np.full(n_cells, main['k_ns'], dtype=np.float64) + # no tile, so no native pixel and therefore no fraction of one that is water + row['water_mask_frac'] = np.full(n_cells, np.nan) + row['n_valid_samples_200m'][:] = 0.0 + summary = {'k_ew': main['k_ew'], 'k_ns': main['k_ns'], + 'tile_columns': min(c for c, _, _ in meta['runs']), + 'zone_dropped': False, + 'mixed': len({(g['k_ew'], g['k_ns']) for g, _ in grids}) > 1, + 'degenerate': min(g['n_blocks'] for g, _ in grids) < RELIEF_WINDOW, + 'missing_near': np.zeros(n_cells, dtype=bool), + 'water_unknown': np.zeros(n_cells, dtype=bool)} + return row, summary + + +def band_plan(source: EarthSource, grid: PlanetBandGrid, band: int, + quarters: bool = False) -> dict: + """Plan a band's reads without making any. + + A band with no tile anywhere in it - open ocean, or any of the 134 bands + above latitude 84 - gets no zone run plans at all and so never reaches the + readers. Its rows are still written, because one row per grid cell is what + makes the Earth and Mars tables joinable. + """ + meta = band_context(grid, band) + has_tiles = any(source.row_tiles(lat_sw) for lat_sw in band_tile_rows(meta['runs'])) + # Bands are numbered south to north, so this band's northern half borders + # band + 1 and is re-indexed on that band's columns. The north-pole band + # has no band above it and so no anchor grid. + n_bands = len(grid.column_counts) + quarter_geometry = ({'center_lat': meta['center_lat'], + 'n_cells_anchor': (int(grid.column_counts[band + 1]) + if band + 1 < n_bands else None)} + if quarters else None) + plans = ([] if source.skip_empty_chunks and not has_tiles else + [zone_run_plan(source, band, columns, start, stop, meta['n_cells'], + meta['lon_step'], quarter_geometry) + for columns, start, stop in meta['runs']]) + return {'band': band, 'meta': meta, 'plans': plans} + + +def band_batches(grid: PlanetBandGrid, bands: list[int], block_rows: int = COG_BLOCK_ROWS, + limit: int = 0) -> list[list[int]]: + """Split consecutive bands into groups that share a COG block row. + + A GLO-30 COG is tiled 1024 rows deep and a 5 km band is ~163 native rows, + so about six consecutive bands are served by the same block row. Reading + those six together turns six fetches of that block row into one. ``limit`` + caps the batch regardless, because the batch is also the unit of peak + memory: every band in it holds its analysis arrays until the whole batch + has been read. + """ + batches: list[list[int]] = [] + current: list[int] = [] + low = high = 0 + for band in bands: + start, stop = band_row_range(grid, band) + if current: + new_low, new_high = min(low, start), max(high, stop) + if (new_high - new_low) <= block_rows and (not limit or len(current) < limit): + current.append(band) + low, high = new_low, new_high + continue + batches.append(current) + current, low, high = [band], start, stop + if current: + batches.append(current) + return batches + + +def process_band_batch(source: EarthSource, mosaics: _OpenMosaics, tmp_dir: Path, + grid: PlanetBandGrid, bands: list[int], stats: ReadStats, + quarters: bool = False) -> list[dict]: + """Read a batch of bands with the longitude chunk on the OUTSIDE. + + The reads are ordered by longitude first and band second, so every band + that needs a given block row takes it while it is still in GDAL's cache, + instead of each band walking the whole planet and evicting everything + before the next one starts. The pieces are stored by chunk index and folded + back in ascending order by :func:`zone_run_finish`, so the reordering + changes which bytes are fetched and when - never a single output value. + """ + plans = [band_plan(source, grid, band, quarters) for band in bands] + tasks = [] + for b, plan in enumerate(plans): + for r, run in enumerate(plan['plans']): + for c in range(len(run.chunks)): + tasks.append((run.chunk_lon(c), b, r, c)) + tasks.sort() + pieces: dict = {(b, r): {} for b, plan in enumerate(plans) + for r in range(len(plan['plans']))} + for _, b, r, c in tasks: + pieces[(b, r)][c] = zone_run_chunk( + source, mosaics, tmp_dir, plans[b]['plans'][r], c, stats) + return [band_rows(source, plan, [pieces[(b, r)] for r in range(len(plan['plans']))]) + for b, plan in enumerate(plans)] + + +def process_band(source: EarthSource, mosaics: _OpenMosaics, tmp_dir: Path, + grid: PlanetBandGrid, band: int, stats: ReadStats, + quarters: bool = False) -> dict: + """Read one band on its own and reduce it to per-cell features.""" + return process_band_batch(source, mosaics, tmp_dir, grid, [band], stats, quarters)[0] + + +def band_rows(source: EarthSource, plan: dict, pieces: list) -> dict: + """Fold a band's chunks into the per-cell feature row.""" + meta = plan['meta'] + band, n_cells = plan['band'], meta['n_cells'] + results = [zone_run_finish(run, pieces[index]) + for index, run in enumerate(plan['plans'])] + segments = [segment for r in results for segment in r['segments']] + + if not segments: + row, summary = _ocean_band_row(meta) + else: + row = tf.cell_features( + segments, n_cells, center_lat=meta['center_lat'], lon_step=meta['lon_step'], + n_native_samples=sum(r['n_native_samples'] for r in results), + n_valid_native_samples=sum(r['n_valid_native_samples'] for r in results), + local_metres=local_metres) + skipped = sum(r['n_samples_200m_skipped'] for r in results) + if np.any(skipped): + # The shared reduction counted only the chunks that were read. Add + # back the analysis pixels of the open-ocean chunks and restate the + # valid fraction over the whole cell, which is the same arithmetic + # terrain_features performs - pinned by a test that runs the band + # again with skipping disabled and demands identical output. + row['n_samples_200m'][:] = row['n_samples_200m'] + skipped + row['valid_frac_200m'][:] = np.where( + row['n_samples_200m'] > 0, row['n_valid_samples_200m'] / np.maximum(row['n_samples_200m'], 1), np.nan) + main = max(results, key=lambda r: r['n_rows']) + row['ew_samples_averaged'][:] = main['k_ew'] + row['ns_samples_averaged'] = np.full(n_cells, main['k_ns'], dtype=np.float64) + missing = np.zeros(n_cells, dtype=bool) + unknown = np.zeros(n_cells, dtype=bool) + for r in results: + missing |= r['missing_near'] + unknown |= r['water_unknown'] + row['water_mask_frac'] = water_fraction( + np.asarray(row['n_native_samples']), + sum(r['n_source_water'] for r in results), unknown, + enabled=source.read_water) + summary = {'k_ew': main['k_ew'], 'k_ns': main['k_ns'], + 'tile_columns': min(r['tile_columns'] for r in results), + 'zone_dropped': any(r['zone_dropped'] for r in results), + 'mixed': len({(r['k_ew'], r['k_ns']) for r in results}) > 1, + 'degenerate': min(r['n_blocks'] for r in results) < RELIEF_WINDOW, + 'missing_near': missing, 'water_unknown': unknown} + + row['quality_flags'] = quality_flags(meta, row, summary) + row['band'] = np.full(n_cells, band, dtype=np.int32) + row['column'] = np.arange(n_cells, dtype=np.int32) + if segments and plan['plans'][0].quarters is not None: + row['quarters'] = band_quarters(results, meta, source.read_water) + return row + + +# -------------------------------------------------------------------------- +# 2.5 km quarter cells (additive merge inputs, see quarter_cells.py) +# -------------------------------------------------------------------------- + +def _quarter_records(feats, band, anchor_band, n_cells, planet_prefix): + """Flatten per-slot arrays into key + feature columns, dropping empty slots.""" + n_slots = len(feats['n_samples_200m']) + keep = np.flatnonzero(feats['n_samples_200m'] > 0) + qcol = keep % 2 + column = (keep // 2) % n_cells + qrow = keep // (2 * n_cells) + out = { + 'quarter_id': [qc.quarter_id(planet_prefix, band, anchor_band, int(c), int(r), int(q)) + for c, r, q in zip(column, qrow, qcol)], + 'band': np.full(len(keep), band, dtype=np.int32), + 'anchor_band': np.full(len(keep), anchor_band, dtype=np.int32), + 'column': column.astype(np.int32), + 'qrow': qrow.astype(np.int32), + 'qcol': qcol.astype(np.int32), + 'n_dropped_empty': n_slots - len(keep), + } + for name in (*qc.QUARTER_FLOAT_COLUMNS, *qc.QUARTER_INT_COLUMNS, *qc.QUARTER_LIST_COLUMNS): + if name in feats: + out[name] = feats[name][keep] + return out + + +def band_quarters(results: list[dict], meta: dict, read_water: bool) -> dict: + """Per-quarter additive statistics for one band: own grid and anchor grid. + + ``results`` are the band's :func:`zone_run_finish` dicts, so the elevation, + slope and relief reduction sees the same segment list ``tf.cell_features`` + does, and the native, water and open-ocean counts are the per-quarter + siblings of the per-column ones, accumulated chunk by chunk and run by run. + The weighting factors are the exception to "same as the cell": a band's + zone runs have their own ``k_ew``/``k_ns``, so each run's pixels are + weighted by that run's own factors rather than by the longest run's. + Returns ``{'own': records, 'anchor': records or None}``. + """ + prefix = PLANETS[PLANET]['prefix'] + band, center_lat = meta['band'], meta['center_lat'] + segments = [segment for r in results for segment in r['segments']] + lon_scale = lambda lat: (math.radians(1.0) * prime_vertical_radius(lat) + * np.cos(np.deg2rad(lat))) + lat_scale = math.radians(1.0) * float(meridional_radius(center_lat)) + + def reduce(name, n_cells, lon_step, slots_of_segment, n_slots, anchor_band): + feats = qc.quarter_features( + segments, n_slots, slots_of_segment=slots_of_segment, + origin_lon=qc.slot_origin_lon(n_cells, lon_step, n_slots), + origin_lat=center_lat, lon_scale=lon_scale, lat_scale=lat_scale) + total = {key: np.zeros(n_slots) for key in qc_counts} + ew = np.zeros(n_slots) + ns = np.zeros(n_slots) + for r in results: + counts = r['quarters'][name] + for key in qc_counts: + total[key] += counts[key] + pixels = counts['skipped'].copy() + for segment in r['segments']: + # None means this segment has no row on the anchor grid at + # all, which is how anchor_grid_slots reports a segment that + # lies entirely south of the band centre. It contributes no + # pixel to weight, exactly as quarter_features' own walk() + # already treats it. + placing = slots_of_segment(segment) + if placing is None: + continue + slots = np.asarray(placing).ravel() + slots = slots[slots >= 0] + pixels += np.bincount(slots, minlength=n_slots)[:n_slots] + ew += r['k_ew'] * pixels + ns += r['k_ns'] * pixels + # open-ocean chunks were never reduced; add their analysis pixels back + feats['n_samples_200m'] = feats['n_samples_200m'] + total['skipped'] + feats['n_native_samples'] = np.rint(total['native']) + feats['n_valid_native_samples'] = np.rint(total['valid']) + feats['ew_samples_weighted'] = ew + feats['ns_samples_weighted'] = ns + feats['n_native_water'] = np.rint(total['water']) + # no mask read means no pixel is known to be dry: all unknown, so the + # window's water fraction is NaN, as the cell's is + feats['n_native_water_unknown'] = (np.rint(total['unknown']) if read_water + else np.rint(total['native'])) + return _quarter_records(feats, band, anchor_band, n_cells, prefix) + + qc_counts = _QUARTER_COUNTS + n_cells, lon_step = meta['n_cells'], meta['lon_step'] + own = reduce('own', n_cells, lon_step, + lambda s: qc.own_grid_slots(s, n_cells=n_cells, lon_step=lon_step, + center_lat=center_lat), + 4 * n_cells, band) + anchor = None + if 'anchor' in results[0]['quarters']: + n_anchor = len(results[0]['quarters']['anchor']['native']) // 2 + a_step = 360.0 / n_anchor + anchor = reduce('anchor', n_anchor, a_step, + lambda s: qc.anchor_grid_slots( + s, n_cells_anchor=n_anchor, lon_step_anchor=a_step, + center_lat=center_lat), + 2 * n_anchor, band + 1) + return {'own': own, 'anchor': anchor} + + +def build_quarter_table(results: list[dict], provenance: dict, bands: list[int]): + """One Parquet table of quarter records from ``band_quarters`` results. + + ``bands`` is every band the group covered, ocean bands included, and is + stored in the metadata so ``--resume`` can tell a finished group from a + partial one the same way it does for the terrain file. + """ + import pyarrow as pa + records = [r[part] for r in results for part in ('own', 'anchor') if r[part] is not None] + + def cat(name, dtype=None): + parts = [np.asarray(r[name]) for r in records] + return np.concatenate(parts) if parts else np.zeros(0, dtype=dtype) + + n = sum(len(r['band']) for r in records) + data = { + 'quarter_id': pa.array([q for r in records for q in r['quarter_id']], type=pa.string()), + 'planet': tf._constant(PLANET, n), + } + for name in qc.QUARTER_KEY_COLUMNS[2:]: + data[name] = pa.array(cat(name, np.int32).astype(np.int32)) + for name in qc.QUARTER_FLOAT_COLUMNS: + if records and name in records[0]: + data[name] = pa.array(cat(name).astype(np.float64)) + for name in qc.QUARTER_INT_COLUMNS: + data[name] = pa.array(cat(name, np.int64).astype(np.int64)) + for name in qc.QUARTER_LIST_COLUMNS: + # A header-only group (every band above 84 N) must carry the same + # int32 list type as a full one: audit_quarter_table dates a file by + # that type and refuses anything else, which would stop the compose. + width = records[0][name].shape[1] if records else qc.N_BINS + flat = (cat(name, np.int32).astype(np.int32).reshape(-1, width) if records + else np.zeros((0, width), dtype=np.int32)) + data[name] = pa.FixedSizeListArray.from_arrays( + pa.array(flat.ravel(), type=pa.int32()), width) + data['quarter_version'] = tf._constant(qc.QUARTER_VERSION, n) + data['code_version'] = tf._constant(provenance['code_version'], n) + # The terrain code_version above does not cover quarter_cells.py, + # which decides every number in this table. This one does. + version = qc.quarter_code_version(Path(__file__)) + data['quarter_code_version'] = tf._constant(version, n) + table = pa.table(data) + return table.replace_schema_metadata({ + 'quarter_version': qc.QUARTER_VERSION, + 'bands': json.dumps(sorted(int(b) for b in bands)), + # also in the metadata, so --resume can date a header-only file too + 'quarter_code_version': version, + 'provenance': json.dumps(provenance, sort_keys=True), + }) + + +def quarter_group_is_current(path: Path, wanted: list[int]) -> bool: + """A resumable quarter group: complete, AND written by this code. + + ``group_is_complete`` only reads the band list. A shard resumes from + whatever an earlier run left on the Hub, so without this a re-run would + keep every group the old code finished and redo only the rest - one + release with two ``quarter_code_version`` values. A file that predates + the metadata key is stale by definition. + """ + if not group_is_complete(path, wanted): + return False + import pyarrow.parquet as pq + try: + metadata = pq.read_schema(path).metadata or {} + written_by = metadata[b'quarter_code_version'].decode() + except Exception: + return False + return written_by == qc.quarter_code_version(Path(__file__)) + + +def quarter_path(out_dir: Path, group: int) -> Path: + return Path(out_dir) / qc.QUARTER_VERSION / f'band_group={group:03d}.parquet' + + +def water_fraction(n_native_samples: np.ndarray, n_source_water: np.ndarray, + water_unknown: np.ndarray, enabled: bool = True) -> np.ndarray: + """Native water pixels over native pixels, per grid cell. + + NaN rather than zero in all three cases where the answer is not known: no + native pixel at all (open ocean, where there is nothing to take a fraction + of), a DEM tile whose Water Body Mask is missing, and the WBM read turned + off. Writing 0.0 for any of them would be a measurement the files do not + support, and would read downstream as "verified dry". + """ + n_native_samples = np.asarray(n_native_samples) + if not enabled: + return np.full(len(n_native_samples), np.nan) + known = (n_native_samples > 0) & ~np.asarray(water_unknown) + with np.errstate(invalid='ignore', divide='ignore'): + return np.where(known, np.asarray(n_source_water, dtype=np.float64) + / np.maximum(n_native_samples, 1), np.nan) + + +def quality_flags(meta: dict, row: dict, summary: dict) -> list[str]: + """The shared advisory flags plus the seven this product needs. + + ``ocean_only`` and ``coastal_partial`` are mutually exclusive by + construction. ``tile_missing_neighbour`` does co-occur with + ``coastal_partial`` along a coastline, where the absent tile really is sea: + it marks "a tile this cell needed was not there", which is a pointer to + check rather than an assertion of error, and it is the only signal that + separates a hole inside land from the edge of the world. + + The three water flags are read off ``water_mask_frac`` and say nothing about + any other column. ``water_only`` is a cell the mask calls water almost + everywhere and ``water_partial`` a cell of mixed land and water - a + coastline, a lake shore or a river bank. ``water_partial`` has a lower + bound as well as an upper one, because a flag that fired on a single pond + would fire on most of the land surface and mark nothing. ``wbm_missing`` + is the separate statement that the mask was unavailable, which is why it + replaces the other two rather than joining them: with no mask there is no + fraction to threshold. + """ + n_source = np.asarray(row['n_native_samples']) + n_native_valid = np.asarray(row['n_valid_native_samples']) + fraction = np.asarray(row['valid_frac_200m']) + water = np.asarray(row['water_mask_frac']) + unknown = summary['water_unknown'] + ocean = (n_source == 0) | (n_native_valid == 0) + per_cell = [] + for index in range(len(n_source)): + own: list[str] = [] + if ocean[index]: + own.append(FLAG_OCEAN_ONLY) + else: + if np.isfinite(fraction[index]) and 0.0 < fraction[index] < LOW_COVERAGE_FRACTION: + own.append(FLAG_COASTAL_PARTIAL) + if summary['missing_near'][index]: + own.append(FLAG_MISSING_NEIGHBOUR) + # water is judged on native pixels, so it is reported for every cell + # that has one - including a tile that exists but reads all nodata + if unknown[index] and n_source[index] > 0: + own.append(FLAG_WBM_MISSING) + elif np.isfinite(water[index]): + if water[index] >= WATER_ONLY_FRACTION: + own.append(FLAG_WATER_ONLY) + elif water[index] >= WATER_PARTIAL_FRACTION: + own.append(FLAG_WATER_PARTIAL) + per_cell.append(own) + shared_extra = [] + if summary['tile_columns'] < FINEST_TILE_COLUMNS: + shared_extra.append(FLAG_HIGH_LAT_EW) + if len({columns for columns, _, _ in meta['runs']}) > 1: + shared_extra.append(FLAG_ZONE_SPLIT) + if summary['zone_dropped']: + shared_extra.append(FLAG_ZONE_HALO) + return tf.quality_flags( + meta['center_lat'], fraction, np.asarray(row['n_samples_200m']), + mixed_factor=summary['mixed'], degenerate=summary['degenerate'], + shared_extra=shared_extra, per_cell_extra=per_cell) + + +# -------------------------------------------------------------------------- +# native pixel windows: a grid cell back to the pixels it was made from +# -------------------------------------------------------------------------- + +@dataclass(frozen=True) +class WindowSegment: + """One zone's worth of a band's native pixel window, per grid cell. + + ``row_min``/``row_max`` are global pixel rows of the whole planet, row 0 at + latitude 90, half open. ``col_min``/``col_max`` are columns of the virtual + mosaic of this zone, which is ``360 * tile_columns`` wide and starts at + longitude -180, also half open. ``present`` is False for a grid cell that + owns no analysis block in this zone at all, which happens where the + meridians converge and one block is wider than a cell. + """ + tile_columns: int + row_min: int + row_max: int + col_min: np.ndarray + col_max: np.ndarray + present: np.ndarray + + +def band_cell_windows(grid: PlanetBandGrid, band: int) -> list[WindowSegment]: + """Native pixel window of every cell of one band, zone by zone. + + Nothing is re-derived: the rows are :func:`band_row_range` through + :func:`band_context`, and the columns come from the same block arithmetic + :func:`zone_run_plan` uses - ``ew_block_factor`` capped the same way, + blocks of ``k_ew`` native columns with a short final block, the block + centre longitude, and the same ``column_of_block`` clip. A cell's window is + the span from the first to the last block it owns, which is contiguous + because the block centre longitudes increase monotonically across the + mosaic. + + Returns one segment per zone run, north to south. All but ten of the 4001 + bands give exactly one; the ten that straddle a pixel-width zone boundary + give two, and a cell in them genuinely owns pixels in two different + mosaics at two different pixel widths. That is represented as two + segments rather than by choosing one and discarding the other. + """ + meta = band_context(grid, band) + n_cells = meta['n_cells'] + cells = np.arange(n_cells, dtype=np.int64) + segments = [] + for tile_columns, row_start, row_stop in meta['runs']: + info = _run_block_grid(tile_columns, row_start, row_stop) + k_ew, n_blocks = info['k_ew'], info['n_blocks'] + width = 360 * tile_columns + starts = np.arange(n_blocks, dtype=np.int64) * k_ew + stops = np.minimum(starts + k_ew, width) + columns = np.clip(((info['block_lons'] + 180.0) / meta['lon_step']).astype(np.int64), + 0, n_cells - 1) + if np.any(np.diff(columns) < 0): + raise AssertionError(f'band {band}: blocks are not column-monotone') + first = np.searchsorted(columns, cells, side='left') + last = np.searchsorted(columns, cells, side='right') + present = last > first + col_min = np.zeros(n_cells, dtype=np.int64) + col_max = np.zeros(n_cells, dtype=np.int64) + col_min[present] = starts[first[present]] + col_max[present] = stops[last[present] - 1] + segments.append(WindowSegment(tile_columns=int(tile_columns), row_min=int(row_start), + row_max=int(row_stop), col_min=col_min, + col_max=col_max, present=present)) + return segments + + +def resolve_region(grid: PlanetBandGrid, source: EarthSource, region_id: str) -> list[dict]: + """Turn one ``region_id`` into the concrete GLO-30 reads behind it. + + The window columns cannot carry this on their own: which tiles exist is a + property of the published index, not of the geometry, and 63.8 per cent of + Earth's cells have no tile at all. This walks the cell's window, keeps only + the tiles the index actually lists, and returns, per tile, the URL of the + DEM, the URL of its Water Body Mask, and the sub-window *inside that tile* + that the extractor read - so a caller can reproduce one cell's pixels + without touching anything else. + + A cell with no existing tile returns an empty list, which is the honest + answer for open ocean. + """ + band, column = parse_region_id(grid, region_id) + out = [] + for segment in band_cell_windows(grid, band): + if not segment.present[column]: + continue + tile_columns = segment.tile_columns + col_min = int(segment.col_min[column]) + col_max = int(segment.col_max[column]) + row = segment.row_min + while row < segment.row_max: + lat_sw = tile_lat_sw(row) + row_stop = min(segment.row_max, tile_row_end(row)) + for tile_col in range(col_min // tile_columns, (col_max - 1) // tile_columns + 1): + lon_sw = tile_col - 180 + if not source.has(lat_sw, lon_sw): + continue + base = tile_col * tile_columns + start = max(col_min, base) + stop = min(col_max, base + tile_columns) + stem = tile_stem(lat_sw, lon_sw) + out.append({ + 'region_id': region_id, 'band': band, 'column': column, + 'stem': stem, 'tile_lat_sw': lat_sw, 'tile_lon_sw': lon_sw, + 'tile_columns': tile_columns, + 'elevation_url': tile_url(source.root, lat_sw, lon_sw), + 'water_mask_url': (wbm_url(source.root, lat_sw, lon_sw) + if source.has_water(lat_sw, lon_sw) else None), + # window inside the tile itself, half open, row 0 at its top + 'row_off': row % TILE_ROWS, 'n_rows': row_stop - row, + 'col_off': start - base, 'n_cols': stop - start, + # and where that sits in the zone's virtual mosaic + 'mosaic_row_min': row, 'mosaic_row_max': row_stop, + 'mosaic_col_min': start, 'mosaic_col_max': stop, + }) + row = row_stop + return out + + +_REGION_RE = re.compile(r'([A-Za-z]+)_(\d{4})_(\d{5})') + + +def parse_region_id(grid: PlanetBandGrid, region_id: str) -> tuple[int, int]: + """``E_2000_04007`` -> ``(2000, 4007)``, checked against the grid.""" + match = _REGION_RE.fullmatch(str(region_id).strip()) + if not match: + raise ValueError(f'{region_id!r} is not a region_id') + prefix, band, column = match.group(1), int(match.group(2)), int(match.group(3)) + if prefix != PLANETS[PLANET]['prefix']: + raise ValueError(f'{region_id!r} is not an Earth region_id') + if not 0 <= band < len(grid.column_counts): + raise ValueError(f'{region_id!r}: band {band} is outside the grid') + if not 0 <= column < int(grid.column_counts[band]): + raise ValueError(f'{region_id!r}: band {band} has only ' + f'{int(grid.column_counts[band])} columns') + return band, column + + +def build_table(rows: list[dict], provenance: dict): + """Concatenate per-band results into one Parquet table.""" + return tf.build_table(rows, provenance, PLANET, extra_float_features=EXTRA_FLOAT_FEATURES) + + +# -------------------------------------------------------------------------- +# driver +# -------------------------------------------------------------------------- + +def load_source_manifest(source_dir: Path) -> dict: + """Read ``source_manifest.json`` and pull out the fields the pipeline needs. + + The zone table is taken from the manifest when it is there and checked + against this module's constants, so a corrected manifest cannot silently + disagree with the code that reads the tiles. + """ + source_dir = Path(source_dir) + manifest_path = source_dir / 'source_manifest.json' + manifest = json.loads(manifest_path.read_text(encoding='utf8')) + try: + product = manifest['product'] + info = {'manifest_path': manifest_path, + 'source_product': str(product['name']), + 'source_version': str(product['version'])} + except KeyError as exc: + raise ValueError(f'{manifest_path} is missing required key {exc}') from exc + raster = manifest.get('raster', {}) + nodata = raster.get('nodata_value', manifest.get('nodata', {}).get('value')) + info['nodata'] = None if nodata is None else float(nodata) + zones = raster.get('zones') + if zones: + parsed = tuple((int(z['abs_lat_from']), int(z['abs_lat_to']), int(z['tile_columns'])) + for z in zones) + if parsed != ZONES: + raise ValueError(f'{manifest_path} zone table {parsed} disagrees with {ZONES}') + for zone in zones: + expected = float(TILE_DEG) / int(zone['tile_columns']) + width = zone.get('geotransform_pixel_width_deg') + if width is not None and not math.isclose(float(width), expected, rel_tol=1e-12): + raise ValueError(f'{manifest_path}: zone {zone["abs_lat_from"]} pixel width ' + f'{width} disagrees with {expected}') + if int(zone.get('tile_rows', TILE_ROWS)) != TILE_ROWS: + raise ValueError(f'{manifest_path}: a zone does not have {TILE_ROWS} rows') + water = manifest.get('water_body_mask') + if water: + codes = water.get('water_value_codes') + if codes is not None and tuple(int(c) for c in codes) != WATER_VALUES: + raise ValueError(f'{manifest_path} water codes {tuple(codes)} disagree ' + f'with {WATER_VALUES}') + info['water_codes_verified'] = bool(water.get('verified_from_files')) + info['water_value_codes'] = WATER_VALUES + bucket = manifest.get('bucket', {}) + info['bucket'] = bucket.get('name', DEFAULT_BUCKET) + info['tile_index_file'] = bucket.get('tile_index_file', 'tileList.txt') + return info + + +def process_group(group: int, bands: list[int], source: EarthSource, out_dir: Path, + provenance: dict, quarters: bool = False) -> dict: + """Process one band group, write its Parquet file, drop its temp folder.""" + started = time.monotonic() + grid = PlanetBandGrid.build(PLANET) + stats = ReadStats() + counter = _ByteCounter(stats) + gdal_log = logging.getLogger(GDAL_LOGGER) + previous_level = gdal_log.level + if source.debug_http: + gdal_log.setLevel(logging.DEBUG) + gdal_log.addHandler(counter) + tmp_dir = Path(tempfile.mkdtemp(prefix=f'earth-terrain-{group:03d}-')) + mosaics = _OpenMosaics() + try: + with source.env(): + rows = [] + writer = qc.QuarterWriter(quarter_path(out_dir, group)) if quarters else None + for batch in band_batches(grid, bands, limit=source.bands_in_flight): + produced = process_band_batch(source, mosaics, tmp_dir, grid, batch, + stats, quarters) + if writer is not None: + # Hand each band's quarters to the file and let them go. A + # whole group of them is several gigabytes in one worker. + for row in produced: + band_quarters_ = row.pop('quarters', None) + if band_quarters_ is not None: + writer.write(build_quarter_table([band_quarters_], + provenance, bands)) + rows.extend(produced) + path = group_path(out_dir, group) + write_atomic(build_table(rows, provenance), path) + if writer is not None: + writer.close(empty=lambda: build_quarter_table([], provenance, bands)) + finally: + mosaics.close() + gdal_log.removeHandler(counter) + gdal_log.setLevel(previous_level) + shutil.rmtree(tmp_dir, ignore_errors=True) + return {'group': group, 'bands': len(bands), + 'rows': int(sum(len(r['column']) for r in rows)), + 'source_pixels': int(sum(int(np.sum(r['n_native_samples'])) for r in rows)), + 'tiles': len(stats.tiles), 'mosaics': stats.mosaics, 'pixels': stats.pixels, + 'water_pixels': stats.water_pixels, + 'http_bytes': stats.http_bytes, 'http_ranges': stats.http_ranges, + 'retried': stats.retried, 'seconds': time.monotonic() - started, + 'path': str(path)} + + +def _format_bytes(result: dict) -> str: + # 4 bytes per DEM sample, 1 per WBM code: the honest decoded total, so the + # HTTP-to-decoded ratio is not flattered by counting the mask as float32 + decoded = (result['pixels'] * 4 + result.get('water_pixels', 0)) / 2 ** 20 + if result['http_ranges']: + # '>=' because reads through a VRT's sources happen on GDAL threads + # this counter cannot see; see _ByteCounter + return (f">={result['http_bytes'] / 2 ** 20:.1f} MiB over HTTP in " + f"{result['http_ranges']} ranges (lower bound), " + f'{decoded:.1f} MiB decoded') + return f'HTTP bytes n/a, {decoded:.1f} MiB decoded' + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('--bands', default=None, + help='inclusive band range START-END (default: every band)') + parser.add_argument('--source', type=Path, default=DEFAULT_SOURCE_DIR, + help='directory holding source_manifest.json') + parser.add_argument('--out', type=Path, default=DEFAULT_OUT_DIR, + help=f'output root; files land in /{FEATURE_VERSION}/') + parser.add_argument('--workers', type=int, default=1, help='band groups in parallel') + parser.add_argument('--resume', action='store_true', + help='skip band groups whose output already covers them') + parser.add_argument('--quarters', action='store_true', + help=f'also write 2.5 km quarter cells to /{qc.QUARTER_VERSION}/') + parser.add_argument('--max-tiles-in-flight', type=int, default=8, + help='tile columns read at once; caps memory and bandwidth') + parser.add_argument('--bands-in-flight', type=int, default=0, + help='bands read together so they share a COG block row ' + '(0: as many as fit in one, ~6; 1: one band at a time, ' + 'the old read order). This is the peak-memory knob.') + parser.add_argument('--gdal-cache-mb', type=int, default=DEFAULT_GDAL_CACHE_MB, + help='GDAL block cache per worker, MB; must hold the block ' + 'rows a batch walks across or the batching buys nothing') + parser.add_argument('--retries', type=int, default=4, + help='attempts per windowed read before the band group fails') + parser.add_argument('--tile-index', default=None, + help='path or URL of tileList.txt (default: the public bucket)') + parser.add_argument('--tile-root', default=None, + help='root holding /.tif (default: /vsis3/)') + parser.add_argument('--wbm-index', default=None, + help='path or URL listing the DEM stems whose Water Body Mask ' + 'exists (default: every tile in the tile index)') + parser.add_argument('--no-gdal-env', action='store_true', + help='do not set the anonymous-S3 GDAL options (local tiles)') + parser.add_argument('--no-skip-ocean', action='store_true', + help='read and reduce chunks with no tiles too (slow; for verification)') + parser.add_argument('--no-water', action='store_true', + help='do not read the Water Body Mask; water_mask_frac is all NaN') + parser.add_argument('--debug-http', action='store_true', + help='count the byte ranges GDAL reports; a LOWER BOUND only, since ' + 'reads through a VRT happen on threads it cannot see') + args = parser.parse_args(argv) + + grid = PlanetBandGrid.build(PLANET) + bands = (parse_band_range(args.bands, len(grid.column_counts)) if args.bands + else list(range(len(grid.column_counts)))) + info = load_source_manifest(args.source) + local_index = args.source / info['tile_index_file'] + index = (args.tile_index or (str(local_index) if local_index.exists() else + f'https://{info["bucket"]}.s3.amazonaws.com/{info["tile_index_file"]}')) + print(f'tile index: {index}', flush=True) + tiles = load_tile_index(index) + source = EarthSource( + root=args.tile_root or f'/vsis3/{info["bucket"]}', + tiles=tiles, nodata=info['nodata'], + max_tiles_in_flight=max(args.max_tiles_in_flight, 1), + retries=max(args.retries, 1), use_gdal_env=not args.no_gdal_env, + skip_empty_chunks=not args.no_skip_ocean, debug_http=args.debug_http, + read_water=not args.no_water, bands_in_flight=max(args.bands_in_flight, 0), + gdal_cache_mb=max(args.gdal_cache_mb, 1), + water_tiles=load_tile_index(args.wbm_index) if args.wbm_index else None) + provenance = { + 'source_product': info['source_product'], + 'source_version': info['source_version'], + 'source_checksum': f'tileindex-sha256:{tile_index_sha256(index)}', + 'code_version': code_version(), + 'computed_at': datetime.now(timezone.utc).isoformat(timespec='seconds'), + 'tile_index': str(index), + 'tiles_in_index': len(tiles), + 'water_mask': ('WBM codes ' + ','.join(str(v) for v in WATER_VALUES) + if not args.no_water else 'not read'), + 'wbm_index': str(args.wbm_index) if args.wbm_index else 'same as the tile index', + 'bands_in_flight': args.bands_in_flight or 'one COG block row', + } + work = plan_groups(bands) + if args.resume: + kept = [] + for group, group_bands in work: + # a stale quarter file sends the whole group back, terrain file + # included, so the two are always rewritten as a pair + if (group_is_complete(group_path(args.out, group), group_bands) + and (not args.quarters or quarter_group_is_current( + quarter_path(args.out, group), group_bands))): + print(f'group {group:03d}: already complete, skipped', flush=True) + else: + kept.append((group, group_bands)) + work = kept + print(f'{len(bands)} bands in {len(work)} groups -> {args.out / FEATURE_VERSION} ' + f'({len(tiles)} tiles in index)', flush=True) + + started = time.monotonic() + totals = {'rows': 0, 'source_pixels': 0, 'tiles': 0, 'pixels': 0, 'water_pixels': 0, + 'http_bytes': 0} + + def report(result): + for key in totals: + totals[key] += result[key] + print(f"group {result['group']:03d}: {result['bands']} bands, {result['rows']} rows, " + f"{result['source_pixels']} source pixels, {result['tiles']} tiles, " + f"{result['mosaics']} mosaics, {_format_bytes(result)}, " + f"{result['retried']} retried reads, {result['seconds']:.1f}s " + f"-> {result['path']}", flush=True) + + if args.workers > 1 and len(work) > 1: + with ProcessPoolExecutor(max_workers=args.workers) as pool: + futures = {pool.submit(process_group, g, b, source, args.out, provenance, + args.quarters): g + for g, b in work} + for future in as_completed(futures): + report(future.result()) + else: + for group, group_bands in work: + report(process_group(group, group_bands, source, args.out, provenance, + args.quarters)) + + print(f"done: {totals['rows']} rows, {totals['source_pixels']} source pixels, " + f"{totals['tiles']} tiles, " + f"{(totals['pixels'] * 4 + totals['water_pixels']) / 2 ** 20:.1f} MiB decoded " + f"(>={totals['http_bytes'] / 2 ** 20:.1f} MiB over HTTP, lower bound), " + f'{time.monotonic() - started:.1f}s', flush=True) + return 0 + + +if __name__ == '__main__': + sys.exit(main())