Datasets:
Download code/mars_terrain.py from enzeeoai/starman: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/mars_terrain.py
- Command line
-
hf download hf://datasets/enzeeoai/starman/code/mars_terrain.py
-
curl -L -o mars_terrain.py https://huggingface.co/datasets/enzeeoai/starman/resolve/main/code/mars_terrain.py
19 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 | |
| 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 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 | |
| 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') | |
| # -------------------------------------------------------------------------- | |
| # 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 load_source_manifest(source_dir: Path) -> dict: | |
| """Read ``source_manifest.json`` and pull out the fields the pipeline needs.""" | |
| 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': source_dir / product['file'], | |
| '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['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) | |
| 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 | |
| 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) -> RasterContext: | |
| """Open the DEM only to validate its geometry against the manifest.""" | |
| 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') | |
| return RasterContext( | |
| path=Path(info['dem_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'], | |
| ) | |
| # -------------------------------------------------------------------------- | |
| # 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) -> 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) | |
| 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) | |
| # -------------------------------------------------------------------------- | |
| # 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_group(group: int, bands: list[int], source_dir: Path, out_dir: Path, | |
| provenance: dict) -> dict: | |
| """Process one band group and write its Parquet file.""" | |
| started = time.monotonic() | |
| info = load_source_manifest(source_dir) | |
| ctx = raster_context(info) | |
| grid = PlanetBandGrid.build(PLANET) | |
| rows = [] | |
| pixels = 0 | |
| with rasterio.open(ctx.path) as src: | |
| for band in bands: | |
| result = process_band(src, grid, ctx, band) | |
| pixels += int(result['n_native_samples'].sum()) | |
| rows.append(result) | |
| path = group_path(out_dir, group) | |
| write_atomic(build_table(rows, provenance), path) | |
| 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') | |
| 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') | |
| 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) | |
| raster_context(info) | |
| 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'].name, | |
| } | |
| work = plan_groups(bands) | |
| if args.resume: | |
| kept = [] | |
| for group, group_bands in work: | |
| if group_is_complete(group_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) | |
| 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): 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)) | |
| 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()) | |