Datasets:
Download code/layers/driver.py from enzeeoai/starman: direct link, hf CLI and curl.
- Browser
- Download file 134 kB
-
https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/layers/driver.py
- Command line
-
hf download hf://datasets/enzeeoai/starman/code/layers/driver.py
-
curl -L -o driver.py https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/layers/driver.py
134 kB
"""Run dataset layer modules over the latband5km-v1 grid and upload them to the Hub as they finish.
Usage (from the repository root):
python -m pipeline.layers.driver <slug>[,<slug>...] --planet mars|earth [--bands START-END]
[--resume] [--workers N] [--cache-max-gb G] [--retries R] [--dry-run] [--no-upload] [--out DIR]
python -m pipeline.layers.driver <slug> --planet mars|earth --publish [--dry-run]
Layer module interface (``pipeline/layers/<slug>.py``)
------------------------------------------------------
``SOURCE`` dict: ``product``, ``version``, ``url``, ``licence``, ``planet`` (``mars`` | ``earth`` |
``both``) and optionally ``aux``, a list of further source dicts.
``COLUMNS`` dict: feature column -> ``{'dtype', 'unit', 'description', 'comparison', 'fill'}``.
``dtype`` defaults to ``float32``; ``comparison`` is one of :data:`COMPARISON_MODES`;
``fill`` is the value given to cells with no data (default NaN / null), for example
``0.0`` for a ``valid_frac`` column. The driver needs it to write rows for cells the
layer has no data for, and ``--publish`` needs units and comparison modes.
``plan(band_group, ctx)`` -> list of source items. An item is an :class:`Item`, a dict of
:class:`Item` fields, or a URL string. ``[]`` means "no source data": every cell gets
the fill values and the missing flag, and ``reduce`` is not called.
``reduce(band_group, items, ctx)`` -> ``pyarrow.Table`` keyed by ``region_id`` holding feature
columns (and optionally ``quality_flags``) only. ``items`` is an :class:`Items`
view: iterate it to stream items through the cache (each item is fetched when
reached and deleted when the loop moves on), or use ``items.get(key)`` /
``items.release(key)`` / ``items.all()`` for random access. Cells missing from the
table get the fill values and the missing flag.
Asset catalog (optional, see ``docs/asset_catalog.md`` and ``pipeline/catalog/``):
* An item from ``plan()`` may carry ``asset={...}`` (uri, footprint, geotransform, time range, ...).
The driver turns those into ``assets`` rows.
* ``reduce()`` may return ``(feature_table, coverage_table)``, the second holding ``region_id``,
``asset_id``, ``coverage_frac``. Without it the driver computes ``coverage_frac`` from the item
footprints and the grid, vectorised per band group (items with ``link_regions=False`` or
``covers_planet=True`` get no ``region_assets`` rows).
* Per band group the same commit carries ``catalog/region_assets/planet=<p>/layer=<slug>/band_group=NNN.parquet``
and ``catalog/assets_staging/...`` (that group's assets rows); ``--publish`` merges the staging files
into ``catalog/assets/planet=<p>/layer=<slug>.parquet`` (deduplicated by ``asset_id``).
Optional:
``prepare(ctx)`` one-time work before band groups run: small downloads into ``ctx.raw_dir``
(``data/raw/<planet>/<slug>/``, see ``ctx.download``) or streaming global
sources into ``ctx.interim_dir`` (``data/interim/<planet>/<slug>/``, capped by
``--interim-max-gb``, never uploaded, deleted after a successful publish).
``finalize(ctx)`` whole-planet post-pass. Reads band groups with ``ctx.read_layer(g, columns)``
over ``ctx.band_groups`` and writes extra column sets with
``ctx.write_extra(name, g, table)``; each name must be declared in
``EXTRA_COLUMNS = {name: COLUMNS-style dict}``.
``PASS_GROUP`` name shared by layers that read the same expensive source. Layers named
together on the command line with the same PASS_GROUP run in one pass: each
item is fetched once and handed to every layer that planned it.
``MISSING_FLAG`` quality flag for cells with no data: a string (default ``no_source``) or
``callable(band_group, missing_cells_table, ctx) -> list[str]`` (e.g. to say
``ocean`` using :func:`earth_land_frac`).
``VERSION`` default ``v0.1``; the layer version is ``<slug>-<VERSION>``.
``CROSSWALKS`` file names (next to the module) hashed into code_version and uploaded on publish.
``LIMITATIONS`` list of strings for the manifest and the dataset card.
``validate(summary, ctx)`` -> list of ``(name, ok, detail)``: layer-specific publish checks.
What the driver guarantees
--------------------------
* One file per band group of 100 bands, holding exactly one row per grid cell of the group, in grid
order, with the standard metadata columns (:data:`LEADING_COLUMNS`, :data:`TRAILING_COLUMNS`).
* The cache never holds more than ``--cache-max-gb``: every byte is charged before it is written,
and the cache is wiped after each band group.
* A failed download is never turned into NaNs. Transient errors are retried with exponential
backoff; after ``--retries`` attempts the band group stops and nothing is written for it. Only an
item planned with ``required=False`` may be *absent* (HTTP 404), and the reduce sees that.
* Uploads are one Hub commit per band group per layer, holding the Parquet file and the updated
progress file together, so a crash leaves either both or neither. The local file is deleted only
after the remote copy is re-listed and its size and hash match.
* ``--resume`` skips a band group only when the progress file records it with the current
code_version and the remote file matches the recorded size and hash.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib
import importlib.util
import io
import json
import math
import os
import random
import re
import shutil
import socket
import sys
import tempfile
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import http.client
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable
import numpy as np
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.parquet as pq
LAYERS_DIR = Path(__file__).resolve().parent
PIPELINE_DIR = LAYERS_DIR.parent
ROOT = PIPELINE_DIR.parent
DRIVER_PATH = Path(__file__).resolve()
if str(PIPELINE_DIR) not in sys.path:
sys.path.insert(0, str(PIPELINE_DIR))
import terrain_features as tf # noqa: E402
from catalog import assets as catalog_assets # noqa: E402
from catalog import coverage as catalog_coverage # noqa: E402
from catalog import schema as catalog_schema # noqa: E402
from planetary_grid import PLANETS, VERSION as GRID_VERSION, PlanetBandGrid # noqa: E402
REPO_ID = 'enzeeoai/starman'
REPO_TYPE = 'dataset'
BANDS_PER_GROUP = tf.BANDS_PER_GROUP
DEFAULT_VERSION = 'v0.1'
GB = 10 ** 9
TERRAIN_FEATURE_VERSION = 'terrain-v0.2'
# the terrain-v0.2 releases (docs/contracts.md); pinned so a layer reads the values it was built on
TERRAIN_REVISION = {'mars': 'terrain-mars-v0.3.0', 'earth': 'terrain-earth-v0.2.0'}
TERRAIN_LOCAL = {p: ROOT / 'data' / 'processed' / p / 'terrain' / TERRAIN_FEATURE_VERSION for p in PLANETS}
DEFAULT_OUT = ROOT / 'data' / 'processed' / 'layers'
DEFAULT_LOG_DIR = ROOT / 'logs' / 'layers'
RAW_ROOT = ROOT / 'data' / 'raw'
INTERIM_ROOT = ROOT / 'data' / 'interim'
LEADING_COLUMNS = ('grid_version', 'region_id', 'planet', 'band', 'column')
FLAGS_COLUMN = 'quality_flags'
TRAILING_COLUMNS = ('source_product', 'source_version', 'source_checksum', 'layer', 'layer_version',
'code_version', 'computed_at')
RESERVED_COLUMNS = frozenset(LEADING_COLUMNS) | frozenset(TRAILING_COLUMNS)
DEFAULT_MISSING_FLAG = 'no_source'
COMPARISON_MODES = {
'absolute': 'same quantity and unit on both planets; compare values directly',
'within_planet': 'only meaningful against the same planet (percentiles, ranks, z-scores)',
'categorical': 'class codes; compare through a crosswalk, never numerically',
'planet_specific': 'defined for one planet only; no cross-planet comparison',
}
METHODS = {'http', 'cog', 'earthaccess', 'api', 'local', 'none'}
METHOD_ALIASES = {'range': 'http', 'vsicurl': 'http', 'vsis3': 'http', 's3': 'http', 'https': 'http',
'provider': 'api'}
HTTP_TIMEOUT = 60
CHUNK = 1 << 20
BACKOFF_BASE = 2.0
BACKOFF_MAX = 60.0
WAIT_POLL = 0.5
CONFLICT_RETRIES = 8
EXTRA_FILES_PER_COMMIT = 20
USER_AGENT = 'starman-layers/0.1'
SLEEP = time.sleep # tests replace this to make backoff instant
# --------------------------------------------------------------------------
# errors
# --------------------------------------------------------------------------
class LayerError(Exception):
"""A layer module broke the interface (bad plan, bad table, undeclared column...)."""
class FetchFailed(Exception):
"""An item could not be fetched. The band group stops; nothing is written for it."""
class ItemAbsent(Exception):
"""The source says the item does not exist (HTTP 404/410, missing file).
Raise it from an ``api`` fetcher to report absence. Only ``required=False`` items may be absent.
"""
class CacheCapExceeded(Exception):
"""The fetch cache cannot hold what the layer needs at once under --cache-max-gb."""
class TransientError(Exception):
"""A retryable failure the driver detected itself (truncated body, checksum mismatch)."""
class UploadError(Exception):
"""The Hub copy does not match the local file after a commit."""
class _Aborted(Exception):
"""A speculative prefetch gave way because the cache had no room; not an error."""
# --------------------------------------------------------------------------
# small helpers
# --------------------------------------------------------------------------
def _now() -> str:
return datetime.now(timezone.utc).isoformat(timespec='seconds')
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK), b''):
digest.update(chunk)
return digest.hexdigest()
def git_blob_id(data: bytes) -> str:
"""The id git (and the Hub, for non-LFS files) gives a blob."""
return hashlib.sha1(f'blob {len(data)}\0'.encode() + data).hexdigest()
def git_blob_id_file(path: Path) -> str:
digest = hashlib.sha1(f'blob {Path(path).stat().st_size}\0'.encode())
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(CHUNK), b''):
digest.update(chunk)
return digest.hexdigest()
def du(path: Path) -> int:
path = Path(path)
if not path.exists():
return 0
if path.is_file():
return path.stat().st_size
total = 0
for p in path.rglob('*'):
try:
if p.is_file():
total += p.stat().st_size
except FileNotFoundError: # deleted while we walked
pass
return total
def human(n: float | None) -> str:
if n is None:
return 'n/a'
for unit in ('B', 'KiB', 'MiB', 'GiB', 'TiB'):
if abs(n) < 1024 or unit == 'TiB':
return f'{n:.0f} {unit}' if unit == 'B' else f'{n:.1f} {unit}'
n /= 1024
return f'{n:.1f} TiB'
def _json_default(value):
if isinstance(value, (np.integer,)):
return int(value)
if isinstance(value, (np.floating,)):
return None if not math.isfinite(float(value)) else float(value)
if isinstance(value, np.bool_):
return bool(value)
if isinstance(value, Path):
return str(value)
if isinstance(value, (set, frozenset, tuple)):
return list(value)
return str(value)
def _sanitize(obj):
"""JSON has no NaN: non-finite floats become null, recursively."""
if isinstance(obj, float):
return obj if math.isfinite(obj) else None
if isinstance(obj, dict):
return {k: _sanitize(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple)):
return [_sanitize(v) for v in obj]
return obj
def dumps(obj) -> str:
return json.dumps(_sanitize(obj), indent=2, sort_keys=True, default=_json_default, allow_nan=False)
def _status_code(exc: BaseException) -> int | None:
if isinstance(exc, urllib.error.HTTPError):
return exc.code
for holder in (exc, getattr(exc, 'response', None)):
code = getattr(holder, 'status_code', None)
if isinstance(code, int):
return code
return None
@lru_cache(maxsize=1)
def _transport_error_types() -> tuple:
found = []
for module_name in ('httpx2', 'httpx', 'requests'):
try:
module = importlib.import_module(module_name)
except ImportError:
continue
for name in ('TransportError', 'ConnectionError', 'Timeout', 'TimeoutException'):
cls = getattr(module, name, None)
if isinstance(cls, type) and issubclass(cls, BaseException):
found.append(cls)
return tuple(found)
def is_transient(exc: BaseException) -> bool:
"""Network-shaped failures worth another attempt. 404s, 4xx and layer bugs are not."""
if isinstance(exc, (ItemAbsent, LayerError, CacheCapExceeded, _Aborted, FetchFailed)):
return False
if isinstance(exc, TransientError):
return True
code = _status_code(exc)
if code is not None:
return code in (408, 425, 429) or code >= 500
if isinstance(exc, (urllib.error.URLError, ConnectionError, TimeoutError, socket.timeout,
http.client.HTTPException)):
return True
return bool(_transport_error_types()) and isinstance(exc, _transport_error_types())
def with_retries(fn: Callable[[], Any], attempts: int, what: str,
on_retry: Callable[[int, BaseException, float], None] | None = None):
"""Call ``fn``; retry transient errors with exponential backoff, ``attempts`` tries in all."""
attempts = max(1, int(attempts))
for attempt in range(1, attempts + 1):
try:
return fn()
except Exception as exc:
if attempt >= attempts or not is_transient(exc):
raise
delay = min(BACKOFF_MAX, BACKOFF_BASE * 2 ** (attempt - 1)) * (1 + 0.25 * random.random())
print(f' retry {attempt}/{attempts - 1} {what}: {type(exc).__name__}: {exc} '
f'(waiting {delay:.1f}s)', file=sys.stderr, flush=True)
if on_retry is not None:
on_retry(attempt, exc, delay)
SLEEP(delay)
raise AssertionError('unreachable')
# --------------------------------------------------------------------------
# items
# --------------------------------------------------------------------------
@dataclass
class Item:
"""One source item a band group needs: a tile, granule, file, byte range or raster window.
``key`` unique id, also the dedupe key across layers of one PASS_GROUP.
``url`` http(s)://, file://, s3://bucket/key, /vsis3/bucket/key, /vsicurl/<url>, or a local
path. ``None`` with method ``none`` for a purely virtual item (data in ``meta``).
``method`` inferred from the URL; set ``cog`` for a raster window (``meta['window'] =
(col_off, row_off, width, height)``, optional ``meta['band']``), ``earthaccess``
for a NASA Earthdata granule, ``api`` with ``fetch`` for a provider API.
``size`` expected bytes. Known sizes let items download in parallel inside the cap.
``range`` inclusive byte range (start, end) for an HTTP range request.
``required`` False only when the item may legitimately not exist (404 -> absent). A failed
download stops the band group either way.
``checksum`` expected SHA-256 (hex, optionally ``sha256:`` prefixed), verified after download.
``fetch`` ``fetch(item, out)`` for method ``api``: write bytes with ``out.write`` (each byte is
charged to the cache cap) or save files into ``out.dir`` and call
``out.adopt(path)``; raise :class:`ItemAbsent` for a missing item.
``asset`` optional catalog metadata (uri, footprint, geotransform, time range, ...; see
``catalog/assets.py``). Items that carry it become ``assets`` rows.
"""
key: str
url: str | None = None
method: str | None = None
size: int | None = None
range: tuple[int, int] | None = None
required: bool = True
checksum: str | None = None
headers: dict = field(default_factory=dict)
fetch: Callable | None = None
meta: dict = field(default_factory=dict)
asset: dict | None = None
def resolved_method(self) -> str:
if self.method:
return METHOD_ALIASES.get(self.method, self.method)
if self.fetch is not None:
return 'api'
if self.url is None:
return 'none'
if self.url.startswith(('http://', 'https://', 'file://', 's3://', '/vsis3/', '/vsicurl/')):
return 'http'
return 'local'
def expected_size(self) -> int | None:
if self.size is not None:
return int(self.size)
if self.range is not None:
return int(self.range[1]) - int(self.range[0]) + 1
return None
def source_id(self) -> tuple:
return (self.resolved_method(), self.url, tuple(self.range) if self.range else None)
def describe(self) -> dict:
out = {'key': self.key, 'url': self.url, 'method': self.resolved_method(),
'size': self.size, 'range': list(self.range) if self.range else None,
'checksum': self.checksum}
for name in ('etag', 'version', 'modified'):
if name in self.meta:
out[name] = str(self.meta[name])
return out
@dataclass
class Fetched:
"""An item as the reduce sees it. ``path`` is None for absent and virtual items."""
item: Item
path: Path | None
absent: bool = False
nbytes: int = 0
@property
def key(self) -> str:
return self.item.key
@property
def meta(self) -> dict:
return self.item.meta
def array(self) -> np.ndarray:
"""The window a ``cog`` item read, as saved by the driver."""
if self.path is None:
raise LayerError(f'{self.key}: no data (absent or virtual item)')
return np.load(self.path, allow_pickle=False)
def read_bytes(self) -> bytes:
if self.path is None:
raise LayerError(f'{self.key}: no data (absent or virtual item)')
return Path(self.path).read_bytes()
def normalize_items(planned, slug: str) -> list[Item]:
if planned is None:
raise LayerError(f'{slug}.plan returned None; return [] for "no source data"')
items = []
for raw in planned:
if isinstance(raw, Item):
item = raw
elif isinstance(raw, dict):
try:
item = Item(**raw)
except TypeError as exc:
raise LayerError(f'{slug}.plan: bad item {raw!r}: {exc}') from exc
elif isinstance(raw, str):
item = Item(key=raw, url=raw)
else:
raise LayerError(f'{slug}.plan: items must be Item, dict or URL string, got {type(raw).__name__}')
method = item.resolved_method()
if method not in METHODS:
raise LayerError(f'{slug}.plan: item {item.key!r} has unknown method {item.method!r}')
if item.asset is not None and not isinstance(item.asset, dict):
raise LayerError(f'{slug}.plan: item {item.key!r}: asset must be a dict')
if method == 'api' and not callable(item.fetch):
raise LayerError(f'{slug}.plan: api item {item.key!r} needs a fetch callable')
if method == 'cog' and 'window' not in item.meta:
raise LayerError(f"{slug}.plan: cog item {item.key!r} needs meta['window']")
if item.range is not None:
start, end = (int(v) for v in item.range)
if start < 0 or end < start:
raise LayerError(f'{slug}.plan: item {item.key!r} has bad range {item.range!r}')
items.append(item)
keys = [i.key for i in items]
if len(set(keys)) != len(keys):
dupes = sorted({k for k in keys if keys.count(k) > 1})
raise LayerError(f'{slug}.plan: duplicate item keys {dupes[:5]}')
return items
def items_checksum(items: list[Item]) -> str:
blob = json.dumps(sorted((i.describe() for i in items), key=lambda d: d['key']), sort_keys=True)
return 'items-sha256:' + hashlib.sha256(blob.encode()).hexdigest()
# --------------------------------------------------------------------------
# transports: each writes through a _CacheWriter so the cap is enforced per byte
# --------------------------------------------------------------------------
def http_url(url: str) -> str:
"""Map GDAL-style and s3:// paths to a plain URL (anonymous S3 over HTTPS)."""
for prefix in ('/vsis3/', 's3://'):
if url.startswith(prefix):
bucket, _, key = url[len(prefix):].partition('/')
return f'https://{bucket}.s3.amazonaws.com/{urllib.parse.quote(key)}'
if url.startswith('/vsicurl/'):
return url[len('/vsicurl/'):]
return url
def gdal_path(url: str) -> str:
if url.startswith(('http://', 'https://')):
return '/vsicurl/' + url
if url.startswith('s3://'):
return '/vsis3/' + url[len('s3://'):]
if url.startswith('file://'):
return urllib.request.url2pathname(urllib.parse.urlparse(url).path)
return url
def fetch_http(item: Item, out: '_CacheWriter') -> None:
url = http_url(item.url)
if url.startswith('file://'):
path = Path(urllib.request.url2pathname(urllib.parse.urlparse(url).path))
if not path.exists():
raise ItemAbsent(f'{url}: no such file')
with open(path, 'rb') as f:
if item.range:
f.seek(int(item.range[0]))
remaining = int(item.range[1]) - int(item.range[0]) + 1
else:
remaining = None
while remaining is None or remaining > 0:
chunk = f.read(CHUNK if remaining is None else min(CHUNK, remaining))
if not chunk:
break
out.write(chunk)
if remaining is not None:
remaining -= len(chunk)
return
headers = {'User-Agent': USER_AGENT, **item.headers}
if item.range:
headers['Range'] = f'bytes={int(item.range[0])}-{int(item.range[1])}'
request = urllib.request.Request(url, headers=headers)
try:
response = urllib.request.urlopen(request, timeout=HTTP_TIMEOUT)
except urllib.error.HTTPError as exc:
if exc.code in (404, 410):
raise ItemAbsent(f'{url}: HTTP {exc.code}') from exc
raise
with response:
status = getattr(response, 'status', None)
if item.range and status != 206:
raise FetchFailed(f'{url}: server answered {status} to a Range request')
expected = response.headers.get('Content-Length')
received = 0
while True:
chunk = response.read(CHUNK)
if not chunk:
break
out.write(chunk)
received += len(chunk)
if expected is not None and int(expected) != received:
raise TransientError(f'{url}: received {received} of {expected} bytes')
def fetch_cog(item: Item, out: '_CacheWriter') -> None:
"""Read one window of a (cloud-optimized) raster and store it as .npy."""
try:
import rasterio
from rasterio.errors import RasterioIOError
from rasterio.windows import Window
except ImportError as exc: # pragma: no cover - rasterio is in the venv
raise FetchFailed('method "cog" needs rasterio') from exc
window = Window(*item.meta['window'])
band = int(item.meta.get('band', 1))
try:
with rasterio.Env(**item.meta.get('gdal_env', {})):
with rasterio.open(gdal_path(item.url)) as src:
array = src.read(band, window=window, boundless=bool(item.meta.get('boundless', False)))
except RasterioIOError as exc:
text = str(exc)
if any(s in text for s in ('No such file', 'does not exist', 'HTTP response code: 404', '404')):
raise ItemAbsent(f'{item.url}: {text}') from exc
raise TransientError(f'{item.url}: {text}') from exc
buffer = io.BytesIO()
np.save(buffer, array, allow_pickle=False)
out.name = 'window.npy'
out.write(buffer.getvalue())
_EARTHACCESS_LOCK = threading.Lock()
_EARTHACCESS_READY = False
def fetch_earthaccess(item: Item, out: '_CacheWriter') -> None:
"""Download one Earthdata granule (``meta['granule']`` or the URL) into the item's cache folder."""
global _EARTHACCESS_READY
try:
import earthaccess
except ImportError as exc:
raise FetchFailed('method "earthaccess" needs `pip install earthaccess`') from exc
with _EARTHACCESS_LOCK:
if not _EARTHACCESS_READY:
for strategy in ('environment', 'netrc'):
try:
if earthaccess.login(strategy=strategy):
_EARTHACCESS_READY = True
break
except Exception:
continue
if not _EARTHACCESS_READY:
raise FetchFailed('earthaccess login failed: set EARTHDATA_USERNAME/PASSWORD or ~/.netrc')
if item.size is None:
print(f' note: earthaccess item {item.key} has no size; the cap is checked after it lands',
file=sys.stderr, flush=True)
files = earthaccess.download([item.meta.get('granule') or item.url], str(out.dir))
if not files:
raise TransientError(f'{item.key}: earthaccess downloaded nothing')
for name in files:
out.adopt(Path(name))
# --------------------------------------------------------------------------
# the per-band-group cache
# --------------------------------------------------------------------------
class _Entry:
__slots__ = ('item', 'seq', 'state', 'path', 'dir', 'nbytes', 'reserved', 'refs', 'claimed',
'error', 'fetcher_consumer', 'fetch_count', 'was_absent')
def __init__(self, item: Item, seq: int):
self.item = item
self.seq = seq
self.state = 'pending' # pending | fetching | ready | absent | failed | done
self.path: Path | None = None
self.dir: Path | None = None
self.nbytes = 0 # bytes on disk, charged to cache.used
self.reserved = 0 # bytes reserved up front for an item of known size
self.refs: set[str] = set() # consumers (layers) still needing it
self.claimed = False # a consumer has acquired it (otherwise speculative)
self.error: BaseException | None = None
self.fetcher_consumer = False
self.fetch_count = 0
self.was_absent = False
class _CacheWriter:
"""The sink a fetcher writes into. Every byte is charged to the cap before it reaches disk."""
def __init__(self, cache: 'GroupCache', entry: _Entry, blocking: bool):
self._cache = cache
self._entry = entry
self._blocking = blocking
self.dir: Path = entry.dir
self.name = self._default_name(entry.item)
self._fh = None
self._hash = hashlib.sha256()
self.nbytes = 0
self._adopted: list[Path] = []
@staticmethod
def _default_name(item: Item) -> str:
if 'filename' in item.meta:
return str(item.meta['filename'])
if item.url:
base = Path(urllib.parse.urlparse(http_url(item.url)).path).name
if base:
return base
return re.sub(r'[^A-Za-z0-9._-]+', '_', item.key)[:120] or 'data'
def write(self, data: bytes) -> int:
if not data:
return 0
self._cache._charge(self._entry, len(data), self._blocking)
if self._fh is None:
self._fh = open(self.dir / self.name, 'wb')
self._fh.write(data)
self._hash.update(data)
self.nbytes += len(data)
return len(data)
def adopt(self, path: Path) -> None:
"""Account for a file the fetcher saved into ``self.dir`` itself."""
path = Path(path)
size = path.stat().st_size
try:
self._cache._charge(self._entry, size, self._blocking)
except BaseException:
path.unlink(missing_ok=True)
raise
self._adopted.append(path)
def close(self) -> None:
if self._fh is not None:
self._fh.close()
self._fh = None
def verify(self, expected: str | None) -> None:
if not expected:
return
want = expected.split(':', 1)[1] if expected.startswith('sha256:') else expected
if self._adopted:
got = sha256_file(self._adopted[0]) if len(self._adopted) == 1 else None
else:
got = self._hash.hexdigest()
if got is not None and got != want.lower():
raise TransientError(f'{self._entry.item.key}: SHA-256 {got} != expected {want}')
def result(self) -> Path:
if self._adopted:
return self._adopted[0] if len(self._adopted) == 1 else self.dir
path = self.dir / self.name
if not path.exists():
path.touch()
return path
class GroupCache:
"""Items of one band group, on disk under ``root``, never more than ``cap`` bytes in total.
Several consumers (the layers of one PASS_GROUP) may need the same item; it is fetched once and
deleted when the last of them releases it. A consumer that needs room waits while another
consumer can still free some, and fails with :class:`CacheCapExceeded` when nobody can.
Prefetches (``workers - 1`` threads) only use room that is free and never wait for it; an
unclaimed prefetched item is evicted first when a consumer needs the space.
"""
def __init__(self, root: Path, cap_bytes: int, *, retries: int, workers: int = 1):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.cap = int(cap_bytes)
self.retries = max(1, int(retries))
self.cond = threading.Condition()
self.entries: dict[str, _Entry] = {}
self.used = 0
self.reserved = 0
self.peak = 0
self.bytes_read = 0
self.retried = 0
self.alive = 0
self.blocked = 0
self.prefetching = 0
self.depth = max(0, int(workers) - 1)
self.pool = (ThreadPoolExecutor(max_workers=self.depth, thread_name_prefix='layer-prefetch')
if self.depth else None)
# -- registration ------------------------------------------------------
def register(self, consumer: str, items: list[Item]) -> None:
with self.cond:
for item in items:
entry = self.entries.get(item.key)
if entry is None:
entry = self.entries[item.key] = _Entry(item, len(self.entries))
elif entry.item.source_id() != item.source_id():
raise LayerError(f'item {item.key!r} is planned with two different sources: '
f'{entry.item.source_id()} and {item.source_id()}')
elif item.required and not entry.item.required:
entry.item = replace(entry.item, required=True)
entry.refs.add(consumer)
def add_consumers(self, n: int) -> None:
with self.cond:
self.alive += n
def finish(self, consumer: str) -> None:
"""A consumer is done: drop its claim on everything it planned."""
with self.cond:
self.alive -= 1
for entry in self.entries.values():
if consumer in entry.refs:
entry.refs.discard(consumer)
if not entry.refs:
self._drop(entry)
self.cond.notify_all()
# -- consumer API ------------------------------------------------------
def acquire(self, consumer: str, key: str) -> Fetched:
with self.cond:
entry = self.entries.get(key)
if entry is None:
raise LayerError(f'item {key!r} was not in the plan')
entry.refs.add(consumer)
while True:
with self.cond:
while True:
if entry.state in ('ready', 'absent'):
entry.claimed = True
return Fetched(entry.item, entry.path, absent=entry.state == 'absent',
nbytes=entry.nbytes)
if entry.state == 'failed':
raise entry.error
if entry.state == 'fetching':
counted = entry.fetcher_consumer
if counted:
self.blocked += 1
self.cond.wait(WAIT_POLL)
if counted:
self.blocked -= 1
continue
# pending, or done and wanted again: fetch it in this thread
entry.state = 'fetching'
entry.fetcher_consumer = True
break
self._fetch(entry, blocking=True)
def release(self, consumer: str, key: str) -> None:
with self.cond:
entry = self.entries.get(key)
if entry is None:
return
entry.refs.discard(consumer)
if not entry.refs:
self._drop(entry)
self.cond.notify_all()
def prefetch(self, keys: list[str]) -> None:
if self.pool is None:
return
with self.cond:
for key in keys:
if self.prefetching >= self.depth:
break
entry = self.entries.get(key)
if entry is None or entry.state != 'pending' or not entry.refs:
continue
entry.state = 'fetching'
entry.fetcher_consumer = False
self.prefetching += 1
self.pool.submit(self._prefetch_task, entry)
def _prefetch_task(self, entry: _Entry) -> None:
try:
self._fetch(entry, blocking=False)
finally:
with self.cond:
self.prefetching -= 1
self.cond.notify_all()
# -- accounting (lock held) ------------------------------------------
def _make_room(self, n: int, blocking: bool, entry: _Entry) -> None:
while self.used + self.reserved + n > self.cap:
if self._evict_one(exclude=entry):
continue
if not blocking:
raise _Aborted()
if entry.nbytes + entry.reserved + n > self.cap:
raise CacheCapExceeded(
f'item {entry.item.key!r} needs more than the whole cache cap '
f'({human(self.cap)}); raise --cache-max-gb or split the item')
others = self.alive - self.blocked - 1
if others <= 0 and self.prefetching == 0:
raise CacheCapExceeded(
f'cache cap {human(self.cap)} is full ({human(self.used)} held by items still '
f'in use) and {entry.item.key!r} needs {human(n)} more; the layer keeps too much '
f'at once (stream items instead of items.all()) or --cache-max-gb is too small')
self.blocked += 1
self.cond.wait(WAIT_POLL)
self.blocked -= 1
def _charge(self, entry: _Entry, n: int, blocking: bool) -> None:
with self.cond:
take = min(n, entry.reserved)
entry.reserved -= take
self.reserved -= take
self.used += take
entry.nbytes += take
rest = n - take
if rest:
self._make_room(rest, blocking, entry)
self.used += rest
entry.nbytes += rest
self.bytes_read += n
self.peak = max(self.peak, self.used)
def _evict_one(self, exclude: _Entry) -> bool:
candidates = [e for e in self.entries.values()
if e is not exclude and e.state == 'ready' and not e.claimed]
if not candidates:
return False
victim = max(candidates, key=lambda e: e.seq) # the one needed last
self._delete_files(victim)
victim.state = 'pending'
return True
def _delete_files(self, entry: _Entry) -> None:
if entry.dir is not None:
shutil.rmtree(entry.dir, ignore_errors=True)
self.used -= entry.nbytes
entry.nbytes = 0
entry.dir = None
if entry.path is not None and entry.item.resolved_method() != 'local':
entry.path = None
def _free_reservation(self, entry: _Entry) -> None:
self.reserved -= entry.reserved
entry.reserved = 0
def _drop(self, entry: _Entry) -> None:
if entry.state in ('ready', 'absent', 'pending'):
self._delete_files(entry)
entry.path = None
entry.claimed = False
entry.state = 'done'
# 'fetching': the fetcher drops it when it finishes; 'failed' keeps its error
# -- fetching ----------------------------------------------------------
def _fetch(self, entry: _Entry, blocking: bool) -> None:
item = entry.item
try:
size = item.expected_size()
if size:
with self.cond:
self._make_room(size, blocking, entry)
self.reserved += size
entry.reserved = size
path = with_retries(lambda: self._fetch_once(entry, blocking), self.retries,
f'fetch {item.key}', on_retry=self._on_retry)
except _Aborted:
with self.cond:
self._delete_files(entry)
self._free_reservation(entry)
entry.state = 'pending'
self.cond.notify_all()
return
except ItemAbsent as exc:
with self.cond:
self._delete_files(entry)
self._free_reservation(entry)
entry.fetch_count += 1
if item.required:
entry.state = 'failed'
entry.error = FetchFailed(f'required item {item.key!r} does not exist at its '
f'source ({exc}); mark it required=False if absence '
f'is legitimate')
else:
entry.state = 'absent'
entry.was_absent = True
if blocking:
entry.claimed = True
self.cond.notify_all()
return
except Exception as exc:
with self.cond:
self._delete_files(entry)
self._free_reservation(entry)
entry.state = 'failed'
if isinstance(exc, (FetchFailed, CacheCapExceeded, LayerError)):
entry.error = exc
else:
entry.error = FetchFailed(f'item {item.key!r} failed after {self.retries} '
f'attempt(s): {type(exc).__name__}: {exc}')
entry.error.__cause__ = exc
self.cond.notify_all()
return
with self.cond:
self._free_reservation(entry)
entry.path = path
entry.state = 'ready'
entry.fetch_count += 1
if blocking:
entry.claimed = True
if not entry.refs:
self._drop(entry)
self.cond.notify_all()
def _on_retry(self, attempt, exc, delay) -> None:
with self.cond:
self.retried += 1
def _fetch_once(self, entry: _Entry, blocking: bool) -> Path | None:
item = entry.item
method = item.resolved_method()
if method == 'none':
return None
if method == 'local':
path = Path(item.url)
if not path.exists():
raise ItemAbsent(f'{path}: no such file')
return path
with self.cond:
self._delete_files(entry) # a previous attempt's partial download
entry.dir = self.root / f'{entry.seq:06d}'
entry.dir.mkdir(parents=True, exist_ok=True)
out = _CacheWriter(self, entry, blocking)
try:
if method == 'http':
fetch_http(item, out)
elif method == 'cog':
fetch_cog(item, out)
elif method == 'earthaccess':
fetch_earthaccess(item, out)
elif method == 'api':
item.fetch(item, out)
else: # pragma: no cover - normalize_items rejects it
raise LayerError(f'unknown method {method!r}')
finally:
out.close()
out.verify(item.checksum)
return out.result()
# -- teardown ----------------------------------------------------------
def stats(self) -> dict:
with self.cond:
entries = list(self.entries.values())
return {
'items': len(entries),
'items_fetched': sum(1 for e in entries if e.fetch_count and e.state != 'failed'),
'items_absent': sum(1 for e in entries if e.was_absent),
'items_failed': sum(1 for e in entries if e.state == 'failed'),
'fetches': sum(e.fetch_count for e in entries),
'refetches': sum(max(0, e.fetch_count - 1) for e in entries),
'bytes_read': self.bytes_read,
'peak_cache_bytes': self.peak,
'cache_cap_bytes': self.cap,
'retried': self.retried,
}
def close(self) -> int:
"""Stop prefetching and wipe the folder. Returns the bytes that were still on disk."""
if self.pool is not None:
self.pool.shutdown(wait=True, cancel_futures=True)
left = du(self.root)
shutil.rmtree(self.root, ignore_errors=True)
return left
class Items:
"""What ``reduce`` receives: the planned items of one band group, fetched on demand.
Iterating fetches each item when the loop reaches it (with up to ``--workers - 1`` of the next
ones downloading meanwhile) and deletes it when the loop asks for the next one, so a reduce that
streams never holds more than a few items. ``get(key)`` fetches one item and keeps it until
``release(key)``; ``all()`` keeps every item and fails when they do not fit under the cap.
"""
def __init__(self, cache: GroupCache, consumer: str, planned: list[Item]):
self._cache = cache
self._consumer = consumer
self.planned = list(planned)
self._keys = [i.key for i in self.planned]
self._kept: set[str] = set()
self.failed: list[str] = []
self.absent: list[str] = []
def __len__(self) -> int:
return len(self.planned)
def keys(self) -> list[str]:
return list(self._keys)
def _acquire(self, key: str) -> Fetched:
try:
fetched = self._cache.acquire(self._consumer, key)
except Exception:
self.failed.append(key)
raise
if fetched.absent:
self.absent.append(key)
return fetched
def __iter__(self):
depth = self._cache.depth
self._cache.prefetch(self._keys[:depth])
previous = None
for i, key in enumerate(self._keys):
if previous is not None and previous not in self._kept:
self._cache.release(self._consumer, previous)
fetched = self._acquire(key)
self._cache.prefetch(self._keys[i + 1:i + 1 + depth])
previous = key
yield fetched
if previous is not None and previous not in self._kept:
self._cache.release(self._consumer, previous)
def get(self, key: str) -> Fetched:
fetched = self._acquire(key)
self._kept.add(key)
return fetched
def release(self, key: str) -> None:
self._kept.discard(key)
self._cache.release(self._consumer, key)
def all(self) -> list[Fetched]:
self._cache.prefetch(self._keys)
return [self.get(key) for key in self._keys]
# --------------------------------------------------------------------------
# grid helpers
# --------------------------------------------------------------------------
@lru_cache(maxsize=None)
def _build_grid(planet: str) -> PlanetBandGrid:
return PlanetBandGrid.build(planet)
def planet_grid(planet: str) -> PlanetBandGrid:
"""The latband5km-v1 grid for a planet (tests replace this with a small grid)."""
return _build_grid(planet)
def n_groups(grid: PlanetBandGrid) -> int:
return math.ceil(len(grid.column_counts) / BANDS_PER_GROUP)
def group_bands(grid: PlanetBandGrid, group: int) -> list[int]:
n_bands = len(grid.column_counts)
if not 0 <= group < n_groups(grid):
raise ValueError(f'band group {group} outside 0-{n_groups(grid) - 1}')
return list(range(group * BANDS_PER_GROUP, min((group + 1) * BANDS_PER_GROUP, n_bands)))
def group_cell_count(grid: PlanetBandGrid, group: int) -> int:
bands = group_bands(grid, group)
return int(np.sum(grid.column_counts[bands[0]:bands[-1] + 1], dtype=np.int64))
_CELLS_CACHE: dict = {}
_CELLS_LOCK = threading.Lock()
def cells_table(planet: str, group: int) -> pa.Table:
"""Every cell of a band group in grid order, with the same values ``PlanetBandGrid.cell`` gives."""
grid = planet_grid(planet)
key = (planet, group, len(grid.column_counts), grid.number_of_cells, float(grid.edges_deg[1]))
with _CELLS_LOCK:
if key in _CELLS_CACHE:
return _CELLS_CACHE[key]
bands = np.asarray(group_bands(grid, group), dtype=np.int64)
counts = grid.column_counts[bands].astype(np.int64)
band = np.repeat(bands, counts)
column = np.concatenate([np.arange(c, dtype=np.int64) for c in counts])
width = np.repeat(360.0 / counts, counts)
lat_min = grid.edges_deg[band]
lat_max = grid.edges_deg[band + 1]
lon_min = -180 + width * column
lon_max = -180 + width * (column + 1)
area = np.repeat(grid.strip_area_m2()[bands] / counts / 1e6, counts)
prefix = PLANETS[planet]['prefix']
region_id = [f'{prefix}_{b:04d}_{c:05d}' for b, c in zip(band.tolist(), column.tolist())]
table = pa.table({
'region_id': pa.array(region_id, type=pa.string()),
'band': pa.array(band.astype(np.int32)),
'column': pa.array(column.astype(np.int32)),
'lat_min': lat_min, 'lat_max': lat_max, 'lon_min': lon_min, 'lon_max': lon_max,
'center_lat': (lat_min + lat_max) / 2, 'center_lon': (lon_min + lon_max) / 2,
'area_km2': area,
})
with _CELLS_LOCK:
if len(_CELLS_CACHE) > 8:
_CELLS_CACHE.clear()
_CELLS_CACHE[key] = table
return table
def groups_for_bands(grid: PlanetBandGrid, bands: list[int] | None) -> list[int]:
if bands is None:
return list(range(n_groups(grid)))
groups = sorted({b // BANDS_PER_GROUP for b in bands})
wanted = set(bands)
partial = [g for g in groups if not set(group_bands(grid, g)) <= wanted]
if partial:
print(f'note: --bands covers only part of band group(s) {partial}; a band-group file always '
f'holds the whole group, so those groups run in full', flush=True)
return groups
# --------------------------------------------------------------------------
# the Hub
# --------------------------------------------------------------------------
@dataclass
class RemoteFile:
path: str
size: int
sha256: str | None # LFS files
blob_id: str | None # git blob id; the content hash for non-LFS files
def matches(self, size: int, sha256: str, blob_id: str | None) -> bool:
if self.size != size:
return False
if self.sha256:
return self.sha256 == sha256
return blob_id is not None and self.blob_id == blob_id
def _not_found(exc: BaseException) -> bool:
try:
from huggingface_hub.errors import EntryNotFoundError
if isinstance(exc, EntryNotFoundError):
return True
except ImportError: # pragma: no cover
pass
return isinstance(exc, FileNotFoundError) or _status_code(exc) == 404
def _is_conflict(exc: BaseException) -> bool:
return _status_code(exc) in (409, 412)
class HubStore:
"""The few Hub operations the driver uses, each retried on transient errors."""
def __init__(self, api=None, repo_id: str = REPO_ID, repo_type: str = REPO_TYPE, retries: int = 4):
if api is None:
from huggingface_hub import HfApi
api = HfApi()
self.api = api
self.repo_id = repo_id
self.repo_type = repo_type
self.retries = max(1, int(retries))
def _call(self, fn, what):
return with_retries(fn, self.retries, f'hub {what}')
def head(self) -> str:
return self._call(lambda: self.api.repo_info(self.repo_id, repo_type=self.repo_type).sha,
'repo_info')
@staticmethod
def _remote(entry) -> RemoteFile | None:
size = getattr(entry, 'size', None)
blob = getattr(entry, 'blob_id', None)
if size is None or blob is None:
return None # a folder
lfs = getattr(entry, 'lfs', None)
return RemoteFile(entry.path, int(size), getattr(lfs, 'sha256', None) if lfs else None, blob)
def list(self, prefix: str, revision: str | None = None) -> dict[str, RemoteFile]:
try:
entries = self._call(lambda: list(self.api.list_repo_tree(
self.repo_id, path_in_repo=prefix, recursive=True, repo_type=self.repo_type,
revision=revision)), f'list {prefix}')
except Exception as exc:
if _not_found(exc):
return {}
raise
out = {}
for entry in entries:
remote = self._remote(entry)
if remote is not None:
out[remote.path] = remote
return out
def info(self, paths: list[str], revision: str | None = None) -> dict[str, RemoteFile]:
try:
entries = self._call(lambda: self.api.get_paths_info(
self.repo_id, list(paths), repo_type=self.repo_type, revision=revision),
'paths_info')
except Exception as exc:
if _not_found(exc):
return {}
raise
out = {}
for entry in entries:
remote = self._remote(entry)
if remote is not None:
out[remote.path] = remote
return out
def read_bytes(self, path: str, revision: str | None = None) -> bytes | None:
with tempfile.TemporaryDirectory(prefix='layer-hub-') as tmp:
try:
local = self._call(lambda: self.api.hf_hub_download(
self.repo_id, path, repo_type=self.repo_type, revision=revision, local_dir=tmp),
f'download {path}')
except Exception as exc:
if _not_found(exc):
return None
raise
return Path(local).read_bytes()
def read_json(self, path: str, revision: str | None = None) -> dict | None:
data = self.read_bytes(path, revision)
return None if data is None else json.loads(data)
def read_parquet(self, path: str, columns=None, revision: str | None = None) -> pa.Table | None:
with tempfile.TemporaryDirectory(prefix='layer-hub-') as tmp:
try:
local = self._call(lambda: self.api.hf_hub_download(
self.repo_id, path, repo_type=self.repo_type, revision=revision, local_dir=tmp),
f'download {path}')
except Exception as exc:
if _not_found(exc):
return None
raise
return pq.read_table(local, columns=columns)
def cached_download(self, path: str, revision: str) -> Path:
"""Download into the normal Hub cache (for pinned, reused files like the terrain tables)."""
return Path(self._call(lambda: self.api.hf_hub_download(
self.repo_id, path, repo_type=self.repo_type, revision=revision), f'download {path}'))
def commit(self, files: dict[str, Path | bytes], message: str, parent_commit: str | None) -> str:
from huggingface_hub import CommitOperationAdd
def attempt():
operations = [CommitOperationAdd(path_in_repo=p,
path_or_fileobj=str(v) if isinstance(v, Path) else v)
for p, v in files.items()]
return self.api.create_commit(self.repo_id, operations=operations, commit_message=message,
repo_type=self.repo_type, parent_commit=parent_commit)
return self._call(attempt, 'create_commit').oid
def commit_update(self, files: dict[str, Path | bytes], message: str, progress_path: str,
mutate: Callable[[dict | None], dict],
already_done: Callable[[dict | None, str], bool] | None = None) -> tuple[str, dict]:
"""Commit ``files`` plus a read-modify-write of the progress JSON, atomically.
The commit names its parent, so a concurrent commit makes it fail instead of overwriting
someone else's progress; it is then redone on the new head. ``already_done`` lets a retry
recognise that an earlier attempt landed after all (e.g. a timeout after the server acted).
"""
for _ in range(CONFLICT_RETRIES):
head = self.head()
progress = self.read_json(progress_path, revision=head)
if already_done is not None and already_done(progress, head):
return head, progress
progress = mutate(progress)
payload = dict(files)
payload[progress_path] = (dumps(progress) + '\n').encode()
try:
return self.commit(payload, message, parent_commit=head), progress
except Exception as exc:
if _is_conflict(exc):
continue
raise
raise UploadError(f'gave up after {CONFLICT_RETRIES} commit conflicts on {self.repo_id}')
def tags(self) -> set[str]:
refs = self._call(lambda: self.api.list_repo_refs(self.repo_id, repo_type=self.repo_type),
'list_repo_refs')
return {t.name for t in refs.tags}
def create_tag(self, tag: str, revision: str, message: str) -> None:
# never retried: a retry after a lost response must not turn into "tag already exists" noise,
# and exist_ok=False means a tag is never moved
self.api.create_tag(self.repo_id, tag=tag, revision=revision, repo_type=self.repo_type,
exist_ok=False, tag_message=message)
_DEFAULT_HUB: HubStore | None = None
def default_hub() -> HubStore:
global _DEFAULT_HUB
if _DEFAULT_HUB is None:
_DEFAULT_HUB = HubStore()
return _DEFAULT_HUB
# --------------------------------------------------------------------------
# shared inputs for layers: terrain values and the Earth land mask
# --------------------------------------------------------------------------
def terrain_remote_path(planet: str, band_group: int) -> str:
return (f'terrain/planet={planet}/feature_version={TERRAIN_FEATURE_VERSION}/'
f'band_group={band_group:03d}.parquet')
def read_terrain(planet: str, band_group: int, columns) -> pa.Table:
"""terrain-v0.2 columns (plus ``region_id``) for one band group, in grid order.
Reads ``data/processed/<planet>/terrain/terrain-v0.2/band_group=NNN.parquet`` when it is on
disk, otherwise the Hub copy at the pinned terrain release tag (kept in the Hub cache).
"""
wanted = list(dict.fromkeys(['region_id', *columns]))
local = TERRAIN_LOCAL[planet] / f'band_group={band_group:03d}.parquet'
if local.exists():
return pq.read_table(local, columns=wanted)
path = default_hub().cached_download(terrain_remote_path(planet, band_group),
revision=TERRAIN_REVISION[planet])
return pq.read_table(path, columns=wanted)
_LAND_CACHE: dict = {}
_LAND_LOCK = threading.Lock()
def earth_land_frac(band_group: int) -> pa.Table:
"""The shared Earth land mask: ``region_id``, ``land_frac`` (0-1) for one band group.
It is the Earth terrain ``valid_frac_200m``: the share of 200 m samples with Copernicus GLO-30
data. Cells with no tile (open ocean) and cells with no samples are 0. Inland water and the sea
pixels inside a coastal GLO-30 tile carry elevation, so they count as land here; layers that need
a water-aware mask should say so in LIMITATIONS rather than build their own.
"""
with _LAND_LOCK:
if band_group in _LAND_CACHE:
return _LAND_CACHE[band_group]
terrain = read_terrain('earth', band_group, ['valid_frac_200m'])
frac = terrain['valid_frac_200m'].to_numpy(zero_copy_only=False).astype(np.float32)
frac = np.where(np.isfinite(frac), frac, np.float32(0))
table = pa.table({'region_id': terrain['region_id'], 'land_frac': pa.array(frac)})
with _LAND_LOCK:
if len(_LAND_CACHE) > 4:
_LAND_CACHE.clear()
_LAND_CACHE[band_group] = table
return table
# --------------------------------------------------------------------------
# layers
# --------------------------------------------------------------------------
def _normalize_columns(spec, where: str) -> dict[str, dict]:
if not isinstance(spec, dict) or not spec:
raise LayerError(f'{where} must be a non-empty dict of column -> definition')
out = {}
for name, definition in spec.items():
if name in RESERVED_COLUMNS or name == FLAGS_COLUMN:
raise LayerError(f'{where}: {name!r} is a driver column and cannot be a feature')
definition = dict(definition or {})
dtype = definition.setdefault('dtype', 'float32')
try:
definition['_type'] = pa.type_for_alias(dtype)
except (ValueError, KeyError) as exc:
raise LayerError(f'{where}: column {name!r} has unknown dtype {dtype!r}') from exc
out[name] = definition
return out
class Layer:
"""A loaded layer module plus everything derived from it."""
def __init__(self, module, slug: str):
self.module = module
self.slug = slug
source = getattr(module, 'SOURCE', None)
if not isinstance(source, dict):
raise LayerError(f'{slug}: SOURCE dict is missing')
missing = [k for k in ('product', 'version', 'url', 'licence', 'planet') if k not in source]
if missing:
raise LayerError(f'{slug}: SOURCE lacks {missing}')
if source['planet'] not in ('mars', 'earth', 'both'):
raise LayerError(f"{slug}: SOURCE['planet'] must be mars, earth or both")
self.source = source
self.planets = ('mars', 'earth') if source['planet'] == 'both' else (source['planet'],)
for name in ('plan', 'reduce'):
if not callable(getattr(module, name, None)):
raise LayerError(f'{slug}: {name}() is missing')
self.columns = _normalize_columns(getattr(module, 'COLUMNS', None), f'{slug}.COLUMNS')
extras = getattr(module, 'EXTRA_COLUMNS', None) or {}
self.extra_columns = {name: _normalize_columns(spec, f'{slug}.EXTRA_COLUMNS[{name!r}]')
for name, spec in extras.items()}
self.has_finalize = callable(getattr(module, 'finalize', None))
if self.has_finalize and not self.extra_columns:
raise LayerError(f'{slug}: finalize() needs EXTRA_COLUMNS naming the sets it writes')
self.pass_group = getattr(module, 'PASS_GROUP', None)
self.version = getattr(module, 'VERSION', DEFAULT_VERSION)
self.layer_version = f'{slug}-{self.version}'
self.path = Path(module.__file__).resolve()
self.crosswalks = [self.path.parent / name for name in getattr(module, 'CROSSWALKS', [])]
for path in self.crosswalks:
if not path.exists():
raise LayerError(f'{slug}: crosswalk {path} does not exist')
# the module, then the driver, then crosswalks: any change to what makes the rows moves it
self.code_version = tf.code_version(self.path, DRIVER_PATH, *self.crosswalks)
def tag(self, planet: str) -> str:
return f'{self.slug}-{planet}-{self.version}.0'
def remote_prefix(self, planet: str) -> str:
return f'layers/planet={planet}/layer={self.slug}/version={self.layer_version}'
def relative_group_path(self, planet: str, group: int, extra: str | None = None) -> str:
middle = f'/extra={extra}' if extra else ''
return f'{self.remote_prefix(planet)}{middle}/band_group={group:03d}.parquet'
def progress_path(self, planet: str) -> str:
return f'manifests/progress/{self.slug}_{planet}.json'
def manifest_path(self, planet: str) -> str:
return f'manifests/{self.slug}_{planet}_{self.version}.json'
def missing_flag(self):
return getattr(self.module, 'MISSING_FLAG', DEFAULT_MISSING_FLAG)
def load_module(slug: str, layers_dir: Path = LAYERS_DIR):
if not re.fullmatch(r'[a-z0-9_]+', slug):
raise LayerError(f'bad layer slug {slug!r} (lowercase letters, digits, underscores)')
if Path(layers_dir).resolve() == LAYERS_DIR and __package__:
return importlib.import_module(f'{__package__}.{slug}')
path = Path(layers_dir) / f'{slug}.py'
if not path.exists():
raise LayerError(f'no layer module {path}')
spec = importlib.util.spec_from_file_location(f'layer_{slug}', path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# --------------------------------------------------------------------------
# table assembly: one row per cell, metadata columns, validation summary
# --------------------------------------------------------------------------
def _constant(value: str, length: int) -> pa.Array:
return pa.DictionaryArray.from_arrays(pa.array(np.zeros(length, dtype=np.int32)),
pa.array([value], type=pa.string()))
def _column_stats(values) -> dict:
out = {'dtype': str(values.type), 'n_null': int(values.null_count)}
if pa.types.is_floating(values.type):
array = values.to_numpy(zero_copy_only=False).astype(np.float64)
finite = np.isfinite(array)
out['n_nan'] = int((~finite).sum())
out['n_finite'] = int(finite.sum())
if finite.any():
out.update(min=float(array[finite].min()), max=float(array[finite].max()),
sum=float(array[finite].sum()))
elif pa.types.is_integer(values.type) and len(values) > values.null_count:
minmax = pc.min_max(values)
out.update(min=minmax['min'].as_py(), max=minmax['max'].as_py())
return out
def _flag_counts(flags) -> dict[str, int]:
counts: dict[str, int] = {}
for row in pc.value_counts(flags).to_pylist():
value, n = row['values'], int(row['counts'])
parts = [p for p in (value or '').split(';') if p]
if not parts:
counts['(clean)'] = counts.get('(clean)', 0) + n
for part in parts:
counts[part] = counts.get(part, 0) + n
return dict(sorted(counts.items()))
def assemble_table(layer: Layer, ctx: 'LayerContext', group: int, reduced, columns: dict[str, dict],
*, source_checksum: str, computed_at: str, extra: str | None = None
) -> tuple[pa.Table, dict]:
"""Expand a reduce result to exactly one row per cell of the band group, plus metadata."""
planet = ctx.planet
where = f'{layer.slug} band group {group:03d}' + (f' extra {extra!r}' if extra else '')
cells = cells_table(planet, group)
n = len(cells)
if reduced is None:
reduced = pa.table({'region_id': pa.array([], type=pa.string())})
elif not isinstance(reduced, pa.Table):
if hasattr(reduced, 'to_dict') and hasattr(reduced, 'columns'):
reduced = pa.Table.from_pandas(reduced, preserve_index=False)
else:
raise LayerError(f'{where}: reduce must return a pyarrow.Table, got {type(reduced).__name__}')
names = set(reduced.column_names)
if 'region_id' not in names:
raise LayerError(f'{where}: the table has no region_id column')
reserved = sorted((names & RESERVED_COLUMNS) - {'region_id'})
if reserved:
raise LayerError(f'{where}: the table must hold feature columns only, not {reserved}')
features = names - {'region_id', FLAGS_COLUMN}
if len(reduced):
missing = sorted(set(columns) - features)
if missing:
raise LayerError(f'{where}: declared columns missing from the table: {missing}')
undeclared = sorted(features - set(columns))
if undeclared:
raise LayerError(f'{where}: columns not declared in COLUMNS: {undeclared}')
m = len(reduced)
present = np.zeros(n, dtype=bool)
take = np.full(n, -1, dtype=np.int64)
if m:
ids = reduced['region_id'].cast(pa.string())
position = pc.index_in(ids, value_set=cells['region_id'])
if position.null_count:
bad = pc.filter(ids, pc.is_null(position)).to_pylist()[:5]
raise LayerError(f'{where}: {position.null_count} region_id(s) are not cells of this band '
f'group, e.g. {bad}')
position = position.to_numpy(zero_copy_only=False).astype(np.int64)
if len(np.unique(position)) != m:
raise LayerError(f'{where}: duplicate region_id rows ({m - len(np.unique(position))})')
take[position] = np.arange(m)
present[position] = True
present_arr = pa.array(present)
index = pa.array(take, mask=~present)
data: dict[str, Any] = {
'grid_version': _constant(GRID_VERSION, n),
'region_id': cells['region_id'],
'planet': _constant(planet, n),
'band': cells['band'],
'column': cells['column'],
}
for name, spec in columns.items():
typ = spec['_type']
if m and name in names:
try:
values = reduced[name].cast(typ, safe=False).take(index)
except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as exc:
raise LayerError(f'{where}: column {name!r} cannot be {spec["dtype"]}: {exc}') from exc
else:
values = pa.nulls(n, type=typ)
if pa.types.is_floating(typ):
values = pc.fill_null(values, pa.scalar(float('nan'), type=typ))
fill = spec.get('fill')
if fill is None and pa.types.is_floating(typ):
fill = float('nan')
values = pc.if_else(present_arr, values, pa.scalar(fill, type=typ))
data[name] = values
missing_rows = int(n - present.sum())
if m and FLAGS_COLUMN in names:
flags = pc.fill_null(reduced[FLAGS_COLUMN].cast(pa.string()).take(index), '')
else:
flags = pa.array([''] * n, type=pa.string())
if missing_rows:
rule = layer.missing_flag()
if callable(rule):
missing_cells = cells.filter(pa.array(~present))
values = list(rule(group, missing_cells, ctx))
if len(values) != missing_rows:
raise LayerError(f'{where}: MISSING_FLAG returned {len(values)} flags for '
f'{missing_rows} cells')
filler = np.full(n, '', dtype=object)
filler[~present] = values
flags = pc.if_else(present_arr, flags, pa.array(filler, type=pa.string()))
else:
flags = pc.if_else(present_arr, flags, pa.scalar(str(rule), type=pa.string()))
data[FLAGS_COLUMN] = flags
source = layer.source
data['source_product'] = _constant(str(source['product']), n)
data['source_version'] = _constant(str(source['version']), n)
data['source_checksum'] = _constant(source_checksum, n)
data['layer'] = _constant(layer.slug, n)
data['layer_version'] = _constant(layer.layer_version, n)
data['code_version'] = _constant(layer.code_version, n)
data['computed_at'] = _constant(computed_at, n)
table = pa.table(data)
unique = pc.count_distinct(table['region_id']).as_py() == n
summary = {
'rows': n,
'expected_rows': group_cell_count(planet_grid(planet), group),
'rows_with_data': int(present.sum()),
'rows_without_data': missing_rows,
'columns': {name: _column_stats(table[name]) for name in columns},
'flags': _flag_counts(table[FLAGS_COLUMN]),
'checks': {'one_row_per_cell': n == group_cell_count(planet_grid(planet), group),
'region_ids_unique': bool(unique),
'region_ids_match_grid': table['region_id'].equals(cells['region_id'])},
'schema_sha256': hashlib.sha256(json.dumps(
[(f.name, str(f.type)) for f in table.schema]).encode()).hexdigest(),
'source_checksum': source_checksum,
'computed_at': computed_at,
}
if not all(summary['checks'].values()):
raise LayerError(f'{where}: row checks failed: {summary["checks"]}')
bands = group_bands(planet_grid(planet), group)
metadata = {
'layer': layer.slug, 'layer_version': layer.layer_version, 'planet': planet,
'grid_version': GRID_VERSION, 'band_group': str(group), 'extra': extra or '',
'bands': json.dumps([bands[0], bands[-1]]), 'code_version': layer.code_version,
'source': json.dumps(layer.source, sort_keys=True, default=_json_default),
}
return table.replace_schema_metadata(metadata), summary
def write_group_file(table: pa.Table, summary: dict, path: Path) -> None:
metadata = dict(table.schema.metadata or {})
metadata[b'layer_summary'] = dumps(summary).encode()
tf.write_atomic(table.replace_schema_metadata(metadata), path)
def read_local_summary(path: Path, layer: Layer, planet: str, group: int, extra: str | None = None
) -> dict | None:
"""The recorded summary of a finished local file written by this code, else None."""
path = Path(path)
if not path.exists():
return None
try:
metadata = pq.read_schema(path).metadata or {}
get = lambda k: metadata.get(k.encode(), b'').decode() # noqa: E731
if (get('layer') != layer.slug or get('planet') != planet or get('band_group') != str(group)
or get('code_version') != layer.code_version or get('extra') != (extra or '')):
return None
summary = json.loads(get('layer_summary'))
rows = pq.read_metadata(path).num_rows
except Exception:
return None
if rows != group_cell_count(planet_grid(planet), group) or summary.get('rows') != rows:
return None
return summary
# --------------------------------------------------------------------------
# logging
# --------------------------------------------------------------------------
class JsonlLog:
def __init__(self, path: Path | None, **base):
self.path = path
self.base = base
def write(self, event: str, **fields) -> None:
if self.path is None:
return
record = {'ts': _now(), 'event': event, **self.base, **fields}
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open('a', encoding='utf8') as f:
f.write(json.dumps(record, default=_json_default) + '\n')
# --------------------------------------------------------------------------
# context handed to layer functions
# --------------------------------------------------------------------------
@dataclass
class Options:
planet: str
bands: list[int] | None = None
resume: bool = False
workers: int = 4
cache_max_bytes: int = 10 * GB
retries: int = 4
dry_run: bool = False
upload: bool = True
out: Path = DEFAULT_OUT
cache_dir: Path | None = None
log_dir: Path | None = DEFAULT_LOG_DIR
raw_root: Path | None = None # None: RAW_ROOT, looked up when used
interim_root: Path | None = None # None: INTERIM_ROOT
interim_max_bytes: int = 50 * GB
class LayerContext:
"""What ``prepare``/``plan``/``reduce``/``finalize`` receive as ``ctx``."""
def __init__(self, run: 'LayerRun'):
self._run = run
layer, opts = run.layer, run.opts
self.slug = layer.slug
self.planet = run.planet
self.layer_version = layer.layer_version
self.code_version = layer.code_version
self.source = layer.source
self.grid = planet_grid(run.planet)
self.retries = opts.retries
self.workers = opts.workers
self.dry_run = opts.dry_run
self.raw_dir = Path(opts.raw_root or RAW_ROOT) / run.planet / layer.slug
self.interim_dir = Path(opts.interim_root or INTERIM_ROOT) / run.planet / layer.slug
self.interim_cap_bytes = opts.interim_max_bytes
self.band_group: int | None = None
self.bands: list[int] = []
self.cache_dir: Path | None = None
self.state: dict = {} # free for the layer, kept across calls in one run
self.source_checksum: str | None = None # set in prepare() to pin e.g. a file's SHA-256
self.source_files: dict[str, dict] = {}
self._finalizing = False
self._staged: list[tuple[str, int, Path, dict]] = []
self._finalize_checksum: str | None = None
self._read_cache: dict[str, Path] = {}
# -- grid and shared inputs --------------------------------------------
@property
def band_groups(self) -> list[int]:
return list(range(n_groups(self.grid)))
def cells(self, band_group: int | None = None) -> pa.Table:
return cells_table(self.planet, self._group(band_group))
def read_terrain(self, columns, band_group: int | None = None) -> pa.Table:
return read_terrain(self.planet, self._group(band_group), columns)
def land_frac(self, band_group: int | None = None) -> pa.Table:
if self.planet != 'earth':
raise LayerError('the land mask is Earth-only')
return earth_land_frac(self._group(band_group))
def _group(self, band_group):
group = self.band_group if band_group is None else band_group
if group is None:
raise LayerError('no current band group; pass band_group')
return group
# -- prepare helpers ---------------------------------------------------
def download(self, url: str, dest: Path | str | None = None, *, headers: dict | None = None,
sha256: str | None = None) -> Path:
"""Fetch a small file into ``raw_dir`` (default) with retries; skip it if already there."""
dest = Path(dest) if dest else self.raw_dir / (Path(urllib.parse.urlparse(http_url(url)).path).name
or 'download')
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists() and (sha256 is None or sha256_file(dest) == sha256):
return dest
partial = dest.with_name(f'.{dest.name}.part')
class _File:
def __init__(self, fh):
self.fh, self.hash = fh, hashlib.sha256()
def write(self, data):
self.fh.write(data)
self.hash.update(data)
return len(data)
def attempt():
with open(partial, 'wb') as fh:
sink = _File(fh)
fetch_http(Item(key=url, url=url, headers=headers or {}), sink)
if sha256 and sink.hash.hexdigest() != sha256:
raise TransientError(f'{url}: SHA-256 mismatch')
os.replace(partial, dest)
try:
with_retries(attempt, self.retries, f'download {url}')
finally:
partial.unlink(missing_ok=True)
return dest
def record_source_file(self, path: Path | str, name: str | None = None) -> str:
"""Hash a source file and record it in the progress file and the manifest."""
path = Path(path)
digest = sha256_file(path)
self.source_files[name or path.name] = {'sha256': digest, 'size': path.stat().st_size}
return digest
def interim_bytes(self) -> int:
return du(self.interim_dir)
def check_interim(self) -> int:
"""Raise when the interim folder is over --interim-max-gb; call it while streaming."""
size = self.interim_bytes()
if size > self.interim_cap_bytes:
raise CacheCapExceeded(f'{self.interim_dir} holds {human(size)}, over the interim cap of '
f'{human(self.interim_cap_bytes)}')
return size
def log(self, **fields) -> None:
self._run.log.write('layer_note', band_group=self.band_group, **fields)
# -- finalize helpers --------------------------------------------------
def read_layer(self, band_group: int, columns=None, extra: str | None = None) -> pa.Table:
"""One already-written band group of this layer (local copy if present, else the Hub)."""
run = self._run
local = run.local_path(band_group, extra)
if local.exists():
return pq.read_table(local, columns=columns)
if not run.opts.upload:
raise LayerError(f'{local} does not exist (and --no-upload means there is no Hub copy)')
remote = run.layer.relative_group_path(run.planet, band_group, extra)
table = run.hub.read_parquet(remote, columns=columns)
if table is None:
raise LayerError(f'{remote} is not on the Hub')
return table
def write_extra(self, name: str, band_group: int, table) -> None:
"""Stage an extra column set for one band group (finalize only). Uploaded after finalize."""
if not self._finalizing:
raise LayerError('write_extra is only available inside finalize()')
run = self._run
if name not in run.layer.extra_columns:
raise LayerError(f'{run.slug}: extra set {name!r} is not declared in EXTRA_COLUMNS')
if any(n == name and g == band_group for n, g, _, _ in self._staged):
raise LayerError(f'{run.slug}: extra {name!r} band group {band_group} written twice')
full, summary = assemble_table(run.layer, self, band_group, table, run.layer.extra_columns[name],
source_checksum=self._finalize_checksum, computed_at=_now(),
extra=name)
path = run.local_path(band_group, name)
write_group_file(full, summary, path)
self._staged.append((name, band_group, path, summary))
# --------------------------------------------------------------------------
# running layers
# --------------------------------------------------------------------------
@dataclass
class Outcome:
table: Any = None
error: BaseException | None = None
trace: str = ''
empty_plan: bool = False
items: list[Item] = field(default_factory=list)
absent: list[str] = field(default_factory=list)
coverage: Any = None # optional (region_id, asset_id, coverage_frac) table from reduce()
def _new_progress(layer: Layer, planet: str) -> dict:
return {'layer': layer.slug, 'planet': planet, 'layer_version': layer.layer_version,
'grid_version': GRID_VERSION, 'groups': {}, 'extras': {}, 'source_files': {},
'updated_at': None}
def _entry_on_remote(entry: dict | None, listing: dict[str, RemoteFile], code_version: str) -> bool:
if not entry or entry.get('code_version') != code_version:
return False
remote = listing.get(entry['path'])
return remote is not None and remote.matches(entry['size'], entry['sha256'], entry.get('git_blob_id'))
class LayerRun:
"""One layer on one planet for one invocation."""
def __init__(self, layer: Layer, planet: str, opts: Options, hub: HubStore | None):
self.layer = layer
self.slug = layer.slug
self.planet = planet
self.opts = opts
self.hub = hub
log_path = (None if opts.dry_run or opts.log_dir is None
else Path(opts.log_dir) / f'{layer.slug}_{planet}.jsonl')
self.log = JsonlLog(log_path, layer=layer.slug, planet=planet,
layer_version=layer.layer_version)
self.ctx = LayerContext(self)
self.broken: str | None = None
self.progress: dict | None = None
self.listing: dict[str, RemoteFile] = {}
def local_path(self, group: int, extra: str | None = None) -> Path:
relative = self.layer.relative_group_path(self.planet, group, extra).removeprefix('layers/')
return Path(self.opts.out) / relative
def catalog_files(self, group: int) -> dict[str, Path]:
"""remote path -> local path of the catalog files that travel with one band group."""
remote = [catalog_schema.staging_path(self.planet, self.slug, group),
catalog_schema.region_assets_path(self.planet, self.slug, group)]
return {r: Path(self.opts.out) / r for r in remote}
def _build_catalog(self, group: int, outcome: 'Outcome') -> dict:
"""Write this band group's assets rows and region_assets rows beside its feature file.
Returns a small summary (empty when no item carried asset metadata).
"""
staging, region = self.catalog_files(group).values()
for path in (staging, region):
path.unlink(missing_ok=True)
rows, linked = catalog_assets.rows_from_items(
outcome.items, planet=self.planet, layer=self.slug, source=self.layer.source,
raw_root=Path(self.opts.raw_root or RAW_ROOT))
if not rows:
if outcome.coverage is not None:
raise LayerError(f'{self.slug} band group {group:03d}: reduce returned a coverage '
f'table but no item carries asset metadata')
return {}
info = {'assets_rows': len(rows)}
tf.write_atomic(catalog_schema.assets_table(rows), staging)
cells = cells_table(self.planet, group)
if outcome.coverage is not None:
table = _check_coverage(outcome.coverage, cells, {r['asset_id'] for r in rows},
f'{self.slug} band group {group:03d}')
elif linked:
table = catalog_coverage.coverage_table(
cells, [(r['asset_id'], r['footprint']) for r in rows if r['asset_id'] in linked])
else:
return info
tf.write_atomic(table, region)
info['region_assets_rows'] = table.num_rows
return info
# -- status --------------------------------------------------------------
def refresh(self) -> None:
if self.opts.upload:
self.progress = (self.hub.read_json(self.layer.progress_path(self.planet))
or _new_progress(self.layer, self.planet))
self.listing = self.hub.list(self.layer.remote_prefix(self.planet))
else:
self.progress, self.listing = None, {}
def group_done(self, group: int, extra: str | None = None) -> bool:
if not self.opts.upload:
return read_local_summary(self.local_path(group, extra), self.layer, self.planet, group,
extra) is not None
key = f'{group:03d}'
entry = (self.progress['groups'].get(key) if extra is None
else self.progress.get('extras', {}).get(extra, {}).get(key))
return _entry_on_remote(entry, self.listing, self.layer.code_version)
# -- prepare -------------------------------------------------------------
def prepare(self) -> None:
prepare = getattr(self.layer.module, 'prepare', None)
if not callable(prepare):
return
started = time.monotonic()
prepare(self.ctx)
size = self.ctx.check_interim()
print(f'{self.slug} {self.planet}: prepare done in {time.monotonic() - started:.1f}s, '
f'interim folder {human(size)} ({self.ctx.interim_dir})', flush=True)
self.log.write('prepare', seconds=time.monotonic() - started, interim_bytes=size,
interim_dir=self.ctx.interim_dir, raw_bytes=du(self.ctx.raw_dir),
source_files=self.ctx.source_files)
# -- per band group ------------------------------------------------------
def finish_group(self, group: int, outcome: Outcome, stats: dict, shared_with: list[str]) -> bool:
base = {'band_group': group, **stats, 'code_version': self.layer.code_version}
if shared_with:
base['pass_group'] = self.layer.pass_group
base['shared_with'] = shared_with
base['items_planned'] = len(outcome.items)
base['items_absent'] = len(outcome.absent)
if outcome.error is not None:
return self._failed(group, outcome.error, outcome.trace, base)
try:
checksum = self.ctx.source_checksum or items_checksum(outcome.items)
table, summary = assemble_table(self.layer, self.ctx, group, outcome.table,
self.layer.columns, source_checksum=checksum,
computed_at=_now())
summary['run'] = {k: base[k] for k in ('seconds', 'items_planned', 'items_absent',
'bytes_read', 'peak_cache_bytes', 'fetches',
'refetches', 'retried') if k in base}
summary['items_absent'] = outcome.absent[:50]
catalog_info = self._build_catalog(group, outcome)
if catalog_info:
summary['catalog'] = catalog_info
path = self.local_path(group)
if self.planet == 'earth' and self.layer.pass_group == 'copdem_glo30':
print(f'{_now()} Copernicus group {group:03d} writing Parquet {self.slug}', flush=True)
write_group_file(table, summary, path)
except Exception as exc:
return self._failed(group, exc, traceback.format_exc(), base)
base['rows'] = summary['rows']
base['rows_without_data'] = summary['rows_without_data']
if not self.opts.upload:
self.log.write('band_group', status='written', path=path, **base)
print(self._line(group, base, f'written {path}'), flush=True)
return True
return self.upload_group(group, path, summary, base)
def _failed(self, group, exc, trace, base) -> bool:
message = f'{type(exc).__name__}: {exc}'
print(f'{self.slug} {self.planet} group {group:03d}: FAILED, nothing written: {message}',
file=sys.stderr, flush=True)
self.log.write('band_group', status='failed', error=message, traceback=trace[-4000:], **base)
return False
def _line(self, group, base, tail) -> str:
return (f"{self.slug} {self.planet} group {group:03d}: {base.get('items_planned', 0)} items "
f"({base.get('items_absent', 0)} absent), {human(base.get('bytes_read'))} read, "
f"peak cache {human(base.get('peak_cache_bytes'))}, {base.get('rows', 0)} rows, "
f"{base.get('seconds', 0):.1f}s -> {tail}")
def upload_group(self, group: int, path: Path, summary: dict, base: dict) -> bool:
remote_path = self.layer.relative_group_path(self.planet, group)
key = f'{group:03d}'
size, sha, blob = path.stat().st_size, sha256_file(path), git_blob_id_file(path)
bands = group_bands(planet_grid(self.planet), group)
entry = {'path': remote_path, 'size': size, 'sha256': sha, 'git_blob_id': blob,
'code_version': self.layer.code_version, 'bands': [bands[0], bands[-1]],
**{k: summary[k] for k in ('rows', 'expected_rows', 'rows_with_data',
'rows_without_data', 'columns', 'flags', 'checks',
'schema_sha256', 'source_checksum', 'computed_at')},
'run': summary.get('run', {})}
catalog = {r: p for r, p in self.catalog_files(group).items() if p.exists()}
if summary.get('catalog'):
entry['catalog'] = {**summary['catalog'], 'files': sorted(catalog)}
started = time.monotonic()
def mutate(progress):
progress = progress or _new_progress(self.layer, self.planet)
progress.setdefault('groups', {})[key] = entry
progress.setdefault('source_files', {}).update(self.ctx.source_files)
progress['interim_bytes'] = self.ctx.interim_bytes()
progress['updated_at'] = _now()
return progress
def already(progress, head):
done = (progress or {}).get('groups', {}).get(key)
if not done or done.get('sha256') != sha:
return False
remote = self.hub.info([remote_path], revision=head).get(remote_path)
return remote is not None and remote.matches(size, sha, blob)
try:
oid, progress = self.hub.commit_update(
{remote_path: path, **catalog},
f'layer {self.layer.layer_version} {self.planet} band_group={key} '
f'(code {self.layer.code_version[:12]})',
self.layer.progress_path(self.planet), mutate, already)
remote = self.hub.info([remote_path], revision=oid).get(remote_path)
if remote is None or not remote.matches(size, sha, blob):
raise UploadError(f'{remote_path} on the Hub does not match the local file '
f'(remote {remote}, local size {size} sha256 {sha})')
if catalog:
info = self.hub.info(list(catalog), revision=oid)
for rpath, lpath in catalog.items():
got = info.get(rpath)
if got is None or not got.matches(lpath.stat().st_size, sha256_file(lpath),
git_blob_id_file(lpath)):
raise UploadError(f'{rpath} on the Hub does not match the local file')
except Exception as exc:
base['upload_seconds'] = time.monotonic() - started
message = f'{type(exc).__name__}: {exc}'
print(f'{self.slug} {self.planet} group {key}: UPLOAD FAILED, local file kept at {path}: '
f'{message}', file=sys.stderr, flush=True)
self.log.write('band_group', status='upload_failed', error=message, path=path, **base)
return False
path.unlink()
for lpath in catalog.values():
lpath.unlink(missing_ok=True)
self.progress = progress
self.listing[remote_path] = remote
base['upload_seconds'] = time.monotonic() - started
base['commit'] = oid
self.log.write('band_group', status='uploaded', remote_path=remote_path, size=size,
sha256=sha, **base)
print(self._line(group, base, f'{remote_path} ({human(size)}, upload '
f'{base["upload_seconds"]:.1f}s)'), flush=True)
return True
def reuse_local(self, group: int) -> bool | None:
"""Upload a finished local file left by an interrupted run instead of recomputing it."""
path = self.local_path(group)
summary = read_local_summary(path, self.layer, self.planet, group)
if summary is None:
return None
print(f'{self.slug} {self.planet} group {group:03d}: uploading the finished local file '
f'from an earlier run ({path})', flush=True)
base = {'band_group': group, 'reused_local': True, 'rows': summary['rows'],
'code_version': self.layer.code_version, **summary.get('run', {})}
return self.upload_group(group, path, summary, base)
# -- finalize -------------------------------------------------------------
def finalize(self) -> bool:
groups = list(range(n_groups(planet_grid(self.planet))))
self.refresh()
missing = [g for g in groups if not self.group_done(g)]
if missing:
print(f'{self.slug} {self.planet}: finalize waits for {len(missing)} band group(s) '
f'(first {missing[:5]})', flush=True)
self.log.write('finalize', status='waiting', missing_groups=missing)
return True
names = list(self.layer.extra_columns)
if self.opts.resume and all(self.group_done(g, n) for n in names for g in groups):
print(f'{self.slug} {self.planet}: finalize already complete, skipped', flush=True)
self.log.write('finalize', status='skipped')
return True
if self.opts.upload:
shas = [self.progress['groups'][f'{g:03d}']['sha256'] for g in groups]
else:
shas = [sha256_file(self.local_path(g)) for g in groups]
ctx = self.ctx
ctx._finalize_checksum = 'groups-sha256:' + hashlib.sha256(''.join(shas).encode()).hexdigest()
ctx._finalizing, ctx._staged, ctx.band_group = True, [], None
started = time.monotonic()
try:
self.layer.module.finalize(ctx)
for name in names:
written = {g for n, g, _, _ in ctx._staged if n == name}
if written != set(groups):
raise LayerError(f'finalize wrote extra {name!r} for {len(written)} of '
f'{len(groups)} band groups')
except Exception as exc:
for _, _, path, _ in ctx._staged:
path.unlink(missing_ok=True)
message = f'{type(exc).__name__}: {exc}'
print(f'{self.slug} {self.planet}: finalize FAILED, nothing uploaded: {message}',
file=sys.stderr, flush=True)
self.log.write('finalize', status='failed', error=message,
traceback=traceback.format_exc()[-4000:])
return False
finally:
ctx._finalizing = False
seconds = time.monotonic() - started
staged = sorted(ctx._staged, key=lambda s: (s[0], s[1]))
if not self.opts.upload:
self.log.write('finalize', status='written', seconds=seconds, files=len(staged))
print(f'{self.slug} {self.planet}: finalize wrote {len(staged)} extra files locally '
f'in {seconds:.1f}s', flush=True)
return True
return self._upload_extras(staged, seconds)
def _upload_extras(self, staged, seconds) -> bool:
started = time.monotonic()
for i in range(0, len(staged), EXTRA_FILES_PER_COMMIT):
batch = staged[i:i + EXTRA_FILES_PER_COMMIT]
files, entries = {}, {}
for name, group, path, summary in batch:
remote_path = self.layer.relative_group_path(self.planet, group, name)
files[remote_path] = path
entries[(name, f'{group:03d}')] = {
'path': remote_path, 'size': path.stat().st_size, 'sha256': sha256_file(path),
'git_blob_id': git_blob_id_file(path), 'code_version': self.layer.code_version,
**{k: summary[k] for k in ('rows', 'expected_rows', 'columns', 'flags', 'checks',
'schema_sha256', 'source_checksum', 'computed_at')}}
def mutate(progress, entries=entries):
progress = progress or _new_progress(self.layer, self.planet)
for (name, key), entry in entries.items():
progress.setdefault('extras', {}).setdefault(name, {})[key] = entry
progress.setdefault('finalize', {})['seconds'] = seconds
progress['updated_at'] = _now()
return progress
def already(progress, head, entries=entries):
extras = (progress or {}).get('extras', {})
if not all(extras.get(n, {}).get(k, {}).get('sha256') == e['sha256']
for (n, k), e in entries.items()):
return False
info = self.hub.info([e['path'] for e in entries.values()], revision=head)
return all(info.get(e['path']) and info[e['path']].matches(
e['size'], e['sha256'], e['git_blob_id']) for e in entries.values())
try:
oid, progress = self.hub.commit_update(
files, f'layer {self.layer.layer_version} {self.planet} finalize '
f'{i // EXTRA_FILES_PER_COMMIT + 1} (code {self.layer.code_version[:12]})',
self.layer.progress_path(self.planet), mutate, already)
info = self.hub.info(list(files), revision=oid)
for e in entries.values():
if not (info.get(e['path']) and info[e['path']].matches(
e['size'], e['sha256'], e['git_blob_id'])):
raise UploadError(f'{e["path"]} on the Hub does not match the local file')
except Exception as exc:
message = f'{type(exc).__name__}: {exc}'
print(f'{self.slug} {self.planet}: finalize UPLOAD FAILED (local files kept): '
f'{message}', file=sys.stderr, flush=True)
self.log.write('finalize', status='upload_failed', error=message)
return False
for path in files.values():
path.unlink()
self.progress = progress
self.log.write('finalize', status='uploaded', seconds=seconds, files=len(staged),
upload_seconds=time.monotonic() - started)
print(f'{self.slug} {self.planet}: finalize uploaded {len(staged)} extra files '
f'({seconds:.1f}s compute, {time.monotonic() - started:.1f}s upload)', flush=True)
return True
def run_band_group(runs: list[LayerRun], group: int, opts: Options, cache_root: Path
) -> tuple[dict[str, Outcome], dict]:
"""Plan, fetch and reduce one band group for the layers of one pass. Wipes the cache after."""
grid = planet_grid(opts.planet)
bands = group_bands(grid, group)
outcomes: dict[str, Outcome] = {}
plans: dict[str, list[Item]] = {}
started = time.monotonic()
for run in runs:
run.ctx.band_group, run.ctx.bands = group, bands
try:
plans[run.slug] = normalize_items(run.layer.module.plan(group, run.ctx), run.slug)
except Exception as exc:
outcomes[run.slug] = Outcome(error=exc, trace=traceback.format_exc())
cache = GroupCache(cache_root / f'group_{group:03d}', opts.cache_max_bytes,
retries=opts.retries, workers=opts.workers)
try:
for slug, items in list(plans.items()):
try:
cache.register(slug, items)
except LayerError as exc:
outcomes[slug] = Outcome(error=exc, trace=traceback.format_exc(), items=items)
del plans[slug]
active = [r for r in runs if plans.get(r.slug)]
for run in runs:
if run.slug in plans and not plans[run.slug]:
outcomes[run.slug] = Outcome(empty_plan=True)
cache.add_consumers(len(active))
def work(run: LayerRun) -> None:
run.ctx.cache_dir = cache.root
items = Items(cache, run.slug, plans[run.slug])
try:
table = run.layer.module.reduce(group, items, run.ctx)
coverage = None
if isinstance(table, tuple):
if len(table) != 2:
raise LayerError(f'{run.slug}.reduce returned a {len(table)}-tuple; return a '
f'table or (feature table, coverage table)')
table, coverage = table
if items.failed:
raise FetchFailed(f'{len(items.failed)} item(s) failed to fetch, so the band group '
f'stops instead of writing NaNs: {items.failed[:5]}')
if table is None:
raise LayerError(f'{run.slug}.reduce returned None; return a pyarrow.Table')
outcomes[run.slug] = Outcome(table=table, items=plans[run.slug], absent=items.absent,
coverage=coverage)
except Exception as exc:
outcomes[run.slug] = Outcome(error=exc, trace=traceback.format_exc(),
items=plans[run.slug], absent=items.absent)
finally:
cache.finish(run.slug)
if len(active) == 1:
work(active[0])
elif active:
threads = [threading.Thread(target=work, args=(r,), name=f'reduce-{r.slug}') for r in active]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
finally:
stats = cache.stats()
stats['cache_bytes_left'] = cache.close()
for run in runs:
run.ctx.cache_dir = None
stats['seconds'] = time.monotonic() - started
stats['cache_files_after_wipe'] = sum(1 for p in cache.root.rglob('*')) if cache.root.exists() else 0
return outcomes, stats
def _pass_groups(runs: list[LayerRun]) -> list[list[LayerRun]]:
groups: dict[str, list[LayerRun]] = {}
for run in runs:
groups.setdefault(run.layer.pass_group or f'__{run.slug}', []).append(run)
return list(groups.values())
def _dry_run_plan(runs: list[LayerRun], todo: dict[int, list[LayerRun]], opts: Options) -> None:
print(f'DRY RUN: planning only; nothing is fetched, written or uploaded '
f'(prepare() is not run, so a plan that needs it reports an error)')
for group, need in todo.items():
seen: dict[str, Item] = {}
for run in need:
run.ctx.band_group, run.ctx.bands = group, group_bands(planet_grid(opts.planet), group)
try:
items = normalize_items(run.layer.module.plan(group, run.ctx), run.slug)
except Exception as exc:
print(f' group {group:03d} {run.slug}: plan failed: {type(exc).__name__}: {exc}')
continue
sizes = [i.expected_size() for i in items]
known = [s for s in sizes if s is not None]
fits = all(s <= opts.cache_max_bytes for s in known)
print(f' group {group:03d} {run.slug}: {len(items)} items, {human(sum(known))} of known '
f'size (+{len(sizes) - len(known)} unknown), largest {human(max(known, default=0))}'
f'{"" if fits else " ** an item is larger than --cache-max-gb **"}'
f'{" (no source data: rows get fill values)" if not items else ""}')
for item in items:
seen.setdefault(item.key, item)
if len(need) > 1:
print(f' group {group:03d} pass total: {len(seen)} distinct items')
def run_layers(layers: list[Layer], opts: Options, hub: HubStore | None) -> int:
planet = opts.planet
grid = planet_grid(planet)
groups = groups_for_bands(grid, opts.bands)
runs = []
for layer in layers:
if planet not in layer.planets:
only = layer.planets[0]
print(f'{layer.slug}: {only.capitalize()}-only layer; it writes no {planet.capitalize()} '
f'rows (recorded in its manifest feature dictionary). Nothing to do.', flush=True)
if not opts.dry_run and opts.log_dir is not None:
JsonlLog(Path(opts.log_dir) / f'{layer.slug}_{planet}.jsonl', layer=layer.slug,
planet=planet).write('not_applicable', layer_planets=list(layer.planets))
continue
runs.append(LayerRun(layer, planet, opts, hub))
if not runs:
return 0
if opts.upload:
# fail before computing anything: a missing repo or token would otherwise look like
# "nothing uploaded yet" (404) and only surface after the first band group
try:
hub.head()
except Exception as exc:
print(f'error: cannot reach {hub.repo_id} on the Hub ({type(exc).__name__}: {exc}); '
f'log in (hf auth login) or use --no-upload', file=sys.stderr)
return 2
cache_root =Path(opts.cache_dir) if opts.cache_dir else Path(tempfile.mkdtemp(prefix='layer-cache-'))
cache_root.mkdir(parents=True, exist_ok=True)
failures = 0
try:
for pass_runs in _pass_groups(runs):
failures += _run_pass(pass_runs, groups, opts, cache_root)
finally:
if not opts.cache_dir:
shutil.rmtree(cache_root, ignore_errors=True)
if failures:
print(f'{failures} band group(s) or finalize step(s) failed; see the log(s) in {opts.log_dir}. '
f'Re-run with --resume to retry only those.', file=sys.stderr, flush=True)
return 1 if failures else 0
def _run_pass(runs: list[LayerRun], groups: list[int], opts: Options, cache_root: Path) -> int:
names = ','.join(r.slug for r in runs)
for run in runs:
run.refresh()
todo: dict[int, list[LayerRun]] = {}
for group in groups:
need = []
for run in runs:
if opts.resume and run.group_done(group):
print(f'{run.slug} {run.planet} group {group:03d}: already complete with this '
f'code_version, skipped', flush=True)
run.log.write('band_group', band_group=group, status='skipped')
else:
need.append(run)
if need:
todo[group] = need
if opts.dry_run:
_dry_run_plan(runs, todo, opts)
return 0
print(f'{names} ({opts.planet}): {len(todo)} band group(s) to run, cache cap '
f'{opts.cache_max_bytes / GB:g} GB, {opts.workers} fetch worker(s)', flush=True)
failures = 0
for run in runs:
try:
run.prepare()
except Exception as exc:
run.broken = f'{type(exc).__name__}: {exc}'
print(f'{run.slug} {run.planet}: prepare FAILED, layer skipped: {run.broken}',
file=sys.stderr, flush=True)
run.log.write('prepare', status='failed', error=run.broken,
traceback=traceback.format_exc()[-4000:])
failures += 1
for group, need in todo.items():
need = [r for r in need if not r.broken]
if opts.upload and opts.resume:
remaining = []
for run in need:
reused = run.reuse_local(group)
if reused is None:
remaining.append(run)
elif not reused:
failures += 1
need = remaining
if not need:
continue
outcomes, stats = run_band_group(need, group, opts, cache_root)
for run in need:
shared = [r.slug for r in need if r is not run]
if not run.finish_group(group, outcomes[run.slug], dict(stats), shared):
failures += 1
for run in runs:
if run.layer.has_finalize and not run.broken:
if not run.finalize():
failures += 1
return failures
# --------------------------------------------------------------------------
# publishing
# --------------------------------------------------------------------------
CARD_HEADING = '## Layers'
CARD_INTRO = ('Dataset layers on the `latband5km-v1` grid, one file per 100 latitude bands with one row '
'per cell. Join on `grid_version` + `region_id`. Each layer has its own manifest under '
'`manifests/` and its own tag.')
def _public_columns(columns: dict[str, dict], stats: dict[str, dict]) -> list[dict]:
out = []
for name, spec in columns.items():
row = {'name': name, 'dtype': spec['dtype'], 'unit': spec.get('unit'),
'comparison': spec.get('comparison'), 'description': spec.get('description'),
'fill_for_cells_without_data': spec.get('fill', 'NaN' if pa.types.is_floating(
spec['_type']) else None)}
row.update(stats.get(name, {}))
out.append(row)
return out
def _aggregate_stats(entries: list[dict]) -> dict[str, dict]:
out: dict[str, dict] = {}
for entry in entries:
for name, stat in entry.get('columns', {}).items():
agg = out.setdefault(name, {'n_null': 0})
agg['n_null'] += stat.get('n_null', 0)
for key in ('n_nan', 'n_finite', 'sum'):
if key in stat:
agg[key] = agg.get(key, 0) + stat[key]
if stat.get('min') is not None:
agg['min'] = stat['min'] if agg.get('min') is None else min(agg['min'], stat['min'])
if stat.get('max') is not None:
agg['max'] = stat['max'] if agg.get('max') is None else max(agg['max'], stat['max'])
for agg in out.values():
if agg.get('n_finite'):
agg['mean'] = agg.pop('sum') / agg['n_finite']
else:
agg.pop('sum', None)
return out
def _undocumented(columns: dict[str, dict]) -> list[str]:
problems = []
for name, spec in columns.items():
if not spec.get('unit'):
problems.append(f'{name}: no unit')
if not spec.get('description'):
problems.append(f'{name}: no description')
if spec.get('comparison') not in COMPARISON_MODES:
problems.append(f'{name}: comparison {spec.get("comparison")!r} not in '
f'{sorted(COMPARISON_MODES)}')
return problems
def build_publication(run: LayerRun) -> dict:
"""Everything a publish would upload, and the checks that decide whether it may."""
layer, planet = run.layer, run.planet
run.refresh()
progress, listing = run.progress, run.listing
grid = planet_grid(planet)
groups = list(range(n_groups(grid)))
cv = layer.code_version
entries = {g: progress.get('groups', {}).get(f'{g:03d}') for g in groups}
checks: list[dict] = []
def check(name, ok, detail=''):
checks.append({'name': name, 'ok': bool(ok), 'detail': detail})
present = [g for g in groups if _entry_on_remote(entries[g], listing, cv)]
absent = [g for g in groups if g not in present]
check('all_band_groups_present', not absent,
f'{len(present)}/{len(groups)} band groups on the Hub with code_version {cv[:12]}'
+ (f'; missing or stale: {absent[:10]}' if absent else ''))
stale = sorted(g for g, e in entries.items() if e and e.get('code_version') != cv)
check('code_version_matches_data', not stale,
f'band groups written by other code: {stale[:10]}' if stale else
f'every recorded band group was written by code_version {cv[:12]}')
expected = {g: group_cell_count(grid, g) for g in groups}
total_rows = sum(entries[g]['rows'] for g in present)
bad_rows = [g for g in present if entries[g]['rows'] != expected[g]]
check('rows_match_grid', not bad_rows and not absent and total_rows == grid.number_of_cells,
f'{total_rows} rows for {grid.number_of_cells} grid cells'
+ (f'; wrong counts in {bad_rows[:10]}' if bad_rows else ''))
bad_ids = [g for g in present if not all(entries[g].get('checks', {}).values())]
check('region_ids_unique_and_match_grid', not bad_ids,
f'failing groups: {bad_ids[:10]}' if bad_ids else 'one row per cell, unique ids, grid order')
schemas = {entries[g].get('schema_sha256') for g in present}
check('schema_consistent', len(schemas) <= 1, f'{len(schemas)} distinct schemas')
problems = _undocumented(layer.columns)
for name, spec in layer.extra_columns.items():
problems += [f'extra {name}: {p}' for p in _undocumented(spec)]
check('columns_documented', not problems, '; '.join(problems[:10]) or 'unit, description and '
'comparison mode for every column')
extras_out = {}
if layer.has_finalize:
missing_extras = []
for name in layer.extra_columns:
recorded = progress.get('extras', {}).get(name, {})
ok = [g for g in groups if _entry_on_remote(recorded.get(f'{g:03d}'), listing, cv)]
missing_extras += [f'{name}:{g:03d}' for g in groups if g not in ok]
extras_out[name] = {
'pattern': f'{layer.remote_prefix(planet)}/extra={name}/band_group=NNN.parquet',
'files': len(ok),
'columns': _public_columns(layer.extra_columns[name], _aggregate_stats(
[recorded[f'{g:03d}'] for g in ok]))}
check('extras_complete', not missing_extras,
f'missing: {missing_extras[:10]}' if missing_extras else
f'{len(layer.extra_columns)} extra set(s) on every band group')
good = [entries[g] for g in present]
stats = _aggregate_stats(good)
flags: dict[str, int] = {}
for entry in good:
for flag, n in entry.get('flags', {}).items():
flags[flag] = flags.get(flag, 0) + n
summary = {'rows': total_rows, 'columns': stats, 'flags': flags, 'groups': len(present)}
validate = getattr(layer.module, 'validate', None)
if callable(validate):
try:
for name, ok, detail in validate(summary, run.ctx):
check(f'layer:{name}', ok, detail)
except Exception as exc:
check('layer:validate', False, f'validate() raised {type(exc).__name__}: {exc}')
planets = {}
for p in ('mars', 'earth'):
if p in layer.planets:
planets[p] = {'rows': True, 'note': 'one row per latband5km-v1 cell'}
else:
only = layer.planets[0]
planets[p] = {'rows': False,
'note': f'{only.capitalize()}-only layer: no {p.capitalize()} rows are written'}
limitations = list(getattr(layer.module, 'LIMITATIONS', []))
if len(layer.planets) == 1:
limitations.append(f'{layer.planets[0].capitalize()} only; there are no rows for the other '
f'planet.')
absent_items = sum(e.get('run', {}).get('items_absent', 0) for e in good)
if absent_items:
limitations.append(f'{absent_items} planned source item(s) did not exist at the source; the '
f'affected cells carry NaN and a quality flag.')
code_files = {f'code/layers/{layer.path.name}': layer.path, 'code/layers/driver.py': DRIVER_PATH}
for path in layer.crosswalks:
code_files[f'code/layers/{path.name}'] = path
tag = layer.tag(planet)
manifest = {
'layer': layer.slug, 'layer_version': layer.layer_version, 'planet': planet,
'grid_version': GRID_VERSION, 'repo': run.hub.repo_id, 'tag': tag,
'files': {'pattern': f'{layer.remote_prefix(planet)}/band_group=NNN.parquet',
'band_groups': len(groups), 'bands_per_group': BANDS_PER_GROUP, 'extras': extras_out},
'code_version': cv,
'code_version_definition': 'SHA-256 over the layer module, then pipeline/layers/driver.py, '
'then each crosswalk, in that order',
'code_files': {dest: sha256_file(src) for dest, src in code_files.items()},
'source': layer.source,
'source_checksums': {f'{g:03d}': entries[g].get('source_checksum') for g in present},
'source_files': progress.get('source_files', {}),
'feature_dictionary': {
'planets': planets,
'metadata_columns': [*LEADING_COLUMNS, FLAGS_COLUMN, *TRAILING_COLUMNS],
'columns': _public_columns(layer.columns, stats),
'comparison_modes': COMPARISON_MODES,
'missing_flag': layer.missing_flag() if isinstance(layer.missing_flag(), str)
else 'set per cell by the layer (MISSING_FLAG callable)',
},
'quality_flags': dict(sorted(flags.items())),
'rows': {'total': total_rows, 'expected': grid.number_of_cells,
'with_data': sum(e.get('rows_with_data', 0) for e in good),
'without_data': sum(e.get('rows_without_data', 0) for e in good),
'by_band_group': {f'{g:03d}': entries[g]['rows'] for g in present}},
'validation': checks,
'runtime': {'seconds': sum(e.get('run', {}).get('seconds', 0) for e in good),
'finalize_seconds': progress.get('finalize', {}).get('seconds'),
'by_band_group': {f'{g:03d}': entries[g].get('run', {}).get('seconds')
for g in present}},
'bytes_read': sum(e.get('run', {}).get('bytes_read', 0) for e in good),
'peak_cache_bytes': max((e.get('run', {}).get('peak_cache_bytes', 0) for e in good), default=0),
'interim_bytes': progress.get('interim_bytes'),
'known_limitations': limitations,
}
files: dict[str, bytes] = {layer.manifest_path(planet): (dumps(manifest) + '\n').encode()}
for dest, src in code_files.items():
files[dest] = src.read_bytes()
return {'manifest': manifest, 'checks': checks, 'files': files, 'tag': tag,
'ok': all(c['ok'] for c in checks), 'card_section': render_card_section(layer, manifest)}
def _check_coverage(coverage, cells: pa.Table, asset_ids: set[str], where: str) -> pa.Table:
"""A coverage table a layer returned from reduce(): validated, typed, in the catalog schema."""
if hasattr(coverage, 'to_dict') and hasattr(coverage, 'columns') and not isinstance(coverage, pa.Table):
coverage = pa.Table.from_pandas(coverage, preserve_index=False)
if not isinstance(coverage, pa.Table):
raise LayerError(f'{where}: the coverage table must be a pyarrow.Table')
missing = {'region_id', 'asset_id', 'coverage_frac'} - set(coverage.column_names)
if missing:
raise LayerError(f'{where}: the coverage table lacks {sorted(missing)}')
n = coverage.num_rows
region = coverage['region_id'].cast(pa.string())
asset = coverage['asset_id'].cast(pa.string())
frac = coverage['coverage_frac'].cast(pa.float64())
if n:
if pc.index_in(region, value_set=cells['region_id']).null_count:
raise LayerError(f'{where}: coverage region_id(s) are not cells of this band group')
unknown = sorted(set(asset.to_pylist()) - asset_ids)
if unknown:
raise LayerError(f'{where}: coverage names asset_id(s) no planned item carries, '
f'e.g. {unknown[:3]}')
values = frac.to_numpy(zero_copy_only=False)
if frac.null_count or not np.all(np.isfinite(values)) or values.min() < 0 or values.max() > 1 + 1e-6:
raise LayerError(f'{where}: coverage_frac must be finite and within 0-1')
pairs = pc.count_distinct(pc.binary_join_element_wise(region, asset, '|')).as_py()
if pairs != n:
raise LayerError(f'{where}: duplicate (region_id, asset_id) rows in the coverage table')
return pa.table({'grid_version': pa.array([GRID_VERSION] * n, type=pa.string()), 'region_id': region,
'asset_id': asset,
'coverage_frac': pa.array(np.clip(frac.to_numpy(zero_copy_only=False), 0, 1)
.astype(np.float32))},
schema=catalog_schema.REGION_ASSETS_SCHEMA)
def build_catalog_publication(run: LayerRun) -> tuple[dict[str, bytes], list[dict]]:
"""The merged ``assets`` file for a layer (staged band-group rows + any existing file, one row
per asset_id) and a consistency check against the ``region_assets`` files on the Hub."""
hub, planet, slug = run.hub, run.planet, run.slug
staged = hub.list(f'catalog/assets_staging/planet={planet}/layer={slug}')
if not staged:
return {}, []
path = catalog_schema.assets_path(planet, slug)
tables = [hub.read_parquet(p) for p in sorted(staged)]
merged = catalog_schema.merge_assets([*tables, hub.read_parquet(path)])
buffer = io.BytesIO()
pq.write_table(merged, buffer, compression='zstd')
ids = set(merged['asset_id'].to_pylist())
region_files = hub.list(f'catalog/region_assets/planet={planet}/layer={slug}')
dangling, rows = 0, 0
for rpath in sorted(region_files):
table = hub.read_parquet(rpath, columns=['asset_id'])
rows += table.num_rows
dangling += sum(1 for a in set(table['asset_id'].to_pylist()) if a not in ids)
check = {'name': 'catalog_assets_consistent', 'ok': dangling == 0,
'detail': f'{merged.num_rows} assets rows, {rows} region_assets rows in {len(region_files)} '
f'file(s)' + (f'; {dangling} asset_id(s) in region_assets missing from assets'
if dangling else '')}
return {path: buffer.getvalue()}, [check]
def render_card_section(layer: Layer, manifest: dict) -> str:
planet = manifest['planet']
src = layer.source
lines = [
f'### `{layer.slug}` ({planet.capitalize()}), `{layer.layer_version}`',
'',
f'Source: [{src["product"]} {src["version"]}]({src["url"]}). Licence: {src["licence"]}.',
]
for aux in src.get('aux', []) or []:
lines.append(f'Also uses [{aux.get("product")} {aux.get("version", "")}]({aux.get("url", "")})'
f' (licence: {aux.get("licence", "see source")}).')
rows = manifest['rows']
lines += [
'',
f'Files: `{manifest["files"]["pattern"]}` ({manifest["files"]["band_groups"]} files, '
f'{rows["total"]:,} rows, one per grid cell; {rows["without_data"]:,} cells have no source '
f'data and carry fill values plus a quality flag). Tag `{manifest["tag"]}`, manifest '
f'`{layer.manifest_path(planet)}`, code `code/layers/{layer.path.name}` '
f'(code_version `{manifest["code_version"][:12]}`).',
]
for name, extra in manifest['files']['extras'].items():
lines.append(f'Extra column set `{name}`: `{extra["pattern"]}`.')
other = [p for p, v in manifest['feature_dictionary']['planets'].items() if not v['rows']]
if other:
lines.append(f'{planet.capitalize()} only: there are no {", ".join(p.capitalize() for p in other)}'
f' rows for this layer.')
lines += ['', '| Column | Type | Unit | Comparison | Meaning |', '|---|---|---|---|---|']
for col in manifest['feature_dictionary']['columns']:
lines.append(f'| `{col["name"]}` | {col["dtype"]} | {col["unit"]} | {col["comparison"]} | '
f'{col["description"]} |')
for name, extra in manifest['files']['extras'].items():
for col in extra['columns']:
lines.append(f'| `{col["name"]}` (extra `{name}`) | {col["dtype"]} | {col["unit"]} | '
f'{col["comparison"]} | {col["description"]} |')
flags = {k: v for k, v in manifest['quality_flags'].items() if k != '(clean)'}
if flags:
lines += ['', 'Quality flags: ' + ', '.join(f'`{k}` ({v:,})' for k, v in flags.items()) + '.']
if manifest['known_limitations']:
lines += ['', 'Known limitations:', '']
lines += [f'- {text}' for text in manifest['known_limitations']]
lines += [
'', '```python', 'import pandas as pd',
f'df = pd.read_parquet("hf://datasets/{manifest["repo"]}@{manifest["tag"]}/'
f'{manifest["files"]["pattern"].replace("NNN", "000")}")', '```',
]
return '\n'.join(lines)
def update_card(text: str, slug: str, planet: str, section: str) -> str:
"""Replace (or add) this layer's marked section of the README; nothing else changes."""
start, end = f'<!-- layer:{slug}:{planet}:start -->', f'<!-- layer:{slug}:{planet}:end -->'
block = f'{start}\n{section.strip()}\n{end}'
if start in text and end in text:
before, rest = text.split(start, 1)
_, after = rest.split(end, 1)
return before + block + after
text = text.rstrip('\n')
ends = list(re.finditer(r'<!-- layer:[^>]*:end -->', text))
if ends:
cut = ends[-1].end()
return text[:cut] + '\n\n' + block + text[cut:] + '\n'
if CARD_HEADING not in text.split('\n'):
text += f'\n\n{CARD_HEADING}\n\n{CARD_INTRO}'
return text + '\n\n' + block + '\n'
def publish_layer(layer: Layer, opts: Options, hub: HubStore) -> int:
planet = opts.planet
if planet not in layer.planets:
print(f'{layer.slug}: {layer.planets[0].capitalize()}-only layer; there is nothing to publish for '
f'{planet}. Refusing.', file=sys.stderr)
return 2
run = LayerRun(layer, planet, opts, hub)
pub = build_publication(run)
catalog_files, catalog_checks = build_catalog_publication(run)
pub['files'].update(catalog_files)
pub['checks'].extend(catalog_checks)
pub['ok'] = pub['ok'] and all(c['ok'] for c in catalog_checks)
tag = pub['tag']
tag_exists = tag in hub.tags()
print(f'== publish {layer.slug} {planet} -> {hub.repo_id} tag {tag} ==')
for c in pub['checks']:
print(f' [{"ok" if c["ok"] else "FAIL"}] {c["name"]}: {c["detail"]}')
print('files:')
for path, data in pub['files'].items():
print(f' {path} ({human(len(data))})')
print(' README.md (this layer\'s section replaced or added; the rest of the card is untouched)')
print('\n--- card section ---\n' + pub['card_section'] + '\n--------------------')
refusals = []
if not pub['ok']:
refusals.append('validation checks are failing: ' + ', '.join(
c['name'] for c in pub['checks'] if not c['ok']))
if tag_exists:
refusals.append(f'tag {tag} already exists (tags are never overwritten; bump VERSION)')
if opts.dry_run:
print('DRY RUN: nothing uploaded.' + (f' A real publish would refuse: {"; ".join(refusals)}'
if refusals else ''))
return 2 if refusals else 0
if refusals:
print('REFUSING to publish: ' + '; '.join(refusals), file=sys.stderr)
run.log.write('publish', status='refused', reasons=refusals)
return 2
started = time.monotonic()
for _ in range(CONFLICT_RETRIES):
head = hub.head()
readme = (hub.read_bytes('README.md', revision=head) or b'').decode('utf8')
files = dict(pub['files'])
files['README.md'] = update_card(readme, layer.slug, planet, pub['card_section']).encode()
try:
oid = hub.commit(files, f'Publish {tag}: layer {layer.layer_version} for {planet}',
parent_commit=head)
break
except Exception as exc:
if _is_conflict(exc):
continue
raise
else:
raise UploadError(f'gave up after {CONFLICT_RETRIES} commit conflicts')
info = hub.info(list(files), revision=oid)
for path, data in files.items():
remote = info.get(path)
if remote is None or not remote.matches(len(data), hashlib.sha256(data).hexdigest(),
git_blob_id(data)):
print(f'upload of {path} did not verify; NOT tagging', file=sys.stderr)
run.log.write('publish', status='verify_failed', path=path, commit=oid)
return 1
if tag in hub.tags():
print(f'tag {tag} appeared during the upload; not touching it', file=sys.stderr)
return 2
hub.create_tag(tag, oid, f'{layer.layer_version} {planet}: {pub["manifest"]["rows"]["total"]} rows')
interim = run.ctx.interim_dir
freed = du(interim)
if interim.exists():
shutil.rmtree(interim)
run.log.write('publish', status='published', tag=tag, commit=oid, files=sorted(files),
seconds=time.monotonic() - started, interim_bytes_deleted=freed)
print(f'published {tag} at {oid}' + (f'; deleted interim folder {interim} ({human(freed)})'
if freed else ''))
print(f'https://huggingface.co/datasets/{hub.repo_id}/tree/{tag}')
return 0
# --------------------------------------------------------------------------
# command line
# --------------------------------------------------------------------------
def parse_args(argv=None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument('slugs', help='layer slug(s), comma separated')
parser.add_argument('--planet', required=True, choices=sorted(PLANETS))
parser.add_argument('--bands', default=None, help='inclusive band range START-END (default: all); '
'touched band groups run in full')
parser.add_argument('--resume', action='store_true',
help='skip band groups already uploaded with this code_version')
parser.add_argument('--workers', type=int, default=4,
help='concurrent downloads inside a band group (1: strictly one at a time)')
parser.add_argument('--cache-max-gb', type=float, default=10.0,
help='hard cap on fetched items on disk at once (GB = 1e9 bytes)')
parser.add_argument('--retries', type=int, default=4,
help='attempts per item / Hub call before giving up')
parser.add_argument('--dry-run', action='store_true',
help='plan only (with --publish: show files, sizes and card text)')
parser.add_argument('--no-upload', action='store_true', help='write Parquet locally only')
parser.add_argument('--out', type=Path, default=DEFAULT_OUT, help='local output root')
parser.add_argument('--publish', action='store_true', help='validate, write the manifest, tag')
parser.add_argument('--cache-dir', type=Path, default=None,
help='where band-group caches live (default: a temp folder)')
parser.add_argument('--log-dir', type=Path, default=DEFAULT_LOG_DIR)
parser.add_argument('--interim-max-gb', type=float, default=50.0,
help='cap on data/interim/<planet>/<slug>/ built by prepare()')
parser.add_argument('--repo', default=REPO_ID, help='Hub dataset repo')
parser.add_argument('--layers-dir', type=Path, default=LAYERS_DIR, help=argparse.SUPPRESS)
return parser.parse_args(argv)
def main(argv=None, *, api=None, modules: dict | None = None) -> int:
global _DEFAULT_HUB
args = parse_args(argv)
slugs = [s.strip() for s in args.slugs.split(',') if s.strip()]
if args.publish and args.no_upload:
print('--publish cannot be combined with --no-upload', file=sys.stderr)
return 2
grid = planet_grid(args.planet)
bands = tf.parse_band_range(args.bands, len(grid.column_counts)) if args.bands else None
opts = Options(planet=args.planet, bands=bands, resume=args.resume, workers=max(1, args.workers),
cache_max_bytes=int(args.cache_max_gb * GB), retries=max(1, args.retries),
dry_run=args.dry_run, upload=not args.no_upload, out=args.out,
cache_dir=args.cache_dir, log_dir=args.log_dir,
interim_max_bytes=int(args.interim_max_gb * GB))
try:
layers = [Layer((modules or {}).get(slug) or load_module(slug, args.layers_dir), slug)
for slug in slugs]
except LayerError as exc:
print(f'error: {exc}', file=sys.stderr)
return 2
# with --no-upload nothing is read from or written to the Hub, except terrain values a layer
# asks for and has no local copy of (read_terrain falls back to a default client then)
hub = (HubStore(api, repo_id=args.repo, retries=opts.retries)
if opts.upload or args.publish or api is not None else None)
previous_hub = _DEFAULT_HUB
if hub is not None:
_DEFAULT_HUB = hub # read_terrain / earth_land_frac use the same Hub client
try:
if args.publish:
return max((publish_layer(layer, opts, hub) for layer in layers), default=0)
return run_layers(layers, opts, hub)
finally:
_DEFAULT_HUB = previous_hub
if __name__ == '__main__':
# Under `python -m` this file runs as __main__; hand over to the package module so layers that
# import `pipeline.layers.driver` share one copy of its classes and state.
_driver = importlib.import_module(__spec__.name) if __spec__ and __spec__.name != '__main__' else None
sys.exit((_driver.main if _driver is not None else main)())
"""Run dataset layer modules over the latband5km-v1 grid and upload them to the Hub as they finish.
Usage (from the repository root):
python -m pipeline.layers.driver <slug>[,<slug>...] --planet mars|earth [--bands START-END]
[--resume] [--workers N] [--cache-max-gb G] [--retries R] [--dry-run] [--no-upload] [--out DIR]
python -m pipeline.layers.driver <slug> --planet mars|earth --publish [--dry-run]
Layer module interface (``pipeline/layers/<slug>.py``)
------------------------------------------------------
``SOURCE`` dict: ``product``, ``version``, ``url``, ``licence``, ``planet`` (``mars`` | ``earth`` |
``both``) and optionally ``aux``, a list of further source dicts.
``COLUMNS`` dict: feature column -> ``{'dtype', 'unit', 'description', 'comparison', 'fill'}``.
``dtype`` defaults to ``float32``; ``comparison`` is one of :data:`COMPARISON_MODES`;
``fill`` is the value given to cells with no data (default NaN / null), for example
``0.0`` for a ``valid_frac`` column. The driver needs it to write rows for cells the
layer has no data for, and ``--publish`` needs units and comparison modes.
``plan(band_group, ctx)`` -> list of source items. An item is an :class:`Item`, a dict of
:class:`Item` fields, or a URL string. ``[]`` means "no source data": every cell gets
the fill values and the missing flag, and ``reduce`` is not called.
``reduce(band_group, items, ctx)`` -> ``pyarrow.Table`` keyed by ``region_id`` holding feature
columns (and optionally ``quality_flags``) only. ``items`` is an :class:`Items`
view: iterate it to stream items through the cache (each item is fetched when
reached and deleted when the loop moves on), or use ``items.get(key)`` /
``items.release(key)`` / ``items.all()`` for random access. Cells missing from the
table get the fill values and the missing flag.
Asset catalog (optional, see ``docs/asset_catalog.md`` and ``pipeline/catalog/``):
* An item from ``plan()`` may carry ``asset={...}`` (uri, footprint, geotransform, time range, ...).
The driver turns those into ``assets`` rows.
* ``reduce()`` may return ``(feature_table, coverage_table)``, the second holding ``region_id``,
``asset_id``, ``coverage_frac``. Without it the driver computes ``coverage_frac`` from the item
footprints and the grid, vectorised per band group (items with ``link_regions=False`` or
``covers_planet=True`` get no ``region_assets`` rows).
* Per band group the same commit carries ``catalog/region_assets/planet=<p>/layer=<slug>/band_group=NNN.parquet``
and ``catalog/assets_staging/...`` (that group's assets rows); ``--publish`` merges the staging files
into ``catalog/assets/planet=<p>/layer=<slug>.parquet`` (deduplicated by ``asset_id``).
Optional:
``prepare(ctx)`` one-time work before band groups run: small downloads into ``ctx.raw_dir``
(``data/raw/<planet>/<slug>/``, see ``ctx.download``) or streaming global
sources into ``ctx.interim_dir`` (``data/interim/<planet>/<slug>/``, capped by
``--interim-max-gb``, never uploaded, deleted after a successful publish).
``finalize(ctx)`` whole-planet post-pass. Reads band groups with ``ctx.read_layer(g, columns)``
over ``ctx.band_groups`` and writes extra column sets with
``ctx.write_extra(name, g, table)``; each name must be declared in
``EXTRA_COLUMNS = {name: COLUMNS-style dict}``.
``PASS_GROUP`` name shared by layers that read the same expensive source. Layers named
together on the command line with the same PASS_GROUP run in one pass: each
item is fetched once and handed to every layer that planned it.
``MISSING_FLAG`` quality flag for cells with no data: a string (default ``no_source``) or
``callable(band_group, missing_cells_table, ctx) -> list[str]`` (e.g. to say
``ocean`` using :func:`earth_land_frac`).
``VERSION`` default ``v0.1``; the layer version is ``<slug>-<VERSION>``.
``CROSSWALKS`` file names (next to the module) hashed into code_version and uploaded on publish.
``LIMITATIONS`` list of strings for the manifest and the dataset card.
``validate(summary, ctx)`` -> list of ``(name, ok, detail)``: layer-specific publish checks.
What the driver guarantees
--------------------------
* One file per band group of 100 bands, holding exactly one row per grid cell of the group, in grid
order, with the standard metadata columns (:data:`LEADING_COLUMNS`, :data:`TRAILING_COLUMNS`).
* The cache never holds more than ``--cache-max-gb``: every byte is charged before it is written,
and the cache is wiped after each band group.
* A failed download is never turned into NaNs. Transient errors are retried with exponential
backoff; after ``--retries`` attempts the band group stops and nothing is written for it. Only an
item planned with ``required=False`` may be *absent* (HTTP 404), and the reduce sees that.
* Uploads are one Hub commit per band group per layer, holding the Parquet file and the updated
progress file together, so a crash leaves either both or neither. The local file is deleted only
after the remote copy is re-listed and its size and hash match.
* ``--resume`` skips a band group only when the progress file records it with the current
code_version and the remote file matches the recorded size and hash.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib
import importlib.util
import io
import json
import math
import os
import random
import re
import shutil
import socket
import sys
import tempfile
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import http.client