starman / code-windows /mars_terrain.py
enzeeoai's picture
Super-squash history (latest files kept, was 8ef726a569)
d922ac9
Raw History Blame Contribute Delete
50.8 kB
"""Single-pass, band-by-band global terrain features on the latband5km-v1 grid. Source: the MOLA-HRSC Blended DEM (200 m/pixel simple-cylindrical GeoTIFF), described by ``source_manifest.json`` next to the raster. The grid is the permanent latitude-band index from :mod:`planetary_grid`; this module never changes cell IDs, band edges or column counts. Each latitude band is read exactly once as a windowed strip of full-width pixel rows plus a two-row halo, equalized east-west to ~200 m of ground spacing, and reduced to per-cell statistics with pure array operations (no per-cell polygon rasterization). Output is one Parquet file per 100 bands. The planet-independent half of that work - block averaging, Horn slope, the per-cell reductions, the ``terrain-v0.2`` feature definitions and the Parquet assembly - lives in :mod:`terrain_features` and is shared verbatim with :mod:`earth_terrain`. What stays here is Mars: the manifest, the raster geometry, the spherical ground-spacing arithmetic and the read window. Usage: python mars_terrain.py --bands 1000-1099 --workers 4 python mars_terrain.py --bands 0-2133 --resume --workers 8 --out DIR python mars_terrain.py --bands 0-2133 --resume --workers 8 --out DIR \ --dem-url https://huggingface.co/datasets/enzeeoai/starman-mars-elevation/resolve/main/\ Mars_HRSC_MOLA_BlendDEM_Global_200mp_v2_cog.tif ``--dem-url`` streams pixels from a remote lossless COG instead of opening a local file, so a worker never needs the ~8 GB source raster on disk; ``--source`` still supplies ``source_manifest.json`` (nodata, body radius and ``source_checksum``, the hash of the original uncompressed GeoTIFF - streaming its COG does not change what that original file was). Reads are retried (``--retries``) under the same anonymous/no-internal-retry GDAL options :mod:`earth_terrain` uses for its own streaming reads, and the remote file's Hub LFS hash is checked against its publish-time verification report before any pixel is read. Conventions and deliberate choices are documented in ``band_context`` and ``process_band``; the ones that matter for interpretation are: * Statistics are computed on the *analysis* grid (after east-west block averaging), so ``n_samples_200m`` counts analysis pixels. ``n_native_samples`` and ``n_valid_native_samples`` carry the native pixel accounting, which partitions the raster exactly. * The block factor ``k`` is a function of latitude, but one ``k`` is used for every row of a band's read window so the three rows of a Horn stencil stay column-aligned. ``k`` is taken at the band's centre latitude; where the rows of the window do not all agree the cell is flagged ``mixed_block_factor``. * Elevations are passed through as published (metres, areoid per the manifest's own inference) and are context only. """ from __future__ import annotations import argparse import json import math import re import sys import time from concurrent.futures import ProcessPoolExecutor, as_completed from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path import numpy as np import rasterio from rasterio.windows import Window import terrain_features as tf import quarter_cells as qc import earth_terrain as et # noqa: F401 (GDAL_ENV, _OpenMosaics, read_with_retries, ReadStats: reused, not forked) from planetary_grid import PLANETS, VERSION as GRID_VERSION, PlanetBandGrid # Re-exported so that every name this module published before the shared # feature code was split out of it still resolves here. Callers may import # either module; these are the same objects. from terrain_features import ( # noqa: F401 ANALYSIS_SPACING_M, BANDS_PER_GROUP, BLOCK_HALO, COUNT_FEATURES, ELEV_PERCENTILES, FEATURE_VERSION, FLOAT_FEATURES, LOW_COVERAGE_FRACTION, POLAR_DISTORTION_LAT, RELIEF_WINDOW, ROW_HALO, SLOPE_PERCENTILES, SLOPE_THRESHOLDS, AnalysisSegment, _constant, _sum, _window_extreme, block_average_ew, detrended_roughness, ew_block_factor, group_is_complete, group_path, grouped_percentiles, horn_slope_deg, local_relief, parse_band_range, plan_groups, wrap_blocks, write_atomic, ) PLANET = 'mars' DEFAULT_SOURCE_DIR = Path('data/raw/mars/mola_hrsc') DEFAULT_OUT_DIR = Path('data/processed/mars/terrain') # The private HF dataset holding the lossless Mars DEM COG that --dem-url # streams from. publish_dem_hf.py uploads it (REPO_ID) and MarsElevationSource # below resolves cells against it (ELEVATION_REPO); these three must agree. DEFAULT_HF_REPO = 'enzeeoai/starman-mars-elevation' DEFAULT_HF_COG = 'Mars_HRSC_MOLA_BlendDEM_Global_200mp_v2_cog.tif' DEFAULT_RETRIES = 4 @dataclass(frozen=True) class _StreamRetry: """Just enough of earth_terrain.EarthSource's shape for et.read_with_retries. et.read_with_retries only ever reads ``source.retries`` and ``source.retry_backoff_s``; it does not need a whole EarthSource, whose other fields (tiles, zones, water...) are Earth-only and meaningless here. """ retries: int = DEFAULT_RETRIES retry_backoff_s: float = 1.0 # -------------------------------------------------------------------------- # provenance # -------------------------------------------------------------------------- def code_version(path: Path | None = None) -> str: """SHA-256 over this driver and ``terrain_features.py``, in that order. Every row names the code that made it. The feature maths lives in ``terrain_features``, so hashing the driver alone would leave a change to a feature definition invisible in provenance. ``path`` overrides the driver file only; the shared module is always included. Rows written before the split (feature_version ``terrain-v0.1`` at commit ccdb979) carry the digest of ``mars_terrain.py`` alone and will not equal this value; that is expected, not a mismatch in the data. """ driver = Path(path) if path else Path(__file__).resolve() return tf.code_version(driver, Path(tf.__file__).resolve()) def dem_gdal_path(url: str) -> str: """A GDAL-openable path for a DEM source: local paths pass through unchanged, an http(s) URL gets the ``/vsicurl/`` prefix it needs for a windowed read.""" url = str(url) if url.startswith(('http://', 'https://')): return f'/vsicurl/{url}' return url def hf_resolve_url(repo_id: str, filename: str, revision: str = 'main') -> str: """The direct-download URL of a file in a (possibly private) HF dataset repo.""" return f'https://huggingface.co/datasets/{repo_id}/resolve/{revision}/{filename}' def load_source_manifest(source_dir: Path, dem_override: str | None = None) -> dict: """Read ``source_manifest.json`` and pull out the fields the pipeline needs. ``dem_override`` points pixel reads at a remote COG (a URL, or an already GDAL-prefixed path) instead of the manifest's own local file. Every other field, ``source_checksum`` included, still comes from the manifest: that checksum names the original uncompressed GeoTIFF the COG was losslessly made from, not the COG itself, and streaming pixels from the COG does not change what the original file was. """ source_dir = Path(source_dir) manifest_path = source_dir / 'source_manifest.json' manifest = json.loads(manifest_path.read_text(encoding='utf8')) try: product = manifest['product'] info = { 'manifest_path': manifest_path, 'dem_path': dem_gdal_path(dem_override) if dem_override else source_dir / product['file'], 'streaming': bool(dem_override), 'source_product': str(product['name']), 'source_version': str(product['version']), 'source_checksum': str(manifest['sha256']['value']), 'nodata': float(manifest['nodata']['value']), 'body_radius_m': float(manifest.get('crs', {}).get('body_radius_m', PLANETS[PLANET]['a_m'])), } except KeyError as exc: raise ValueError(f'{manifest_path} is missing required key {exc}') from exc if not info['streaming'] and not info['dem_path'].exists(): raise FileNotFoundError(f'DEM named by the manifest is missing: {info["dem_path"]}') radius = PLANETS[PLANET]['a_m'] if not math.isclose(info['body_radius_m'], radius, rel_tol=1e-9): raise ValueError( f'Manifest body radius {info["body_radius_m"]} disagrees with the grid reference {radius}') return info # -------------------------------------------------------------------------- # grid / raster geometry # -------------------------------------------------------------------------- def band_row_range(lat_top: float, res_deg: float, height: int, lat_min: float, lat_max: float) -> tuple[int, int]: """Pixel rows whose CENTRE latitude lies in [lat_min, lat_max). Returns a half-open ``(start, stop)`` clipped to the raster. Adjacent bands share an edge value exactly, so the row sets partition the raster with no gap and no overlap. """ first = math.floor((lat_top - lat_max) / res_deg - 0.5) + 1 last = math.floor((lat_top - lat_min) / res_deg - 0.5) return max(first, 0), min(last + 1, height) @dataclass(frozen=True) class RasterContext: """Immutable description of the DEM, validated once per worker.""" path: Path width: int height: int lat_top: float lon_left: float res_deg: float nodata: float radius_m: float @property def dy_m(self) -> float: """North-south ground spacing of one pixel row, in metres.""" return math.radians(self.res_deg) * self.radius_m def row_center_lat(self, rows: np.ndarray) -> np.ndarray: return self.lat_top - (np.asarray(rows, dtype=np.float64) + 0.5) * self.res_deg def col_center_lon(self, cols: np.ndarray) -> np.ndarray: return self.lon_left + (np.asarray(cols, dtype=np.float64) + 0.5) * self.res_deg def local_metres(self, d_lon: np.ndarray, lat: np.ndarray, center_lat: float) -> tuple[np.ndarray, np.ndarray]: """East/north offsets in metres on the Mars indexing sphere.""" x_m = np.radians(d_lon) * self.radius_m * np.cos(np.deg2rad(lat)) y_m = np.radians(lat - center_lat) * self.radius_m return x_m, y_m def raster_context(info: dict, *, retry: _StreamRetry | None = None) -> RasterContext: """Open the DEM only to validate its geometry against the manifest. The caller must already hold the right ``rasterio.Env`` (``streaming_gdal_env`` for a remote path; the default env for a local one) for the duration of this call. ``retry`` retries a failed *open* - a connection that never completes - which is a different, earlier failure than the per-window read failures ``et.read_with_retries`` retries; with ``retry=None`` this tries exactly once, matching the previous behaviour byte for byte. """ attempts = max(retry.retries, 1) if retry else 1 delay = retry.retry_backoff_s if retry else 0.0 for attempt in range(1, attempts + 1): try: with rasterio.open(info['dem_path']) as src: transform = src.transform if transform.b or transform.d: raise ValueError('A north-up, unrotated geographic raster is required') res_x, res_y = transform.a, -transform.e if res_x <= 0 or not math.isclose(res_x, res_y, rel_tol=1e-12): raise ValueError(f'Square pixels are required, got {res_x} x {res_y}') if src.nodata is not None and not math.isclose(src.nodata, info['nodata']): raise ValueError( f'Raster nodata {src.nodata} disagrees with the manifest value {info["nodata"]}') width, height = src.width, src.height span = width * res_x if abs(span - 360.0) > res_x: raise ValueError( f'Longitude coverage must be global for the wrap halo; got {span:.6f} degrees') path = info['dem_path'] if info.get('streaming') else Path(info['dem_path']) return RasterContext( path=path, width=width, height=height, lat_top=transform.f, lon_left=transform.c, res_deg=res_x, nodata=info['nodata'], radius_m=info['body_radius_m'], ) except Exception: if attempt == attempts: raise time.sleep(delay) delay *= 2 raise AssertionError('unreachable') # -------------------------------------------------------------------------- # streaming the DEM from a remote COG (HF Job path; see module docstring) # -------------------------------------------------------------------------- def streaming_gdal_env(token: str | None, gdal_cache_mb: int) -> rasterio.Env: """``rasterio.Env`` for a remote read. Reuses ``et.GDAL_ENV`` as-is: it disables GDAL's own HTTP retry (this module's retry loop is the only one) and turns off directory probing, neither of which is specific to S3 and both of which apply equally to the HF-hosted COG. Only the private-repo bearer header and the cache size are added on top. """ options = dict(et.GDAL_ENV) options['GDAL_CACHEMAX'] = int(gdal_cache_mb) * 2 ** 20 if token: options['GDAL_HTTP_HEADERS'] = f'Authorization: Bearer {token}' return rasterio.Env(**options) def hf_token(explicit: str | None) -> str | None: """Resolve a Hub token: an explicit value, then $HF_TOKEN, then the cached login.""" import os if explicit: return explicit env_token = os.environ.get('HF_TOKEN') if env_token: return env_token from huggingface_hub import get_token return get_token() def verify_remote_cog(repo_id: str, filename: str, token: str | None) -> str: """Refuse to stream unless the Hub's own copy still matches its verification report. The same check ``publish_dem_hf.py`` makes before it will publish - ``sha256_file(cog) != report['cog']['sha256']`` - just moved to the other end: there the trusted value is the file on disk, here it is whatever this repo's LFS object actually is right now, read from ``repo_info`` rather than a download. Returns the verified hash on success. """ from huggingface_hub import HfApi, hf_hub_download report_path = hf_hub_download(repo_id, 'cog_verification.json', repo_type='dataset', token=token) report = json.loads(Path(report_path).read_text(encoding='utf8')) expected = report['cog']['sha256'] api = HfApi(token=token) info = api.repo_info(repo_id, repo_type='dataset', files_metadata=True, token=token) sibling = next((s for s in info.siblings if s.rfilename == filename), None) if sibling is None or sibling.lfs is None: raise RuntimeError(f'{filename} is not an LFS file in {repo_id}; refusing to stream it') if sibling.lfs.sha256 != expected: raise RuntimeError( f'{filename} in {repo_id}: Hub LFS sha256 {sibling.lfs.sha256} does not match the ' f'verified COG hash {expected} from cog_verification.json; refusing to stream it') return expected @dataclass class _RemoteBand1Reader: """Duck-types rasterio's ``.read(1, window=...)`` over a retrying remote read. ``read_band_strip`` and ``process_band`` only ever call ``src.read(1, window=...)``; handing this object to them in place of an open dataset is what lets a streaming run reuse them completely unchanged, instead of forking a second copy of the band-reading logic. """ mosaics: 'et._OpenMosaics' path: str retry: _StreamRetry stats: 'et.ReadStats' def read(self, band_index: int, window: Window): assert band_index == 1, 'the DEM has exactly one band' return et.read_with_retries( self.mosaics, self.path, window.row_off, window.height, window.col_off, window.width, self.retry, self.stats, what=f'rows {window.row_off}-{window.row_off + window.height}') # -------------------------------------------------------------------------- # array stages # -------------------------------------------------------------------------- def read_band_strip(src, ctx: RasterContext, row_start: int, row_stop: int, halo: int = ROW_HALO) -> tuple[np.ndarray, np.ndarray]: """Windowed read of a band's rows plus a halo; nodata becomes NaN. Rows beyond the raster (only at the poles) are returned as all-NaN, which makes every stencil that needs them NaN as well. """ want_start, want_stop = row_start - halo, row_stop + halo have_start, have_stop = max(want_start, 0), min(want_stop, ctx.height) out = np.full((want_stop - want_start, ctx.width), np.nan, dtype=np.float64) if have_stop > have_start: window = Window(0, have_start, ctx.width, have_stop - have_start) data = src.read(1, window=window) sentinel = np.asarray(ctx.nodata).astype(data.dtype) if float(sentinel) != ctx.nodata: raise ValueError(f'nodata {ctx.nodata} is not representable in {data.dtype}') block = data.astype(np.float64) block[data == sentinel] = np.nan out[have_start - want_start:have_stop - want_start] = block return out, ctx.row_center_lat(np.arange(want_start, want_stop)) # -------------------------------------------------------------------------- # one band # -------------------------------------------------------------------------- def band_context(grid: PlanetBandGrid, ctx: RasterContext, band: int) -> dict: """Everything about a band that does not need pixels.""" lat_min = float(grid.edges_deg[band]) lat_max = float(grid.edges_deg[band + 1]) n_cells = int(grid.column_counts[band]) row_start, row_stop = band_row_range(ctx.lat_top, ctx.res_deg, ctx.height, lat_min, lat_max) center_lat = 0.5 * (lat_min + lat_max) return { 'band': band, 'lat_min': lat_min, 'lat_max': lat_max, 'center_lat': center_lat, 'n_cells': n_cells, 'lon_step': 360.0 / n_cells, 'row_start': row_start, 'row_stop': row_stop, 'block_factor': ew_block_factor(center_lat, max_factor=ctx.width), } def process_band(src, grid: PlanetBandGrid, ctx: RasterContext, band: int, quarters: bool = False) -> dict: """Read one band once and reduce it to per-cell features. Stages follow the read: wrap east-west, nodata to NaN (done in the read), equalize east-west ground spacing, Horn slope and 1 km relief on the padded array, then drop the halos and assign analysis pixels to grid columns by their centre longitude. """ meta = band_context(grid, ctx, band) n_cells = meta['n_cells'] k = meta['block_factor'] native, row_lats = read_band_strip(src, ctx, meta['row_start'], meta['row_stop']) blocks, source_per_block, valid_per_block = block_average_ew(native, k) del native n_blocks = blocks.shape[1] block_cols = np.arange(n_blocks, dtype=np.int64) * k + (source_per_block - 1) / 2.0 block_lons = ctx.col_center_lon(block_cols) normalized = (block_lons + 180.0) % 360.0 - 180.0 column_of_block = np.clip(((normalized + 180.0) / meta['lon_step']).astype(np.int64), 0, n_cells - 1) interior_rows = slice(ROW_HALO, blocks.shape[0] - ROW_HALO) lats = row_lats padded = wrap_blocks(blocks) # True east-west stencil spacing, per output row and column. Unwrapping the # halo longitudes (rather than assuming 2k pixels) absorbs both the short # final block and the raster's incomplete longitude ring at the seam. lon_padded = np.concatenate([block_lons[-BLOCK_HALO:] - 360.0, block_lons, block_lons[:BLOCK_HALO] + 360.0]) span_deg = lon_padded[2:] - lon_padded[:-2] dx_m = np.outer(np.cos(np.deg2rad(lats[1:-1])), span_deg) * (math.radians(1.0) * ctx.radius_m / 2.0) slope_full = horn_slope_deg(padded, dx_m, ctx.dy_m) # shrinks by 1 each side del dx_m slope = slope_full[1:-1, 1:-1] relief = local_relief(padded) # shrinks by 2 each side elevation = padded[interior_rows, BLOCK_HALO:padded.shape[1] - BLOCK_HALO] del padded, slope_full n_rows = elevation.shape[0] lats_interior = lats[ROW_HALO:len(lats) - ROW_HALO] # native pixel accounting: exact, and independent of the analysis grid valid_interior = valid_per_block[interior_rows] n_native_samples = np.rint(tf._sum( column_of_block, source_per_block * float(n_rows), n_cells)).astype(np.int64) n_valid_native_samples = np.rint(tf._sum( np.broadcast_to(column_of_block, valid_interior.shape).ravel(), valid_interior.ravel().astype(np.float64), n_cells)).astype(np.int64) segment = AnalysisSegment( elevation=elevation, slope=slope, relief=relief, column_of_block=column_of_block, block_lons=normalized, row_lats=lats_interior) row = tf.cell_features( [segment], n_cells, center_lat=meta['center_lat'], lon_step=meta['lon_step'], n_native_samples=n_native_samples, n_valid_native_samples=n_valid_native_samples, local_metres=ctx.local_metres) row['ew_samples_averaged'][:] = k row_factors = {ew_block_factor(float(lat), max_factor=ctx.width) for lat in lats_interior} row['quality_flags'] = quality_flags( meta['center_lat'], row['valid_frac_200m'], row['n_samples_200m'], mixed_factor=row_factors != {k}, degenerate=n_blocks < RELIEF_WINDOW) row['band'] = np.full(n_cells, band, dtype=np.int32) row['column'] = np.arange(n_cells, dtype=np.int32) if quarters: # bands run south to north: the northern half borders band + 1 row['quarters'] = band_quarters( segment, ctx, meta, source_per_block, valid_interior, k, n_cells_anchor=(int(grid.column_counts[band + 1]) if band + 1 < len(grid.column_counts) else None)) return row def quality_flags(center_lat: float, valid_frac_200m: np.ndarray, n_samples_200m: np.ndarray, mixed_factor: bool, degenerate: bool) -> list[str]: """Per-cell advisory flags, semicolon separated, empty string when clean.""" return tf.quality_flags(center_lat, valid_frac_200m, n_samples_200m, mixed_factor=mixed_factor, degenerate=degenerate) # -------------------------------------------------------------------------- # 2.5 km quarter cells (additive merge inputs, see quarter_cells.py) # -------------------------------------------------------------------------- def _quarter_native_counts(slots_per_block, rows_mask, source_per_block, valid_interior, n_slots): """Native pixel counts per quarter slot, from the arrays the cell counts use. ``slots_per_block`` is the quarter slot of each block for ONE quarter row. Summing these over both quarter rows reproduces the published per-column counts exactly, because each is the same product, only split by row. """ n_rows = int(rows_mask.sum()) native = tf._sum(slots_per_block, source_per_block * float(n_rows), n_slots) valid = tf._sum(slots_per_block, valid_interior[rows_mask].sum(axis=0).astype(np.float64), n_slots) return np.rint(native), np.rint(valid) def _quarter_records(feats, band, anchor_band, n_cells, planet_prefix): """Flatten per-slot arrays into key + feature columns, dropping empty slots.""" n_slots = len(feats['n_samples_200m']) keep = np.flatnonzero(feats['n_samples_200m'] > 0) qcol = keep % 2 column = (keep // 2) % n_cells qrow = keep // (2 * n_cells) out = { 'quarter_id': [qc.quarter_id(planet_prefix, band, anchor_band, int(c), int(r), int(q)) for c, r, q in zip(column, qrow, qcol)], 'band': np.full(len(keep), band, dtype=np.int32), 'anchor_band': np.full(len(keep), anchor_band, dtype=np.int32), 'column': column.astype(np.int32), 'qrow': qrow.astype(np.int32), 'qcol': qcol.astype(np.int32), 'n_dropped_empty': n_slots - len(keep), } for name in (*qc.QUARTER_FLOAT_COLUMNS, *qc.QUARTER_INT_COLUMNS, *qc.QUARTER_LIST_COLUMNS): if name in feats: out[name] = feats[name][keep] return out def band_quarters(segment: AnalysisSegment, ctx: RasterContext, meta: dict, source_per_block: np.ndarray, valid_interior: np.ndarray, k: int, n_cells_anchor: int | None) -> dict: """Per-quarter additive statistics for one band: own grid and anchor grid. Returns ``{'own': records, 'anchor': records or None}``; quarters with no analysis pixel are dropped. ``segment`` and ``valid_interior`` are the halo-free arrays ``process_band`` already holds. The anchor grid is the next band's (``band + 1``, to the north); the north-pole band has none, hence no anchor quarters. """ prefix = PLANETS[PLANET]['prefix'] band, center_lat = meta['band'], meta['center_lat'] lon_scale = lambda lat: math.radians(1.0) * ctx.radius_m * np.cos(np.radians(lat)) lat_scale = math.radians(1.0) * ctx.radius_m north = qc.qrow_of_row(segment.row_lats, center_lat) == 0 def finish(feats, slots_by_row, n_slots, n_cells, anchor_band): native = np.zeros(n_slots) valid = np.zeros(n_slots) for rows_mask, slots in slots_by_row: a, b = _quarter_native_counts(slots, rows_mask, source_per_block, valid_interior, n_slots) native += a valid += b feats['n_native_samples'] = native feats['n_valid_native_samples'] = valid feats['ew_samples_weighted'] = k * feats['n_samples_200m'] return _quarter_records(feats, band, anchor_band, n_cells, prefix) # own grid: 2 quarter rows x n_cells x 2 quarter columns n_cells, lon_step = meta['n_cells'], meta['lon_step'] n_slots = 4 * n_cells feats = qc.quarter_features( [segment], n_slots, slots_of_segment=lambda s: qc.own_grid_slots( s, n_cells=n_cells, lon_step=lon_step, center_lat=center_lat), origin_lon=qc.slot_origin_lon(n_cells, lon_step, n_slots), origin_lat=center_lat, lon_scale=lon_scale, lat_scale=lat_scale) cell = qc.cell_of_block(segment.block_lons, lon_step, n_cells) qcol = qc.qcol_of_block(segment.block_lons, lon_step) per_row = [(north, qc.slot_index(0, cell, qcol, n_cells)), (~north, qc.slot_index(1, cell, qcol, n_cells))] own = finish(feats, per_row, n_slots, n_cells, band) anchor = None if n_cells_anchor is not None and north.any(): a_step = 360.0 / n_cells_anchor a_slots = 2 * n_cells_anchor # Only the northern rows are handed over, so no pixel carries a "skip" slot. north_segment = AnalysisSegment( elevation=segment.elevation[north], slope=segment.slope[north], relief=segment.relief[north], column_of_block=segment.column_of_block, block_lons=segment.block_lons, row_lats=segment.row_lats[north]) feats = qc.quarter_features( [north_segment], a_slots, slots_of_segment=lambda s: qc.anchor_grid_slots( s, n_cells_anchor=n_cells_anchor, lon_step_anchor=a_step, center_lat=center_lat), origin_lon=qc.slot_origin_lon(n_cells_anchor, a_step, a_slots), origin_lat=center_lat, lon_scale=lon_scale, lat_scale=lat_scale) a_cell = qc.cell_of_block(segment.block_lons, a_step, n_cells_anchor) a_qcol = qc.qcol_of_block(segment.block_lons, a_step) anchor = finish(feats, [(north, qc.slot_index(0, a_cell, a_qcol, n_cells_anchor))], a_slots, n_cells_anchor, band + 1) return {'own': own, 'anchor': anchor} def build_quarter_table(results: list[dict], provenance: dict, bands: list[int]): """One Parquet table of quarter records from ``band_quarters`` results. ``bands`` is every band the group covered, dropped-quarter bands included, and is stored in the metadata so ``--resume`` can tell a finished group from a partial one the same way it does for the terrain file. """ import pyarrow as pa records = [r[part] for r in results for part in ('own', 'anchor') if r[part] is not None] def cat(name, dtype=None): parts = [np.asarray(r[name]) for r in records] return np.concatenate(parts) if parts else np.zeros(0, dtype=dtype) n = sum(len(r['band']) for r in records) data = { 'quarter_id': pa.array([q for r in records for q in r['quarter_id']], type=pa.string()), 'planet': tf._constant(PLANET, n), } for name in qc.QUARTER_KEY_COLUMNS[2:]: data[name] = pa.array(cat(name, np.int32).astype(np.int32)) for name in qc.QUARTER_FLOAT_COLUMNS: if records and name in records[0]: data[name] = pa.array(cat(name).astype(np.float64)) for name in qc.QUARTER_INT_COLUMNS: data[name] = pa.array(cat(name, np.int64).astype(np.int64)) for name in qc.QUARTER_LIST_COLUMNS: # header-only files keep the int32 list type audit_quarter_table expects width = records[0][name].shape[1] if records else qc.N_BINS flat = (cat(name, np.int32).astype(np.int32).reshape(-1, width) if records else np.zeros((0, width), dtype=np.int32)) data[name] = pa.FixedSizeListArray.from_arrays( pa.array(flat.ravel(), type=pa.int32()), width) data['quarter_version'] = tf._constant(qc.QUARTER_VERSION, n) data['code_version'] = tf._constant(provenance['code_version'], n) # The terrain code_version above does not cover quarter_cells.py, # which decides every number in this table. This one does. version = qc.quarter_code_version(Path(__file__)) data['quarter_code_version'] = tf._constant(version, n) table = pa.table(data) return table.replace_schema_metadata({ 'quarter_version': qc.QUARTER_VERSION, 'bands': json.dumps(sorted(int(b) for b in bands)), # also in the metadata, so --resume can date a header-only file too 'quarter_code_version': version, 'provenance': json.dumps(provenance, sort_keys=True), }) def quarter_path(out_dir: Path, group: int) -> Path: return Path(out_dir) / qc.QUARTER_VERSION / f'band_group={group:03d}.parquet' def quarter_group_is_current(path: Path, wanted: list[int]) -> bool: """A resumable quarter group: complete, AND written by this code. Mirrors ``earth_terrain.quarter_group_is_current``. ``group_is_complete`` only reads the band list: a shard resumes from whatever an earlier run left on the Hub, so without this a re-run would keep every group the old code finished and redo only the rest - one release with two ``quarter_code_version`` values. A file that predates the metadata key is stale by definition. """ if not group_is_complete(path, wanted): return False import pyarrow.parquet as pq try: metadata = pq.read_schema(path).metadata or {} written_by = metadata[b'quarter_code_version'].decode() except Exception: return False return written_by == qc.quarter_code_version(Path(__file__)) # -------------------------------------------------------------------------- # a cell back to the elevation samples behind it # -------------------------------------------------------------------------- # # The terrain table is an aggregate: it says how many elevation samples stand # behind a cell, never which ones. These helpers close that gap, and they are # the single implementation of the rule - ``build_grid_windows.py`` writes the # published window table from ``band_windows`` and :func:`resolve_region` # answers for one cell from the same function, so the table and the resolver # cannot drift apart. Nothing here is re-derived from the grid definition: the # rows come from :func:`band_row_range` through :func:`band_context` and the # columns from the block arithmetic :func:`process_band` uses. # # No pixel is read and no raster is opened. A window is geometry, so a consumer # can go from a ``region_id`` to a read window without fetching 3.8 GB first. # The published raster, as recorded in ``source_manifest.json`` and in # ``grid/grid_manifest.json`` on the Hub. The COG is pixel-identical to the # original GeoTIFF, verified strip by strip, so its geometry is the same. RASTER_WIDTH = 106694 RASTER_HEIGHT = 53347 RASTER_RES_DEG = 0.003374120830641 RASTER_LAT_TOP = 90.0 RASTER_LON_LEFT = -180.0 RASTER_NODATA = -32768.0 ELEVATION_REPO = 'enzeeoai/starman-mars-elevation' ELEVATION_FILE = 'Mars_HRSC_MOLA_BlendDEM_Global_200mp_v2_cog.tif' # The commit the published windows are built against. Pinned, not 'main': the # windows are indices into one exact file, so a later commit that replaced it # would silently re-point every cell. ELEVATION_REVISION = '3c2bf831942cccf9e9ccc116c5ccc9ecd1e3c275' ELEVATION_SHA256 = 'a78e40a79295d2cd0219362b257d103e788f895278ea4764ddd1aa1a89e9bc63' _REGION_RE = re.compile(r'([A-Za-z]+)_(\d{4})_(\d{5})') def parse_region_id(grid: PlanetBandGrid, region_id: str) -> tuple[int, int]: """``M_1067_01234`` -> ``(1067, 1234)``, checked against the grid. Mirrors :func:`earth_terrain.parse_region_id`. A band or column outside the grid is an error rather than a clamped guess, because a wrong cell would return a perfectly well-formed window over the wrong part of Mars. """ match = _REGION_RE.fullmatch(str(region_id).strip()) if not match: raise ValueError(f'{region_id!r} is not a region_id') prefix, band, column = match.group(1), int(match.group(2)), int(match.group(3)) if prefix != PLANETS[PLANET]['prefix']: raise ValueError(f'{region_id!r} is not a Mars region_id') if not 0 <= band < len(grid.column_counts): raise ValueError(f'{region_id!r}: band {band} is outside the grid') if not 0 <= column < int(grid.column_counts[band]): raise ValueError(f'{region_id!r}: band {band} has only ' f'{int(grid.column_counts[band])} columns') return band, column def block_layout(width: int, k: int) -> tuple[np.ndarray, np.ndarray]: """Native start column and native width of each block, as ``block_average_ew`` lays them out. The last block is short wherever ``k`` does not divide the width, which is why this is taken from the layout rather than assumed to be ``k`` wide. """ n_blocks = -(-width // k) spb = np.full(n_blocks, k, dtype=np.int64) spb[-1] = k - (n_blocks * k - width) return np.arange(n_blocks, dtype=np.int64) * k, spb def band_windows(ctx: RasterContext, meta: dict) -> np.ndarray: """``(n_cells, 4)`` int64 ``[row_min, row_max, col_min, col_max]`` for one band. Half-open, row 0 = north, column 0 = -180 degrees east. The arithmetic is :func:`process_band`'s verbatim: blocks of ``k`` native columns with a short final block, the block-centre longitude, and the same ``column_of_block`` clip. A cell's window is the span from the first to the last block it owns, which is contiguous because the block-centre longitudes increase monotonically across the raster. """ n_cells, k = meta['n_cells'], meta['block_factor'] starts, spb = block_layout(ctx.width, k) n_blocks = len(starts) block_cols = np.arange(n_blocks, dtype=np.int64) * k + (spb - 1) / 2.0 block_lons = ctx.col_center_lon(block_cols) normalized = (block_lons + 180.0) % 360.0 - 180.0 cob = np.clip(((normalized + 180.0) / meta['lon_step']).astype(np.int64), 0, n_cells - 1) if np.any(np.diff(cob) < 0): raise AssertionError(f"band {meta['band']}: blocks are not column-monotone (seam wrap)") cells = np.arange(n_cells) first = np.searchsorted(cob, cells, side='left') last = np.searchsorted(cob, cells, side='right') # exclusive if np.any(last <= first): raise AssertionError(f"band {meta['band']}: a cell owns no block") out = np.empty((n_cells, 4), dtype=np.int64) out[:, 0], out[:, 1] = meta['row_start'], meta['row_stop'] out[:, 2] = starts[first] out[:, 3] = starts[last - 1] + spb[last - 1] return out @dataclass(frozen=True) class MarsElevationSource: """Where the Mars elevation samples live, and the geometry of that raster. Earth's :class:`earth_terrain.EarthSource` names a bucket and a tile index; Mars needs neither, because the whole planet is one file. The defaults are the published release: a pinned commit of a private Hub dataset holding a lossless COG of the MOLA-HRSC blend. """ repo_id: str = ELEVATION_REPO revision: str = ELEVATION_REVISION filename: str = ELEVATION_FILE sha256: str = ELEVATION_SHA256 width: int = RASTER_WIDTH height: int = RASTER_HEIGHT lat_top: float = RASTER_LAT_TOP lon_left: float = RASTER_LON_LEFT res_deg: float = RASTER_RES_DEG nodata: float = RASTER_NODATA radius_m: float = PLANETS[PLANET]['a_m'] @property def elevation_url(self) -> str: """``hf://`` URL of the COG, pinned to ``revision``.""" return f'hf://datasets/{self.repo_id}@{self.revision}/{self.filename}' @property def elevation_https_url(self) -> str: """The same file over HTTPS, for GDAL's ``/vsicurl/`` (private: needs a token).""" return (f'https://huggingface.co/datasets/{self.repo_id}/resolve/' f'{self.revision}/{self.filename}') def raster_context(self) -> RasterContext: """The geometry as :func:`process_band` sees it, without opening a file.""" return RasterContext(path=None, width=self.width, height=self.height, lat_top=self.lat_top, lon_left=self.lon_left, res_deg=self.res_deg, nodata=self.nodata, radius_m=self.radius_m) @classmethod def from_manifest(cls, source_dir: Path, **overrides) -> 'MarsElevationSource': """Build from ``source_manifest.json``, which records the raster the pipeline read. Used by the window builder so the published table is pinned to the manifest rather than to the constants above, and the two are checked against each other. Geometry only. ``repo_id``, ``revision``, ``filename`` and ``sha256`` keep their defaults, because the manifest describes the *original* uncompressed GeoTIFF - its ``sha256`` is that file's, not the COG's - and says nothing about where the COG is published. Pass them as ``overrides`` to point at a different copy. """ manifest = json.loads((Path(source_dir) / 'source_manifest.json').read_text(encoding='utf8')) raster, gt = manifest['raster'], manifest['raster']['geotransform'] fields = dict(width=int(raster['width']), height=int(raster['height']), lon_left=float(gt[0]), res_deg=float(gt[1]), lat_top=float(gt[3]), nodata=float(manifest['nodata']['value']), radius_m=float(manifest['crs']['body_radius_m'])) return cls(**{**fields, **overrides}) def resolve_region(region_id: str, source: MarsElevationSource | None = None, grid: PlanetBandGrid | None = None) -> dict: """Turn one ``region_id`` into the concrete elevation read behind it. Returns the file to open and the half-open window to read from it, with the same keys as :func:`earth_terrain.resolve_region` uses per tile. Mars needs only one entry where Earth needs a list: the planet is a single raster, so every cell is exactly one contiguous rectangle and there is no index of which tiles exist - every Mars cell has samples. ``row_off`` / ``col_off`` are offsets into the file itself, so they go straight into ``rasterio.windows.Window(col_off, row_off, n_cols, n_rows)``. ``n_rows * n_cols`` equals the cell's ``n_native_samples`` in the terrain table, and the windows of all cells tile the raster exactly. Raises ``ValueError`` for an unknown or malformed ``region_id``. A ``source`` whose geometry does not match the grid - a wrong ``res_deg`` or ``width`` - raises ``AssertionError`` from the window arithmetic instead: that is an internal invariant failing, not bad input. """ source = source or MarsElevationSource() grid = grid if grid is not None else PlanetBandGrid.build(PLANET) ctx = source.raster_context() band, column = parse_region_id(grid, region_id) meta = band_context(grid, ctx, band) row_min, row_max, col_min, col_max = (int(v) for v in band_windows(ctx, meta)[column]) return { 'region_id': region_id, 'band': band, 'column': column, 'elevation_repo': source.repo_id, 'elevation_revision': source.revision, 'elevation_file': source.filename, 'elevation_sha256': source.sha256, 'elevation_url': source.elevation_url, 'elevation_https_url': source.elevation_https_url, # the window inside the raster, half open, row 0 = north, column 0 = -180 E 'row_off': row_min, 'n_rows': row_max - row_min, 'col_off': col_min, 'n_cols': col_max - col_min, # and the same thing as the published table spells it 'elev_raster_row_start': row_min, 'elev_raster_row_stop': row_max, 'elev_raster_col_start': col_min, 'elev_raster_col_stop': col_max, } # -------------------------------------------------------------------------- # table assembly and output # -------------------------------------------------------------------------- def build_table(rows: list[dict], provenance: dict): """Concatenate per-band results into one Parquet table.""" return tf.build_table(rows, provenance, PLANET) # -------------------------------------------------------------------------- # driver # -------------------------------------------------------------------------- def _process_bands(src, grid: PlanetBandGrid, ctx: RasterContext, bands: list[int], quarters: bool, writer, provenance: dict) -> tuple[list[dict], int]: """The per-band loop shared by the local and the streaming read path.""" rows = [] pixels = 0 for band in bands: result = process_band(src, grid, ctx, band, quarters=quarters) pixels += int(result['n_native_samples'].sum()) if writer is not None: # Written and dropped per band: a group's worth of quarter # rows is gigabytes, and several groups run side by side. band_quarters_ = result.pop('quarters', None) if band_quarters_ is not None: writer.write(build_quarter_table([band_quarters_], provenance, bands)) rows.append(result) return rows, pixels def process_group(group: int, bands: list[int], source_dir: Path, out_dir: Path, provenance: dict, quarters: bool = False, *, dem_url: str | None = None, token: str | None = None, retries: int = DEFAULT_RETRIES, gdal_cache_mb: int = et.DEFAULT_GDAL_CACHE_MB) -> dict: """Process one band group and write its Parquet file. ``dem_url`` streams pixels from a remote COG instead of opening the manifest's local file; ``token``/``retries``/``gdal_cache_mb`` matter only then. See the module docstring and ``streaming_gdal_env``. """ started = time.monotonic() info = load_source_manifest(source_dir, dem_url) streaming = info['streaming'] retry = _StreamRetry(retries=retries) if streaming else None env = streaming_gdal_env(token, gdal_cache_mb) if streaming else rasterio.Env() stats = et.ReadStats() if streaming else None mosaics = et._OpenMosaics() if streaming else None grid = PlanetBandGrid.build(PLANET) writer = qc.QuarterWriter(quarter_path(out_dir, group)) if quarters else None try: with env: ctx = raster_context(info, retry=retry) if streaming: src = _RemoteBand1Reader(mosaics, ctx.path, retry, stats) rows, pixels = _process_bands(src, grid, ctx, bands, quarters, writer, provenance) else: with rasterio.open(ctx.path) as src: rows, pixels = _process_bands(src, grid, ctx, bands, quarters, writer, provenance) finally: if mosaics is not None: mosaics.close() path = group_path(out_dir, group) write_atomic(build_table(rows, provenance), path) if writer is not None: writer.close(empty=lambda: build_quarter_table([], provenance, bands)) return {'group': group, 'bands': len(bands), 'rows': int(sum(len(r['column']) for r in rows)), 'source_pixels': pixels, 'seconds': time.monotonic() - started, 'path': str(path)} def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument('--bands', default=None, help='inclusive band range START-END (default: every band)') parser.add_argument('--source', type=Path, default=DEFAULT_SOURCE_DIR, help='directory holding source_manifest.json (and the DEM, ' 'unless --dem-url streams it instead)') parser.add_argument('--out', type=Path, default=DEFAULT_OUT_DIR, help=f'output root; files land in <out>/{FEATURE_VERSION}/') parser.add_argument('--workers', type=int, default=1, help='band groups in parallel') parser.add_argument('--resume', action='store_true', help='skip band groups whose output already covers them') parser.add_argument('--quarters', action='store_true', help=f'also write 2.5 km quarter cells to <out>/{qc.QUARTER_VERSION}/') parser.add_argument('--dem-url', default=None, help='stream the DEM from this URL (or an already-prefixed GDAL ' 'VSI path, or a local path for testing) instead of the ' 'manifest\'s local file; --source still supplies every other ' 'field, source_checksum included') parser.add_argument('--hf-repo', default=DEFAULT_HF_REPO, help='HF dataset repo that --dem-url and its cog_verification.json ' 'live in, for the pre-read hash check') parser.add_argument('--hf-filename', default=DEFAULT_HF_COG, help='filename inside --hf-repo whose LFS hash is checked ' 'before streaming') parser.add_argument('--hf-token', default=None, help='Hub token for a private --hf-repo (default: $HF_TOKEN, ' 'then the cached login)') parser.add_argument('--skip-remote-verify', action='store_true', help='skip the pre-read Hub LFS hash check (for a local, ' 'non-Hub --dem-url fixture)') parser.add_argument('--retries', type=int, default=DEFAULT_RETRIES, help='attempts per remote open/read before a streaming run fails') parser.add_argument('--gdal-cache-mb', type=int, default=et.DEFAULT_GDAL_CACHE_MB, help='GDAL block cache for a streaming run, MB') args = parser.parse_args(argv) grid = PlanetBandGrid.build(PLANET) n_bands = len(grid.column_counts) bands = parse_band_range(args.bands, n_bands) if args.bands else list(range(n_bands)) info = load_source_manifest(args.source, args.dem_url) streaming = info['streaming'] token = hf_token(args.hf_token) if streaming else None if streaming and not args.skip_remote_verify: verify_remote_cog(args.hf_repo, args.hf_filename, token) retry = _StreamRetry(retries=args.retries) if streaming else None env = streaming_gdal_env(token, args.gdal_cache_mb) if streaming else rasterio.Env() with env: raster_context(info, retry=retry) provenance = { 'source_product': info['source_product'], 'source_version': info['source_version'], 'source_checksum': info['source_checksum'], 'code_version': code_version(), 'computed_at': datetime.now(timezone.utc).isoformat(timespec='seconds'), 'dem_file': info['dem_path'] if streaming else info['dem_path'].name, } work = plan_groups(bands) if args.resume: kept = [] for group, group_bands in work: # a stale quarter file sends the whole group back, terrain file # included, so the two are always rewritten as a pair if (group_is_complete(group_path(args.out, group), group_bands) and (not args.quarters or quarter_group_is_current( quarter_path(args.out, group), group_bands))): print(f'group {group:03d}: already complete, skipped', flush=True) else: kept.append((group, group_bands)) work = kept print(f'{len(bands)} bands in {len(work)} groups -> {args.out / FEATURE_VERSION}', flush=True) started = time.monotonic() totals = {'rows': 0, 'source_pixels': 0} def report(result): totals['rows'] += result['rows'] totals['source_pixels'] += result['source_pixels'] print(f"group {result['group']:03d}: {result['bands']} bands, {result['rows']} rows, " f"{result['source_pixels']} source pixels, {result['seconds']:.1f}s " f"-> {result['path']}", flush=True) kwargs = dict(dem_url=args.dem_url, token=token, retries=args.retries, gdal_cache_mb=args.gdal_cache_mb) if args.workers > 1 and len(work) > 1: with ProcessPoolExecutor(max_workers=args.workers) as pool: futures = {pool.submit(process_group, g, b, args.source, args.out, provenance, args.quarters, **kwargs): g for g, b in work} for future in as_completed(futures): report(future.result()) else: for group, group_bands in work: report(process_group(group, group_bands, args.source, args.out, provenance, args.quarters, **kwargs)) print(f"done: {totals['rows']} rows, {totals['source_pixels']} source pixels, " f'{time.monotonic() - started:.1f}s', flush=True) return 0 if __name__ == '__main__': sys.exit(main())
"""Single-pass, band-by-band global terrain features on the latband5km-v1 grid.
Source: the MOLA-HRSC Blended DEM (200 m/pixel simple-cylindrical GeoTIFF),
described by ``source_manifest.json`` next to the raster. The grid is the
permanent latitude-band index from :mod:`planetary_grid`; this module never
changes cell IDs, band edges or column counts.
Each latitude band is read exactly once as a windowed strip of full-width pixel
rows plus a two-row halo, equalized east-west to ~200 m of ground spacing, and
reduced to per-cell statistics with pure array operations (no per-cell polygon
rasterization). Output is one Parquet file per 100 bands.
The planet-independent half of that work - block averaging, Horn slope, the
per-cell reductions, the ``terrain-v0.2`` feature definitions and the Parquet
assembly - lives in :mod:`terrain_features` and is shared verbatim with
:mod:`earth_terrain`. What stays here is Mars: the manifest, the raster
geometry, the spherical ground-spacing arithmetic and the read window.
Usage:
python mars_terrain.py --bands 1000-1099 --workers 4
python mars_terrain.py --bands 0-2133 --resume --workers 8 --out DIR
python mars_terrain.py --bands 0-2133 --resume --workers 8 --out DIR \
--dem-url https://huggingface.co/datasets/enzeeoai/starman-mars-elevation/resolve/main/\
Mars_HRSC_MOLA_BlendDEM_Global_200mp_v2_cog.tif
``--dem-url`` streams pixels from a remote lossless COG instead of opening a
local file, so a worker never needs the ~8 GB source raster on disk; ``--source``
still supplies ``source_manifest.json`` (nodata, body radius and
``source_checksum``, the hash of the original uncompressed GeoTIFF - streaming
its COG does not change what that original file was). Reads are retried
(``--retries``) under the same anonymous/no-internal-retry GDAL options
:mod:`earth_terrain` uses for its own streaming reads, and the remote file's
Hub LFS hash is checked against its publish-time verification report before
any pixel is read.
Conventions and deliberate choices are documented in ``band_context`` and
``process_band``; the ones that matter for interpretation are:
* Statistics are computed on the *analysis* grid (after east-west block
averaging), so ``n_samples_200m`` counts analysis pixels. ``n_native_samples`` and
``n_valid_native_samples`` carry the native pixel accounting, which partitions the
raster exactly.
* The block factor ``k`` is a function of latitude, but one ``k`` is used for
every row of a band's read window so the three rows of a Horn stencil stay
column-aligned. ``k`` is taken at the band's centre latitude; where the rows
of the window do not all agree the cell is flagged ``mixed_block_factor``.
* Elevations are passed through as published (metres, areoid per the manifest's
own inference) and are context only.
"""
from __future__ import annotations
import argparse
import json
import math
import re
import sys
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
import rasterio
from rasterio.windows import Window
import terrain_features as tf
import quarter_cells as qc
import earth_terrain as et # noqa: F401 (GDAL_ENV, _OpenMosaics, read_with_retries, ReadStats: reused, not forked)
from planetary_grid import PLANETS, VERSION as GRID_VERSION, PlanetBandGrid
# Re-exported so that every name this module published before the shared
# feature code was split out of it still resolves here. Callers may import
# either module; these are the same objects.
from terrain_features import ( # noqa: F401
ANALYSIS_SPACING_M, BANDS_PER_GROUP, BLOCK_HALO, COUNT_FEATURES, ELEV_PERCENTILES,
FEATURE_VERSION, FLOAT_FEATURES, LOW_COVERAGE_FRACTION, POLAR_DISTORTION_LAT,
RELIEF_WINDOW, ROW_HALO, SLOPE_PERCENTILES, SLOPE_THRESHOLDS,
AnalysisSegment, _constant, _sum, _window_extreme, block_average_ew,
detrended_roughness, ew_block_factor, group_is_complete, group_path,
grouped_percentiles, horn_slope_deg, local_relief, parse_band_range, plan_groups,
wrap_blocks, write_atomic,
)
PLANET = 'mars'
DEFAULT_SOURCE_DIR = Path('data/raw/mars/mola_hrsc')
DEFAULT_OUT_DIR = Path('data/processed/mars/terrain')
# The private HF dataset holding the lossless Mars DEM COG that --dem-url
# streams from. publish_dem_hf.py uploads it (REPO_ID) and MarsElevationSource
# below resolves cells against it (ELEVATION_REPO); these three must agree.
DEFAULT_HF_REPO = 'enzeeoai/starman-mars-elevation'
DEFAULT_HF_COG = 'Mars_HRSC_MOLA_BlendDEM_Global_200mp_v2_cog.tif'
DEFAULT_RETRIES = 4
@dataclass(frozen=True)
class _StreamRetry:
"""Just enough of earth_terrain.EarthSource's shape for et.read_with_retries.
et.read_with_retries only ever reads ``source.retries`` and