#!/usr/bin/env python3 """ Standalone Reproducible Verification & Benchmark Suite for racemap/elevation-service Covers: - Issue #21 & #55 ("Some locations have seriously incorrect altitudes" / "Investigate and filter implausible altitudes") - Issue #50 & PR #67 ("HGT sampling blends void samples (-32768) into results") - Issue #64 ("Evaluate Copernicus DEM GLO-30 as a replacement for the 2017 skadi mosaic") Zero third-party dependencies (uses Python 3 standard library only: urllib, gzip, zlib, struct, math, statistics). """ import gzip import json import math import statistics import struct import urllib.request import zlib from collections import Counter SKADI_BASE = "https://s3.amazonaws.com/elevation-tiles-prod/skadi" COPERNICUS_BASE = "https://copernicus-dem-30m.s3.amazonaws.com" _skadi_cache = {} _cog_hdr_cache = {} _cog_tile_cache = {} def fetch_skadi_tile(lat_fl: int, lng_fl: int) -> bytes | None: key = (lat_fl, lng_fl) if key in _skadi_cache: return _skadi_cache[key] ns = f"N{lat_fl:02d}" if lat_fl >= 0 else f"S{-lat_fl:02d}" ew = f"E{lng_fl:03d}" if lng_fl >= 0 else f"W{-lng_fl:03d}" url = f"{SKADI_BASE}/{ns}/{ns}{ew}.hgt.gz" try: req = urllib.request.Request(url, headers={"User-Agent": "Vireo-Elevation-Audit/1.0"}) with urllib.request.urlopen(req, timeout=25) as r: raw = gzip.decompress(r.read()) _skadi_cache[key] = raw return raw except Exception: _skadi_cache[key] = None return None def sample_skadi(lat: float, lng: float, mode: str = "master", max_dev_m: float | None = None) -> int | None: """ mode: - 'master': current master branch (no void filtering, double i16 truncation) - 'pr67': PR #67 as opened (only filters -32768 / i16::MIN) - 'fixed': filters both i16::MIN (-32768) and i16::MAX (+32767), single f64 round(), plus optional 8-neighbor median deviation filter (#55 PLAUSIBILITY_MAX_DEVIATION_M) """ lat_fl = math.floor(lat) lng_fl = math.floor(lng) buf = fetch_skadi_tile(lat_fl, lng_fl) if buf is None: return None size = 3601 if len(buf) == 25934402 else 1201 span = size - 1 row = (lat - lat_fl) * span col = (lng - lng_fl) * span r_low = int(math.floor(row)) c_low = int(math.floor(col)) r_high = min(r_low + 1, span) c_high = min(c_low + 1, span) r_frac = row - r_low c_frac = col - c_low def raw_at(r_idx: int, c_idx: int) -> int: # Note: in racemap/elevation-service src/tileset/hgt.rs:108: # offset = ((self.size - row as usize - 1) * self.size + col as usize) * 2 off = ((size - r_idx - 1) * size + c_idx) * 2 return struct.unpack(">h", buf[off : off + 2])[0] if mode == "master": vll = raw_at(r_low, c_low) vlh = raw_at(r_low, c_high) vhl = raw_at(r_high, c_low) vhh = raw_at(r_high, c_high) v_low = int(vll * (1.0 - c_frac) + vlh * c_frac) v_high = int(vhl * (1.0 - c_frac) + vhh * c_frac) return int(v_low * (1.0 - r_frac) + v_high * r_frac) def valid_sample(r_idx: int, c_idx: int) -> int | None: v = raw_at(r_idx, c_idx) if mode == "pr67": return None if v == -32768 else v # 'fixed': filter both i16::MIN (-32768) and i16::MAX (+32767) if v == -32768 or v == 32767: return None return v corners = [ (valid_sample(r_low, c_low), (1.0 - r_frac) * (1.0 - c_frac)), (valid_sample(r_low, c_high), (1.0 - r_frac) * c_frac), (valid_sample(r_high, c_low), r_frac * (1.0 - c_frac)), (valid_sample(r_high, c_high), r_frac * c_frac), ] w_sum = 0.0 val_sum = 0.0 for s, w in corners: if s is not None: val_sum += s * w w_sum += w if w_sum == 0.0: return None interp = val_sum / w_sum if mode == "fixed" and max_dev_m is not None: # #55 8-neighbor median plausibility check around nearest grid node r_near = int(round(row)) c_near = int(round(col)) neighbors = [] for dr in (-1, 0, 1): for dc in (-1, 0, 1): if dr == 0 and dc == 0: continue rn, cn = r_near + dr, c_near + dc if 0 <= rn < size and 0 <= cn < size: sv = valid_sample(rn, cn) if sv is not None: neighbors.append(sv) if neighbors: med = statistics.median(neighbors) if abs(interp - med) > max_dev_m: return None return int(interp) if mode == "pr67" else int(round(interp)) def sample_copernicus_glo30(lat: float, lng: float) -> tuple[float | None, int]: """ Reads exact float32 elevation from Copernicus DEM GLO-30 Cloud-Optimized GeoTIFF using two HTTP Range requests (16 KB header + single 1024x1024 compressed sub-tile). Returns (elevation_meters, subtile_compressed_bytes). """ lat_fl = math.floor(lat) lng_fl = math.floor(lng) ns = f"N{lat_fl:02d}" if lat_fl >= 0 else f"S{-lat_fl:02d}" ew = f"E{lng_fl:03d}" if lng_fl >= 0 else f"W{-lng_fl:03d}" name = f"Copernicus_DSM_COG_10_{ns}_00_{ew}_00_DEM" url = f"{COPERNICUS_BASE}/{name}/{name}.tif" try: if url not in _cog_hdr_cache: req = urllib.request.Request( url, headers={"Range": "bytes=0-16383", "User-Agent": "Vireo-Elevation-Audit/1.0"} ) with urllib.request.urlopen(req, timeout=15) as r: hdr = r.read() ifd_off = struct.unpack("f", bytes([b0, b1, b2, b3]))[0] return round(float(val), 1), cnt return None, cnt except Exception: return None, 0 REFERENCE_POINTS = [ # 1. Issue #21 / #55 Boston & New England Coastal Anomaly Points ("Boston Harbor #21-A (MA, USA)", "Issue #21", 42.299990, -71.030919, 0.0), ("Atlantic Shore #21-B (MA, USA)", "Issue #21", 42.279885, -71.015816, 1.0), ("Boston Inner Harbor (MA, USA)", "Issue #21", 42.355000, -71.042000, 0.0), ("Portsmouth Harbor (NH, USA)", "Coastal US", 43.071800, -70.712500, 0.0), # 2. European & US City Centres (including Racemap GmbH HQ in Leipzig) ("Leipzig — Racemap HQ (DE)", "City / DSM", 51.312700, 12.373100, 118.0), ("Berlin — Alexanderplatz (DE)", "City / DSM", 52.521900, 13.413200, 38.0), ("Munich — Marienplatz (DE)", "City / DSM", 48.137154, 11.576124, 519.0), ("Zurich — Bürkliplatz (CH)", "City / DSM", 47.366300, 8.541400, 408.0), ("Milan — Piazza del Duomo (IT)", "City / DSM", 45.464100, 9.190000, 122.0), ("Boston — State House (MA, USA)", "City / DSM", 42.358056, -71.063611, 33.0), # 3. Alpine & Mountain Summits ("Zugspitze Summit (DE/AT)", "Alpine", 47.421100, 10.985300, 2962.0), ("Mont Blanc Summit (FR/IT)", "Alpine", 45.832500, 6.864400, 4808.0), ("Matterhorn Summit (CH/IT)", "Alpine", 45.976400, 7.658600, 4478.0), ("Grossglockner Summit (AT)", "Alpine", 47.074444, 12.693889, 3798.0), ("Mount Washington (NH, USA)", "Mountain", 44.270500, -71.303250, 1917.0), # 4. Coastlines & Low Elevation Basins ("Dead Sea Shore (IL/JO)", "Basin", 31.500000, 35.480000, -430.0), ("Badwater Basin — Death Valley (USA)", "Basin", 36.229700, -116.778000, -86.0), ("Rotterdam Waalhaven (NL)", "Coastal EU", 51.885000, 4.425000, 0.0), ("Venice — San Marco Basin (IT)", "Coastal EU", 45.432500, 12.338500, 0.0), # 5. High-Latitude Sites (> 60°N — beyond SRTM 60°N ceiling) ("Tromsø Harbour (NO, 69.65°N)", "High-Lat", 69.649200, 18.955300, 5.0), ("Reykjavik Centre (IS, 64.15°N)", "High-Lat", 64.146600, -21.942600, 14.0), ("Trondheim Fjord (NO, 63.43°N)", "High-Lat", 63.430500, 10.395100, 5.0), ("Rovaniemi Arctic Circle (FI, 66.50°N)", "High-Lat", 66.503900, 25.729400, 85.0), ("Anchorage Downtown (AK, 61.22°N)", "High-Lat", 61.218100, -149.900300, 31.0), ] def main(): print("=" * 100) print("PART 1: ISSUE #21, #50, #55 & PR #67 — BINARY ROOT-CAUSE VERIFICATION ON SKADI N42W072.hgt.gz") print("=" * 100) buf = fetch_skadi_tile(42, -72) size = 3601 vals = struct.unpack(f">{size * size}h", buf) c_min = sum(1 for v in vals if v == -32768) c_max = sum(1 for v in vals if v == 32767) valid_vals = [v for v in vals if v not in (-32768, 32767)] print(f"Tile N42W072.hgt.gz total samples : {len(vals):,}") print(f" v == -32768 (0x8000, i16::MIN) : {c_min:,} <-- Only sentinel checked by PR #67") print(f" v == +32767 (0x7fff, i16::MAX) : {c_max:,} <-- Actual sentinel causing Issue #21!") print(f" All other samples range : [{min(valid_vals)} m, +{max(valid_vals)} m]") for label, lat, lng in [ ("Issue #21 Point A (Boston Harbor)", 42.299990, -71.030919), ("Issue #21 Point B (Atlantic Shore)", 42.279885, -71.015816), ]: m_val = sample_skadi(lat, lng, mode="master") p_val = sample_skadi(lat, lng, mode="pr67") f_val = sample_skadi(lat, lng, mode="fixed", max_dev_m=150.0) print(f" {label} ({lat}, {lng}):") print(f" master={m_val} m | PR #67={p_val} m (STILL BROKEN) | Fixed (i16::MIN|MAX void)={f_val} m") print("\n" + "=" * 100) print("PART 2: ISSUE #64 — 24-POINT BENCHMARK: SKADI (master / PR #67 / Fixed) vs COPERNICUS DEM GLO-30") print("=" * 100) print(f"{'Location':<35} | {'Cat':<10} | {'Ref':>6} | {'Skadi(M)':>8} | {'Skadi(#67)':>10} | {'Skadi(Fix)':>10} | {'GLO-30':>8}") print("-" * 100) results = [] for name, cat, lat, lng, ref_m in REFERENCE_POINTS: sk_m = sample_skadi(lat, lng, mode="master") sk_67 = sample_skadi(lat, lng, mode="pr67") sk_fix = sample_skadi(lat, lng, mode="fixed", max_dev_m=150.0) glo_m, cog_bytes = sample_copernicus_glo30(lat, lng) print( f"{name:<35} | {cat:<10} | {ref_m:>6.1f} | {str(sk_m):>8} | {str(sk_67):>10} | {str(sk_fix):>10} | {str(glo_m):>8}" ) results.append( { "name": name, "category": cat, "lat": lat, "lng": lng, "ref_m": ref_m, "skadi_master": sk_m, "skadi_pr67": sk_67, "skadi_fixed": sk_fix, "copernicus_glo30": glo_m, "cog_subtile_bytes": cog_bytes, } ) out_path = "/Users/fabio/workspace/Survivor/world/projects/racemap_offer/benchmark_results.json" with open(out_path, "w") as f: json.dump(results, f, indent=2) print(f"\nSaved full JSON benchmark to {out_path}") if __name__ == "__main__": main()