Skip to main content

ras_commander_fast_map/
lib.rs

1//! Native 2D flood inundation mapping: horizontal, sloping, and ras2fim-2D Step05.
2//!
3//! Extends the immutable baseline prototype `prototype/kernel` (RasMapper_Stored_Maps_Rust,
4//! 2026-10-22, CLB Engineering): the barycentric evaluation, the `100 * DBL_EPSILON` inclusion
5//! test and the lowest-simplex-id tie rule are copied from that kernel. Upstream algorithm:
6//! Andy Carter, PE / University of Texas at Austin, ras2fim-2d `3146f647`, Step05 (BSD-3-Clause).
7//!
8//! The application uses [`step05`], which preserves the upstream float32 sequence
9//! and native approximate reprojection over supplied SciPy transforms and axes.
10//! The older [`session`] diagnostic retains its distinct f64 arithmetic.
11//! Step05 and triangulated-session scope boundaries:
12//! - Interpolation topology is always caller-supplied global SciPy/Qhull simplices. There is no
13//!   native triangulation and never a per-AOI or per-tile retriangulation.
14//! - Wet masks and sample preparation are caller-supplied (upstream/Python adapters).
15//! - Native terrain is same-CRS, north-up, single-band float32 GeoTIFF read through terrio with
16//!   an explicit sampling formula. Other terrain types require separate qualification.
17//! - The diagnostic session's f64 arithmetic does not replace the Step05 float32 sequence.
18//!
19//! Independent [`horizontal`] and [`sloping_session`] methods prepare pixel ownership
20//! directly from cell polygons. Plain sloping reconstructs hydraulic connectivity
21//! and corner interpolation rather than using the Step05 SciPy topology.
22#![forbid(unsafe_code)]
23
24/// Version of the standalone crate and Python wheel.
25pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
26/// Source revision of an official build, or `unknown` for an unversioned archive.
27pub const ENGINE_COMMIT: &str = env!("FAST_MAP_ENGINE_COMMIT");
28
29pub mod cache;
30pub mod horizontal;
31pub mod interp;
32pub mod model;
33pub mod ownership;
34pub mod scipy_interp;
35pub mod session;
36pub mod sink;
37pub mod sloping;
38mod sloping_binary;
39pub mod sloping_session;
40pub mod step05;
41pub mod terrain;
42
43use std::fmt;
44
45/// Identifies the method semantics. Changing any recorded convention must change this string.
46pub const METHOD_VERSION: &str = "ras2fim-batch-prototype/0.1.0 method-r1";
47
48/// Identifies the output/failure/budget contract (not the numerical method, which is unchanged).
49pub const CONTRACT_VERSION: &str = "ras2fim-batch-prototype contract-r2-hardening";
50
51/// Errors are typed so callers can distinguish invalid input, budgets and unsupported cases.
52#[derive(Debug, Clone, PartialEq)]
53pub enum MapError {
54    Invalid(String),
55    Budget(String),
56    Unsupported(String),
57    Io(String),
58    Terrain(String),
59    /// A caught panic or broken internal invariant (never a silent partial result).
60    Internal(String),
61}
62
63impl fmt::Display for MapError {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            MapError::Invalid(s) => write!(f, "invalid input: {s}"),
67            MapError::Budget(s) => write!(f, "budget exceeded: {s}"),
68            MapError::Unsupported(s) => write!(f, "unsupported: {s}"),
69            MapError::Io(s) => write!(f, "io error: {s}"),
70            MapError::Terrain(s) => write!(f, "terrain error: {s}"),
71            MapError::Internal(s) => write!(f, "internal error: {s}"),
72        }
73    }
74}
75
76impl std::error::Error for MapError {}
77
78impl From<std::io::Error> for MapError {
79    fn from(e: std::io::Error) -> Self {
80        MapError::Io(e.to_string())
81    }
82}
83
84impl MapError {
85    pub fn kind(&self) -> &'static str {
86        match self {
87            MapError::Invalid(_) => "invalid",
88            MapError::Budget(_) => "budget",
89            MapError::Unsupported(_) => "unsupported",
90            MapError::Io(_) => "io",
91            MapError::Terrain(_) => "terrain",
92            MapError::Internal(_) => "internal",
93        }
94    }
95}
96
97/// Static description of the implemented semantics, emitted in every report.
98pub fn method_record() -> serde_json::Value {
99    serde_json::json!({
100        "method_version": METHOD_VERSION,
101        "interpolation": {
102            "topology": "caller-supplied global SciPy/Qhull simplices only; no native or per-AOI triangulation",
103            "evaluation": "f64 barycentric linear interpolation (baseline prototype kernel)",
104            "inclusion_tolerance": "all barycentric coordinates >= -100*DBL_EPSILON",
105            "tie_rule": "lowest supplied simplex index among containing simplices (order independent)",
106            "degenerate_simplices": "skipped when determinant == 0 or exact 1-norm reciprocal condition < 1000*DBL_EPSILON; modeled on SciPy's singular-transform skip, not verified bit-identical to SciPy's LAPACK estimate",
107            "scipy_eps_broad_fallback": "not implemented; no claim of SciPy find_simplex walk parity",
108            "query_point": "x = x0 + col*dx, y = y0 + row*dy in f64 (explicit grid); terrain-aligned grid: x = gt0 + (abs_col + 0.5)*gt1, y = gt3 + (abs_row + 0.5)*gt5"
109        },
110        "mask": "caller-supplied rasterized wet union on the profile grid (upstream/Python adapter); unmasked pixels are nodata",
111        "depth_wse": "depth = raw_wse - ground (f64); wet iff ground present and depth >= 0; wse = raw_wse where wet. Baseline prototype semantics; upstream float32 writes, '<0 -> NaN' sequencing and the Step05 nudge are NOT replicated",
112        "terrain_modes": {
113            "caller_buffer": "per-profile pre-aligned f64 terrain buffer, null/NaN = nodata (old oracle parity mode)",
114            "native_geotiff": {
115                "format": "same-CRS, north-up (gt2 == gt4 == 0, gt1 > 0, gt5 < 0), single-band float32 GeoTIFF/BigTIFF via terrio 0.4.2 lazy tile reads",
116                "sample_formula": "col = floor((xs - gt0) / gt1), row = floor((ys - gt3) / gt5) in f64",
117                "query_convention": "explicit per session: pixel_center (xs = x0 + (col + 0.5)*dx, ys = y0 + (row + 0.5)*dy) or query_point (xs, ys = query point)",
118                "nodata_policy": "explicit per session: dry (declared-nodata sentinel -> dry) or raw_value (sentinel subtracted as a number, upstream-like raw subtraction; not qualified)",
119                "outside_extent": "dry",
120                "nan_value": "dry",
121                "reprojection": "never; terrain EPSG must equal the declared session EPSG",
122                "not_qualified": "GDAL Warp nearest-neighbour, Step05 inverted-bounds lattice, nudge, upstream raw-sentinel behaviour; rasterio rowcol uses a linear solve and may differ at exact pixel-boundary ties (counted as terrain_near_boundary_samples)"
123            }
124        },
125        "nonfinite_terrain": "NaN terrain is dry; declared NaN or +/-inf nodata is accepted (a pixel is the sentinel iff v == nodata as f32, GDAL-like; report states whether that cast is exact); any other infinite terrain value that is sampled is rejected (native: typed terrain error failing the profile; caller_buffer: invalid request)",
126        "aoi": "pixel windows on each profile's own grid; AOI output equals the crop of the full-grid output by construction (same tiles, same per-pixel formula); bounds select pixels whose center lies in [min, max)",
127        "outputs": "per (profile, AOI) unit: little-endian f64 rasters with NaN nodata, simplex_id as i64 with -1 nodata, row-major in grid row order",
128        "output_contract": {
129            "contract_version": CONTRACT_VERSION,
130            "commit": "unit.json status in_progress is written before any data; data is written as <product>.bin.partial, fsynced (errors propagate), renamed to .bin, directory synced where supported, then unit.json is atomically replaced with status complete. A .bin is valid only when unit.json says complete",
131            "failure": "a failed unit, or every open unit after a session error or caught panic, has its data removed and unit.json status failed; report.json is still written with status aborted when possible (otherwise stderr says so and in_progress/.partial names remain)",
132            "json_writes": "<name>.partial, fsync, rename",
133            "ids": "[A-Za-z0-9_.-]{1,64}, unique case-insensitively, no trailing '.', no Windows device names (CON, PRN, AUX, NUL, COM0-9, LPT0-9, with any extension)"
134        },
135        "bounds": {
136            "enforced": "decoded resident terrain tiles <= max_cache_bytes; evaluated tile buffers <= effective_tiles_in_flight x output_tile^2 x 40 bytes; plan tiles per profile <= 4194304",
137            "admission_estimates": "per-profile load+prepare peak from request content / file lengths before any read (binary/inline: buffer sizes plus an assumed one-copy R-tree bulk-load; legacy JSON: 64 x file length heuristic) checked against max_profile_bytes; optional max_session_bytes packs batches over accounted static terms + batch load peaks + plan metadata",
138            "not_bounded": "decoder transients (estimated only), allocator fragmentation, thread stacks, codec state, JSON transients; no hard total memory bound is claimed"
139        }
140    })
141}