"""Planet-independent terrain feature machinery for the latband5km-v1 grid. Everything here is pure array work plus Parquet assembly: it knows nothing about a particular planet, raster or storage backend. The planet-specific modules (:mod:`mars_terrain`, :mod:`earth_terrain`) own source discovery, read windows, ground-spacing geometry and quality semantics; they call into this module for the parts that must stay identical across planets so that the two feature tables mean the same thing and join on ``region_id``. What lives here: * block averaging east-west (and north-south), with exact native pixel accounting; * the +-180 degree wrap halo; * Horn 3x3 slope with caller-supplied true ground spacing; * the 1 km local-relief window; * grouped per-cell reductions (percentiles, extremes, detrended roughness); * the ``terrain-v0.2`` feature definitions and the per-cell reduction that produces them; * advisory quality flags, Parquet table assembly, atomic writes and the band-group bookkeeping shared by both drivers. The feature contract is versioned by ``FEATURE_VERSION``. Changing any number produced here changes both planets at once and requires a version bump. """ from __future__ import annotations import hashlib import json import os import math import uuid from dataclasses import dataclass from pathlib import Path import numpy as np import pyarrow as pa import pyarrow.parquet as pq from planetary_grid import PLANETS, VERSION as GRID_VERSION FEATURE_VERSION = 'terrain-v0.2' ANALYSIS_SPACING_M = 200.0 BANDS_PER_GROUP = 100 ROW_HALO = 2 BLOCK_HALO = 2 RELIEF_WINDOW = 5 # 5 x 5 analysis pixels ~ 1 km SLOPE_THRESHOLDS = (2, 5, 10, 20, 30) # degrees, for slope_frac_gt_* POLAR_DISTORTION_LAT = 88.0 LOW_COVERAGE_FRACTION = 0.8 ELEV_PERCENTILES = (5, 95) SLOPE_PERCENTILES = (50, 90, 99) FLOAT_FEATURES = [ 'n_samples_200m', 'n_valid_samples_200m', 'valid_frac_200m', 'elev_min', 'elev_max', 'elev_mean', 'elev_p05', 'elev_p95', 'elev_range', 'elev_range_robust', 'slope_mean', 'slope_median', 'slope_std', 'slope_p90', 'slope_p99', *[f'slope_frac_gt_{t}' for t in SLOPE_THRESHOLDS], 'roughness_detrended_std', 'local_relief_1km', 'ew_samples_averaged', ] COUNT_FEATURES = ['n_native_samples', 'n_valid_native_samples'] # -------------------------------------------------------------------------- # provenance # -------------------------------------------------------------------------- def code_version(*paths: Path | str) -> str: """SHA-256 over the named source files, in the order given. Every row names the code that made it. A single path reproduces the original single-module digest exactly; passing several files lets a driver cover itself and this module together. """ digest = hashlib.sha256() for path in paths: digest.update(Path(path).read_bytes()) return digest.hexdigest() # -------------------------------------------------------------------------- # block factors # -------------------------------------------------------------------------- def block_factor(ratio: float, max_factor: int | None = None) -> int: """max(1, round(ratio)) with deterministic half-up rounding. Half-way values round up via ``floor(x + 0.5)`` rather than to even, so the factor is reproducible across platforms. ``ratio`` is target spacing over source spacing; a non-finite or non-positive ratio means the source pixel is degenerate (at a pole) and the whole row collapses to ``max_factor``. """ if not math.isfinite(ratio) or ratio <= 0: return max_factor if max_factor else 1 factor = max(1, math.floor(ratio + 0.5)) return min(factor, max_factor) if max_factor else factor def ew_block_factor(lat_deg: float, max_factor: int | None = None) -> int: """k = max(1, round(1/cos(lat))): pixels to average east-west for ~200 m ground. This is the square-pixel, simple-cylindrical case (Mars): the source pixel already spans ~200 m north-south, so only the 1/cos(lat) convergence of the meridians has to be undone. """ cos_lat = math.cos(math.radians(lat_deg)) if cos_lat <= 0: return max_factor if max_factor else 1 return block_factor(1.0 / cos_lat, max_factor) # -------------------------------------------------------------------------- # array stages # -------------------------------------------------------------------------- def block_average_ew(z: np.ndarray, k: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """NaN-aware mean of k adjacent east-west pixels. Returns the block means, the number of native pixels behind each block column (the final block is short when k does not divide the width), and the number of valid native pixels per block. Blocks partition the native columns exactly, so the native counts stay exact. """ rows, width = z.shape if k < 1: raise ValueError('block factor must be >= 1') n_blocks = -(-width // k) pad = n_blocks * k - width valid = np.isfinite(z) filled = np.where(valid, z, 0.0).astype(np.float64) if pad: filled = np.concatenate([filled, np.zeros((rows, pad))], axis=1) valid = np.concatenate([valid, np.zeros((rows, pad), dtype=bool)], axis=1) total = filled.reshape(rows, n_blocks, k).sum(axis=2) count = valid.reshape(rows, n_blocks, k).sum(axis=2) with np.errstate(invalid='ignore'): mean = np.where(count > 0, total / np.maximum(count, 1), np.nan) source = np.full(n_blocks, k, dtype=np.int64) source[-1] = k - pad return mean, source, count.astype(np.int64) def block_average(z: np.ndarray, row_starts: np.ndarray, col_starts: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """NaN-aware mean over arbitrary rectangular blocks, plus the valid counts. ``row_starts`` and ``col_starts`` are the first index of each block; each block runs to the next start (the last to the end of the array), so blocks partition the input exactly and a short final block is allowed. Explicit starts, rather than a single factor, are what lets a band keep whole blocks on both sides of a halo whose own blocks must stay aligned. The mean is taken over all valid native pixels in the two-dimensional block at once, which is not the same as averaging rows and then columns whenever some pixels are NaN. """ valid = np.isfinite(z) filled = np.where(valid, z, 0.0).astype(np.float64) total = np.add.reduceat(np.add.reduceat(filled, row_starts, axis=0), col_starts, axis=1) count = np.add.reduceat(np.add.reduceat(valid.astype(np.int64), row_starts, axis=0), col_starts, axis=1) with np.errstate(invalid='ignore'): mean = np.where(count > 0, total / np.maximum(count, 1), np.nan) return mean, count def block_starts(length: int, k: int, offset: int = 0) -> np.ndarray: """Block start indices for ``length`` items taken ``k`` at a time.""" if k < 1: raise ValueError('block factor must be >= 1') return np.arange(offset, offset + length, k, dtype=np.int64) def wrap_blocks(a: np.ndarray, halo: int = BLOCK_HALO) -> np.ndarray: """Pad east-west with the opposite edge so +-180 degrees is continuous.""" if a.shape[1] < halo: raise ValueError('too few block columns to wrap') return np.concatenate([a[:, -halo:], a, a[:, :halo]], axis=1) def horn_slope_deg(z: np.ndarray, dx_m: np.ndarray, dy_m: float | np.ndarray) -> np.ndarray: """Horn 3x3 slope in degrees, NaN wherever any stencil pixel is NaN. ``z`` is north-up and the result is smaller by one pixel on every side. ``dx_m`` is the east-west ground spacing, broadcastable to the output shape: half of the true separation between the stencil's outer columns. Passing it per column is what keeps the +-180 seam honest, because the published raster stops 0.46 pixels short of closing the longitude ring. ``dy_m`` is the matching north-south spacing, scalar or per row. """ north, mid, south = z[:-2], z[1:-1], z[2:] dzdx = ((north[:, 2:] + 2 * mid[:, 2:] + south[:, 2:]) - (north[:, :-2] + 2 * mid[:, :-2] + south[:, :-2])) / (8 * dx_m) dzdy = ((north[:, :-2] + 2 * north[:, 1:-1] + north[:, 2:]) - (south[:, :-2] + 2 * south[:, 1:-1] + south[:, 2:])) / (8 * dy_m) slope = np.degrees(np.arctan(np.hypot(dzdx, dzdy))) return np.where(np.isfinite(mid[:, 1:-1]), slope, np.nan) def _window_extreme(a: np.ndarray, size: int, op) -> np.ndarray: """Separable moving max/min; NaN propagates, so partial windows are NaN.""" for axis in (0, 1): length = a.shape[axis] parts = [] for shift in range(size): index = [slice(None)] * a.ndim index[axis] = slice(shift, length - (size - 1 - shift)) parts.append(a[tuple(index)]) a = op.reduce(parts) return a def local_relief(z: np.ndarray, size: int = RELIEF_WINDOW) -> np.ndarray: """max - min over a size x size window; shrinks by (size-1) on each axis.""" return _window_extreme(z, size, np.maximum) - _window_extreme(z, size, np.minimum) # -------------------------------------------------------------------------- # grouped reductions (no per-cell loops) # -------------------------------------------------------------------------- def _sum(cells: np.ndarray, values: np.ndarray, n_cells: int) -> np.ndarray: return np.bincount(cells, weights=values, minlength=n_cells)[:n_cells] def grouped_percentiles(values: np.ndarray, cells: np.ndarray, n_cells: int, probs) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Per-cell linear-interpolated percentiles via one sort by (cell, value). Also returns per-cell counts and the sorted values, from which min and max are the first and last element of each run. """ order = np.lexsort((values, cells)) ordered = values[order] counts = np.bincount(cells, minlength=n_cells)[:n_cells] starts = np.concatenate(([0], np.cumsum(counts)[:-1])) out = np.full((len(probs), n_cells), np.nan) present = counts > 0 if present.any(): base = starts[present] size = counts[present] for i, prob in enumerate(probs): position = (size - 1) * (prob / 100.0) low = np.floor(position).astype(np.int64) frac = position - low lower = ordered[base + low] upper = ordered[base + np.minimum(low + 1, size - 1)] out[i, present] = lower * (1.0 - frac) + upper * frac extremes = np.full((2, n_cells), np.nan) if present.any(): extremes[0, present] = ordered[starts[present]] extremes[1, present] = ordered[starts[present] + counts[present] - 1] return out, counts, extremes def detrended_roughness(z: np.ndarray, x_m: np.ndarray, y_m: np.ndarray, cells: np.ndarray, n_cells: int) -> np.ndarray: """Std of residuals from a per-cell least-squares plane in local metres. Batched 3x3 normal equations built with bincount, then an exact second pass for the residuals (the algebraic shortcut loses precision on large relief). """ ones = np.ones_like(z) sums = {name: _sum(cells, value, n_cells) for name, value in ( ('n', ones), ('x', x_m), ('y', y_m), ('z', z), ('xx', x_m * x_m), ('yy', y_m * y_m), ('xy', x_m * y_m), ('xz', x_m * z), ('yz', y_m * z))} normal = np.empty((n_cells, 3, 3)) normal[:, 0, 0] = sums['n'] normal[:, 0, 1] = normal[:, 1, 0] = sums['x'] normal[:, 0, 2] = normal[:, 2, 0] = sums['y'] normal[:, 1, 1] = sums['xx'] normal[:, 1, 2] = normal[:, 2, 1] = sums['xy'] normal[:, 2, 2] = sums['yy'] rhs = np.stack([sums['z'], sums['xz'], sums['yz']], axis=1) enough = sums['n'] >= 4 coefficients = np.zeros((n_cells, 3)) if enough.any(): # pinv keeps rank-deficient cells (single row or column of pixels) # solvable; their residuals are still measured exactly below. coefficients[enough] = np.einsum( 'cij,cj->ci', np.linalg.pinv(normal[enough]), rhs[enough]) fitted = (coefficients[cells, 0] + coefficients[cells, 1] * x_m + coefficients[cells, 2] * y_m) residual = z - fitted sum_squares = _sum(cells, residual * residual, n_cells) with np.errstate(invalid='ignore', divide='ignore'): roughness = np.sqrt(np.maximum(sum_squares, 0.0) / np.maximum(sums['n'], 1)) return np.where(enough, roughness, np.nan) # -------------------------------------------------------------------------- # the terrain-v0.2 per-cell reduction # -------------------------------------------------------------------------- @dataclass(frozen=True) class AnalysisSegment: """One rectangular analysis grid belonging to a band, halos already dropped. A band normally has exactly one segment. It has more than one only when the source's pixel geometry changes inside the band (the Copernicus GLO-30 east-west pixel-width zones), in which case each segment carries its own block factors and its own column grid. Segments are reduced together, so a grid cell's statistics cover every pixel in it regardless of segment. """ elevation: np.ndarray # (n_rows, n_blocks) analysis elevations slope: np.ndarray # (n_rows, n_blocks) Horn slope, degrees relief: np.ndarray # (n_rows, n_blocks) local relief, metres column_of_block: np.ndarray # (n_blocks,) analysis column -> grid column block_lons: np.ndarray # (n_blocks,) centre longitude in [-180, 180) row_lats: np.ndarray # (n_rows,) centre latitude def validate(self) -> None: shapes = (self.elevation.shape, self.slope.shape, self.relief.shape) if len(set(shapes)) != 1: raise ValueError(f'misaligned stages: {shapes}') n_rows, n_blocks = self.elevation.shape if self.column_of_block.shape != (n_blocks,) or self.block_lons.shape != (n_blocks,): raise ValueError('column metadata does not match the analysis width') if self.row_lats.shape != (n_rows,): raise ValueError('row metadata does not match the analysis height') def cell_features(segments, n_cells: int, *, center_lat: float, lon_step: float, n_native_samples: np.ndarray, n_valid_native_samples: np.ndarray, local_metres) -> dict: """Reduce one band's analysis segments to the ``terrain-v0.2`` feature set. ``segments`` is a sequence of :class:`AnalysisSegment` covering the band's interior. ``local_metres(d_lon_deg, lat_deg, center_lat)`` returns the east/north offsets in metres used by the plane fit, which is the only place the body's shape enters. ``n_native_samples`` and ``n_valid_native_samples`` are the caller's exact native pixel accounting per grid column; they are passed through untouched because only the caller knows how its read window partitions the source raster. """ segments = list(segments) for segment in segments: segment.validate() row = {name: np.full(n_cells, np.nan) for name in FLOAT_FEATURES} row['n_native_samples'] = n_native_samples row['n_valid_native_samples'] = n_valid_native_samples row['n_samples_200m'][:] = sum( np.bincount(s.column_of_block, minlength=n_cells)[:n_cells] * s.elevation.shape[0] for s in segments) flat_cells = np.concatenate([ np.broadcast_to(s.column_of_block, s.elevation.shape).ravel() for s in segments]) elev_flat = np.concatenate([s.elevation.ravel() for s in segments]) finite_elev = np.isfinite(elev_flat) elev_cells = flat_cells[finite_elev] elev_values = elev_flat[finite_elev] row['n_valid_samples_200m'][:] = np.bincount(elev_cells, minlength=n_cells)[:n_cells] with np.errstate(invalid='ignore', divide='ignore'): row['valid_frac_200m'][:] = np.where(row['n_samples_200m'] > 0, row['n_valid_samples_200m'] / np.maximum(row['n_samples_200m'], 1), np.nan) if elev_values.size: percentiles, counts, extremes = grouped_percentiles( elev_values, elev_cells, n_cells, ELEV_PERCENTILES) has = counts > 0 row['elev_min'][:] = extremes[0] row['elev_max'][:] = extremes[1] row['elev_p05'][:] = percentiles[0] row['elev_p95'][:] = percentiles[1] totals = _sum(elev_cells, elev_values, n_cells) row['elev_mean'][has] = totals[has] / counts[has] row['elev_range'][:] = extremes[1] - extremes[0] row['elev_range_robust'][:] = percentiles[1] - percentiles[0] # local metres for the plane fit, relative to each cell's own centre cell_center_lon = -180.0 + lon_step * (np.arange(n_cells) + 0.5) lon_grid = np.concatenate([ np.broadcast_to(s.block_lons, s.elevation.shape).ravel() for s in segments ])[finite_elev] lat_grid = np.concatenate([ np.repeat(s.row_lats, s.elevation.shape[1]) for s in segments])[finite_elev] d_lon = (lon_grid - cell_center_lon[elev_cells] + 180.0) % 360.0 - 180.0 x_m, y_m = local_metres(d_lon, lat_grid, center_lat) # the intercept absorbs any constant; removing one improves conditioning row['roughness_detrended_std'][:] = detrended_roughness( elev_values - float(np.mean(elev_values)), x_m, y_m, elev_cells, n_cells) slope_flat = np.concatenate([s.slope.ravel() for s in segments]) finite_slope = np.isfinite(slope_flat) slope_cells = flat_cells[finite_slope] slope_values = slope_flat[finite_slope] if slope_values.size: percentiles, counts, _ = grouped_percentiles( slope_values, slope_cells, n_cells, SLOPE_PERCENTILES) has = counts > 0 totals = _sum(slope_cells, slope_values, n_cells) squares = _sum(slope_cells, slope_values * slope_values, n_cells) mean = np.full(n_cells, np.nan) mean[has] = totals[has] / counts[has] row['slope_mean'][:] = mean row['slope_median'][:] = percentiles[0] row['slope_p90'][:] = percentiles[1] row['slope_p99'][:] = percentiles[2] variance = np.full(n_cells, np.nan) variance[has] = squares[has] / counts[has] - mean[has] ** 2 row['slope_std'][:] = np.sqrt(np.maximum(variance, 0.0)) for threshold in SLOPE_THRESHOLDS: over = _sum(slope_cells, (slope_values > threshold).astype(float), n_cells) fraction = np.full(n_cells, np.nan) fraction[has] = over[has] / counts[has] row[f'slope_frac_gt_{threshold}'][:] = fraction relief_flat = np.concatenate([s.relief.ravel() for s in segments]) finite_relief = np.isfinite(relief_flat) if finite_relief.any(): relief_cells = flat_cells[finite_relief] counts = np.bincount(relief_cells, minlength=n_cells)[:n_cells] totals = _sum(relief_cells, relief_flat[finite_relief], n_cells) has = counts > 0 values = np.full(n_cells, np.nan) values[has] = totals[has] / counts[has] row['local_relief_1km'][:] = values row['n_rows_read'] = sum(s.elevation.shape[0] for s in segments) return row def quality_flags(center_lat: float, valid_frac_200m: np.ndarray, n_samples_200m: np.ndarray, mixed_factor: bool, degenerate: bool, shared_extra=(), per_cell_extra=None) -> list[str]: """Per-cell advisory flags, semicolon separated, empty string when clean. ``shared_extra`` are band-wide flags appended after the shared ones; ``per_cell_extra`` is an optional per-cell iterable of extra flag lists, appended last. Planet-specific modules add their own vocabulary that way without changing the meaning of the shared flags. """ shared = [] if abs(center_lat) > POLAR_DISTORTION_LAT: shared.append('polar_distortion') if mixed_factor: shared.append('mixed_block_factor') if degenerate: shared.append('degenerate_block_grid') shared.extend(shared_extra) extra = per_cell_extra if per_cell_extra is not None else [()] * len(n_samples_200m) out = [] for fraction, pixels, own in zip(valid_frac_200m, n_samples_200m, extra): flags = list(shared) if not pixels: flags.append('no_pixels') elif not np.isfinite(fraction) or fraction < LOW_COVERAGE_FRACTION: flags.append('low_coverage') flags.extend(own) out.append(';'.join(flags)) return out # -------------------------------------------------------------------------- # table assembly and output # -------------------------------------------------------------------------- def _constant(value: str, length: int) -> pa.Array: """Dictionary-encoded constant column; these repeat on every row.""" return pa.DictionaryArray.from_arrays( pa.array(np.zeros(length, dtype=np.int32)), pa.array([value], type=pa.string())) def build_table(rows: list[dict], provenance: dict, planet: str, extra_float_features=()) -> pa.Table: """Concatenate per-band results into one Parquet table. Column order is fixed: identity, the shared ``terrain-v0.2`` features, the native pixel counts, the flags, then provenance, then any planet-specific ``extra_float_features`` at the very end. Appending keeps the shared prefix identical between planets, so the tables stay comparable column by column. """ def cat(name, dtype): return np.concatenate([np.asarray(r[name], dtype=dtype) for r in rows]) if rows \ else np.zeros(0, dtype=dtype) bands = cat('band', np.int32) columns = cat('column', np.int32) length = len(bands) prefix = PLANETS[planet]['prefix'] region_id = [f'{prefix}_{b:04d}_{c:05d}' for b, c in zip(bands.tolist(), columns.tolist())] flags = [flag for r in rows for flag in r['quality_flags']] data = { 'grid_version': _constant(GRID_VERSION, length), 'region_id': pa.array(region_id, type=pa.string()), 'planet': _constant(planet, length), 'band': pa.array(bands), 'column': pa.array(columns), } for name in FLOAT_FEATURES: data[name] = pa.array(cat(name, np.float64).astype(np.float32)) for name in COUNT_FEATURES: data[name] = pa.array(cat(name, np.int64)) data['quality_flags'] = pa.array(flags, type=pa.string()) data['source_product'] = _constant(provenance['source_product'], length) data['source_version'] = _constant(provenance['source_version'], length) data['source_checksum'] = _constant(provenance['source_checksum'], length) data['sample_spacing_m'] = pa.array( np.full(length, ANALYSIS_SPACING_M, dtype=np.float32)) data['feature_version'] = _constant(FEATURE_VERSION, length) data['code_version'] = _constant(provenance['code_version'], length) data['computed_at'] = _constant(provenance['computed_at'], length) for name in extra_float_features: data[name] = pa.array(cat(name, np.float64).astype(np.float32)) table = pa.table(data) return table.replace_schema_metadata({ 'feature_version': FEATURE_VERSION, 'grid_version': GRID_VERSION, 'bands': json.dumps(sorted(int(r['band'][0]) for r in rows)), 'sample_spacing_m': str(ANALYSIS_SPACING_M), 'provenance': json.dumps(provenance, sort_keys=True), }) def group_path(out_dir: Path, group: int) -> Path: return Path(out_dir) / FEATURE_VERSION / f'band_group={group:03d}.parquet' def write_atomic(table: pa.Table, path: Path) -> None: """Write beside the target and rename, so readers never see a partial file.""" path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(f'.{path.name}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp') try: pq.write_table(table, temporary, compression='zstd') os.replace(temporary, path) finally: if temporary.exists(): temporary.unlink() def group_is_complete(path: Path, wanted: list[int]) -> bool: """A resumable group must exist and already cover every band we were asked for.""" if not path.exists(): return False try: metadata = pq.read_schema(path).metadata or {} done = set(json.loads(metadata[b'bands'].decode())) except Exception: return False return set(wanted).issubset(done) # -------------------------------------------------------------------------- # band-group bookkeeping # -------------------------------------------------------------------------- def plan_groups(bands: list[int]) -> list[tuple[int, list[int]]]: groups: dict[int, list[int]] = {} for band in bands: groups.setdefault(band // BANDS_PER_GROUP, []).append(band) return sorted(groups.items()) def parse_band_range(text: str, n_bands: int) -> list[int]: parts = text.split('-') if len(parts) == 1: start = stop = int(parts[0]) elif len(parts) == 2: start, stop = int(parts[0]), int(parts[1]) else: raise ValueError('--bands takes START-END') if not (0 <= start <= stop < n_bands): raise ValueError(f'--bands must lie inside 0-{n_bands - 1}') return list(range(start, stop + 1))