"""mars_valleys (Mars): drainage density, maximum Strahler order and distance to the nearest valley. Source: Alemanno & Orofino, "Global map of Martian fluvial systems" (Zenodo 1051038), the ``Giulia Valleys`` shapefile: 3,772 features, projected equidistant cylindrical on the Mars sphere. Cleaning (``prepare``): 10 features carry a 1-vertex line part that shapely refuses to build; the WKB is parsed directly and those parts are dropped. The 10 exact-duplicate geometries are removed (first one kept). Coordinates are un-projected with lon = x / R, lat = y / R (R = 3,396,190 m) and lengths are measured on the Mars sphere, never taken from the ``Length(km)`` attribute (which is measured in the projected plane and overstates ground length). Channels are made comparable with HydroRIVERS by the shared code in ``vector_common.prune_network``: vertex spacing 460 m, endpoints snapped within 1 km, source segments shorter than L_min = 20 km dropped repeatedly, systems shorter than L_min dropped, Strahler order recomputed on what is left. Mars valleys have no flow direction: each connected system is oriented toward the end of its longest path. Earth twin: ``hydrorivers``. """ from __future__ import annotations import json from pathlib import Path import numpy as np import pyarrow as pa from . import vector_common as vc, geology_geometry from .driver import Item, LayerError SLUG = 'mars_valleys' VERSION = 'v0.2' CROSSWALKS = ['vector_common.py', 'geology_geometry.py'] SHAPEFILE = 'Giulia Valleys.shp' WORK_FILE = 'network.parquet' STATS_FILE = 'network_stats.json' L_MIN_KM = 20.0 SNAP_KM = 1.0 VERTEX_SPACING_M = 460.0 UPLAND_MIN_KM2 = None # Mars has no upstream-area threshold R = vc.MARS_RADIUS_M SOURCE = { 'product': 'Global map of Martian fluvial systems (Alemanno & Orofino)', 'version': 'v1, 2017-11-16', 'url': 'https://doi.org/10.5281/zenodo.1051038', 'licence': 'CC-BY-SA-4.0 (Zenodo record). Derived Parquet is published under CC-BY-SA-4.0. ' 'Approved for non-commercial use (Enzo, 2026-11-13).', 'planet': 'mars', 'doi': '10.5281/zenodo.1051038', 'parameters': { 'L_min_km': L_MIN_KM, 'snap_km': SNAP_KM, 'vertex_spacing_m': VERTEX_SPACING_M, 'upstream_area_threshold_km2': UPLAND_MIN_KM2, 'upstream_area_note': 'Mars has no upstream-area threshold (valleys >= 20 km, as mapped)', 'length': 'great circle on the Mars sphere, R = 3396190 m, after resampling; Length(km) is not used', 'cleaning': 'drop 1-vertex line parts; remove exact-duplicate geometries', 'orientation': 'toward the end of the longest path of each system (no flow direction in the data)', }, } COLUMNS = { 'drain_dens_km_km2': {'dtype': 'float32', 'unit': 'km/km2', 'comparison': 'planet_specific', 'fill': 0.0, 'description': 'Length of kept valley lines in the cell / cell area. Lines are resampled ' 'to 460 m, pruned (source segments < 20 km, systems < 20 km) and measured ' 'on the Mars sphere. Earth twin: hydrorivers drain_dens_km_km2 (per land ' 'area).'}, 'max_order': {'dtype': 'int16', 'unit': 'order', 'comparison': 'planet_specific', 'fill': 0, 'description': 'Highest Strahler order of the kept valley lines in the cell, recomputed on the ' 'pruned network; 0 where there is no channel. Earth twin: hydrorivers max_order.'}, 'dist_channel_km': {'dtype': 'float32', 'unit': 'km', 'comparison': 'planet_specific', 'description': 'Great-circle distance on the Mars sphere from the cell centre to the nearest ' 'kept valley line. Earth twin: hydrorivers dist_channel_km.'}, } LIMITATIONS = [ 'The map misses small and buried valleys (Alemanno kept valleys >= 20 km on THEMIS 100 m, CTX where needed); ' 'a cell with no valley is 0, not unknown.', 'The valley lines carry no flow direction, so Strahler order is computed after orienting each connected ' 'system toward the end of its longest path; max_order is approximate.', 'Channel columns are made comparable with HydroRIVERS by shared pruning (L_min 20 km, snap 1 km, vertex spacing ' '460 m); the Earth upstream-area threshold has no Mars counterpart.', 'Length is measured on the Mars sphere after resampling; the source Length(km) attribute is measured in the ' 'equidistant-cylindrical plane and overstates ground length (ratio up to 1.7 at 60-70 degrees).', 'The derived Parquet is CC-BY-SA-4.0.', ] def _project_back(parts): """Equidistant cylindrical metres -> lon/lat degrees on the Mars sphere.""" return [np.column_stack([np.degrees(p[:, 0] / R), np.degrees(p[:, 1] / R)]) for p in parts] def load_valleys(path: Path): """(parts, stats): cleaned valley line parts in lon/lat degrees.""" import pyogrio meta, fids, geometry, fields = pyogrio.raw.read(str(path)) features, dropped, seen, dup = [], 0, set(), 0 for wkb in geometry: parts, n_drop = vc.wkb_line_parts(bytes(wkb)) dropped += n_drop key = b''.join(p.tobytes() for p in parts) if key in seen: dup += 1 continue seen.add(key) if parts: features.append(_project_back(parts)) flat = [p for parts in features for p in parts] return flat, {'features_in': int(len(geometry)), 'features_kept': len(features), 'parts': len(flat), 'parts_dropped_1_vertex': dropped, 'duplicates_removed': dup} def build_network(flat, planet='mars'): return vc.prune_network(flat, L_MIN_KM, SNAP_KM, VERTEX_SPACING_M, UPLAND_MIN_KM2, planet=planet) def write_network(net: vc.Network, path: Path) -> None: import geopandas as gpd import shapely lines = [shapely.LineString(p) for p in net.lines] miny = [float(p[:, 1].min()) for p in net.lines] maxy = [float(p[:, 1].max()) for p in net.lines] gdf = gpd.GeoDataFrame({'order': net.order.astype(np.int16), 'length_km': net.length_km.astype(np.float32), 'miny': miny, 'maxy': maxy}, geometry=lines, crs=None) path.parent.mkdir(parents=True, exist_ok=True) gdf.to_parquet(path) def read_network(path: Path, lat0: float = -91.0, lat1: float = 91.0): """(Lines, order) of the kept lines whose latitude range meets [lat0, lat1].""" import pyarrow.parquet as pq import shapely table = pq.read_table(path, filters=[('maxy', '>=', lat0), ('miny', '<=', lat1)]) geoms = shapely.from_wkb(table['geometry'].to_numpy(zero_copy_only=False)) arrays = [shapely.get_coordinates(g) for g in geoms] return vc.Lines.from_list(arrays), table['order'].to_numpy().astype(np.int16) def prepare(ctx) -> None: src = ctx.raw_dir / SHAPEFILE if not src.exists(): raise LayerError(f'{src} is missing (G-A downloads it)') ctx.source_checksum = ctx.record_source_file(src) flat, stats = load_valleys(src) net = build_network(flat, ctx.planet) stats.update(kept_lines=len(net.lines), kept_length_km=float(net.length_km.sum()), max_order=int(net.order.max()) if len(net.order) else 0, self_loops_dropped=net.n_self_loops, params=net.params) write_network(net, ctx.interim_dir / WORK_FILE) (ctx.interim_dir / STATS_FILE).write_text(json.dumps(stats, indent=1)) ctx.log(note='valley network written', **{k: v for k, v in stats.items() if k != 'params'}) def _network(ctx): if 'network' not in ctx.state: path = ctx.interim_dir / WORK_FILE if not path.exists(): raise LayerError(f'{path} is missing: prepare() has not run') lines, order = read_network(path) ctx.state['network'] = (lines, order, vc.Features.from_lines(lines, ctx.planet)) return ctx.state['network'] def plan(band_group: int, ctx) -> list: return [Item(key='valley_network', url=None, method='none', meta={'file': WORK_FILE})] def compute(band_group: int, lines: vc.Lines, order, feats: vc.Features, planet='mars', grid=None): cells = vc.group_cells(grid, band_group) length_km, max_order = geology_geometry.channel_cells(band_group, lines, order, planet=planet, grid=grid) dist = vc.nearest_distance_km(cells.clon, cells.clat, feats, planet, window_deg=5.0) return {'drain_dens_km_km2': length_km / cells.area_km2, 'max_order': max_order, 'dist_channel_km': dist} def reduce(band_group: int, items, ctx) -> pa.Table: for _ in items: pass lines, order, feats = _network(ctx) res = compute(band_group, lines, order, feats, ctx.planet, ctx.grid) return pa.table({ 'region_id': ctx.cells(band_group)['region_id'], 'drain_dens_km_km2': pa.array(res['drain_dens_km_km2'].astype(np.float32)), 'max_order': pa.array(res['max_order']), 'dist_channel_km': pa.array(res['dist_channel_km'].astype(np.float32)), 'quality_flags': pa.array([''] * len(res['max_order']), pa.string()), })