Skip to main content

vibe/capability_schema/
geo_spatial_stats_algebra_entries.rs

1//! Spatial statistics, geomorphometry, map algebra, and network capability schemas (GEO-S7 / R7-V).
2//!
3//! Provides machine schema definitions for all 16 `GisGp.*` host capability invocations
4//! covering geostatistical kriging and spatial autocorrelation (empirical variogram, ordinary
5//! kriging, IDW / natural neighbor, Moran's I / Geary's C, LISA / Getis-Ord Gi*, GWR / Ripley's K),
6//! viewshed and terrain geomorphometry (radial/cumulative viewshed, TPI/TRI/VRM/geomorphons),
7//! map algebra, zonal statistics, marching squares contours, and Saaty AHP overlay,
8//! and hydrological cost distance, least cost paths, and network topology analysis (A*, isochrones,
9//! TSP, MST, max-flow, and centrality).
10
11use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
12
13/// CapabilitySchemaEntry alias for uniform catalog representation.
14pub type CapabilitySchemaEntry = SchemaEntry;
15
16/// Effect classification for VibeScript 0.2 capability operations.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18pub enum Effect {
19    Pure, Compute, Cold, Async, External,
20}
21
22impl Effect {
23    pub const fn as_str(&self) -> &'static str {
24        match self {
25            Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
26            Self::Async => "async", Self::External => "external",
27        }
28    }
29}
30
31/// Parameter type for spatial statistics, map algebra, and network operations.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub enum ParamType {
34    F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
35}
36
37impl ParamType {
38    pub const fn as_str(&self) -> &'static str {
39        match self {
40            Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64", Self::Bool => "bool",
41            Self::Str => "string", Self::Record => "Record", Self::List => "List",
42            Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
43        }
44    }
45}
46
47/// Parameter schema descriptor.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub struct ParamSchema {
50    pub name: &'static str,
51    pub param_type: ParamType,
52    pub required: bool,
53    pub description: &'static str,
54}
55
56const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
57    ParamSchema { name, param_type: ty, required: req, description: desc }
58}
59
60/// Operation schema specification for spatial statistics and map algebra capabilities.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct GeoSpatialStatsSpec {
63    pub invoke_id: &'static str,
64    pub call_path: &'static str,
65    pub effect: Effect,
66    pub params: &'static [ParamSchema],
67    pub returns: &'static str,
68    pub description: &'static str,
69}
70
71const fn spec(
72    invoke_id: &'static str, call_path: &'static str, effect: Effect,
73    returns: &'static str, description: &'static str, params: &'static [ParamSchema],
74) -> GeoSpatialStatsSpec {
75    GeoSpatialStatsSpec { invoke_id, call_path, effect, params, returns, description }
76}
77
78/// Declarative specification for a Map Algebra Suitability and Routing Complex.
79#[derive(Debug, Clone, PartialEq)]
80pub struct ComplexDecl {
81    pub name: String,
82    pub complex_id: String,
83    pub states: Vec<String>,
84    pub transitions: Vec<String>,
85    pub invariants: Vec<String>,
86    pub initial_state: String,
87    pub target_state: String,
88}
89
90impl ComplexDecl {
91    pub fn new(
92        name: impl Into<String>, complex_id: impl Into<String>, states: Vec<String>,
93        transitions: Vec<String>, invariants: Vec<String>,
94        initial_state: impl Into<String>, target_state: impl Into<String>,
95    ) -> Self {
96        Self {
97            name: name.into(), complex_id: complex_id.into(), states, transitions,
98            invariants, initial_state: initial_state.into(), target_state: target_state.into(),
99        }
100    }
101
102    pub fn validate(&self) -> Result<(), &'static str> {
103        if self.name.is_empty() { return Err("name must not be empty"); }
104        if self.complex_id.is_empty() { return Err("complex_id must not be empty"); }
105        if self.states.is_empty() { return Err("states must not be empty"); }
106        if self.transitions.is_empty() { return Err("transitions must not be empty"); }
107        if !self.states.contains(&self.initial_state) { return Err("initial_state not in states"); }
108        if !self.states.contains(&self.target_state) { return Err("target_state not in states"); }
109        Ok(())
110    }
111}
112
113/// Convenience alias for `ComplexDecl`.
114pub type MapAlgebraSuitabilityComplexDecl = ComplexDecl;
115
116/// Constructs the declarative `MapAlgebraSuitabilityComplex` specification.
117pub fn map_algebra_suitability_complex_decl() -> ComplexDecl {
118    ComplexDecl::new(
119        "MapAlgebraSuitabilityComplex",
120        "urn:qualia:topology:map-algebra-suitability",
121        vec!["RawBands".into(), "VariogramKriged".into(), "HydroIndicesEvaluated".into(), "AhpWeightedOverlay".into(), "LeastCostRouted".into()],
122        vec!["krige_covariates".into(), "compute_twi_rusle".into(), "compile_cell_algebra".into(), "route_least_cost_network".into()],
123        vec!["ContinuousFieldPreservation".into(), "ZeroNegativeCost".into(), "AcyclicOptimalPath".into(), "DeterministicCellCompilation".into()],
124        "RawBands",
125        "LeastCostRouted",
126    )
127}
128
129/// Canonical sequence of all 16 Spatial Statistics, Map Algebra, and Network invoke IDs.
130pub const GEO_SPATIAL_STATS_ALGEBRA_INVOKE_IDS: &[&str] = &[
131    "GisGp.empirical_variogram", "GisGp.ordinary_kriging", "GisGp.idw_natural_neighbor",
132    "GisGp.morans_i_gearys_c", "GisGp.local_lisa_getis_ord_gi_star", "GisGp.gwr_ripleys_k",
133    "GisGp.viewshed_radial_cumulative", "GisGp.tpi_tri_vrm_geomorphons", "GisGp.map_algebra_cell_compile",
134    "GisGp.zonal_statistics_reclassify", "GisGp.marching_squares_contours", "GisGp.ahp_multi_criteria_overlay",
135    "GisGp.twi_spi_sti_rusle", "GisGp.watershed_cost_distance_lcp", "GisGp.network_astar_isochrone_tsp",
136    "GisGp.network_mst_maxflow_centrality",
137];
138
139/// Canonical sequence of all 16 Spatial Statistics, Map Algebra, and Network raw specs.
140pub const GEO_SPATIAL_STATS_ALGEBRA_RAW: &[GeoSpatialStatsSpec] = &[
141    // 1. Kriging & Spatial Autocorrelation
142    spec("GisGp.empirical_variogram", "gis_gp.empirical_variogram", Effect::Cold, "Record",
143        "Computes experimental empirical variogram from irregular point samples.", &[
144            p("points", ParamType::List, true, "Sample point observations with values"),
145            p("lag_distance", ParamType::F64, true, "Lag bin distance in meters"),
146            p("max_lags", ParamType::U64, true, "Maximum number of lag bins"),
147        ]),
148    spec("GisGp.ordinary_kriging", "gis_gp.ordinary_kriging", Effect::Compute, "Record",
149        "Performs Best Linear Unbiased Prediction (BLUP) ordinary kriging interpolation with variance surface.", &[
150            p("points", ParamType::List, true, "Sample observations with values"),
151            p("variogram_model", ParamType::Str, true, "Fitted model: Spherical, Exponential, or Gaussian"),
152            p("nugget", ParamType::F64, true, "Nugget variance c0"),
153            p("sill", ParamType::F64, true, "Partial sill c"),
154            p("range", ParamType::F64, true, "Spatial correlation range a in meters"),
155            p("target_grid", ParamType::Record, true, "Prediction raster grid specification (bbox, cell_size)"),
156        ]),
157    spec("GisGp.idw_natural_neighbor", "gis_gp.idw_natural_neighbor", Effect::Compute, "FieldRef",
158        "Interpolates scattered points into a continuous raster using IDW or Natural Neighbor (Sibson).", &[
159            p("points", ParamType::List, true, "Scatter observation points with values"),
160            p("method", ParamType::Str, true, "Interpolation method: idw or natural_neighbor"),
161            p("power", ParamType::F64, true, "IDW distance weighting exponent (default 2.0)"),
162            p("radius_or_neighbors", ParamType::F64, true, "Search radius or maximum neighbor count"),
163            p("target_grid", ParamType::Record, true, "Output raster grid extent and cell size"),
164        ]),
165    spec("GisGp.morans_i_gearys_c", "gis_gp.morans_i_gearys_c", Effect::Cold, "Record",
166        "Evaluates global spatial autocorrelation indices (Moran's I and Geary's C) with permutation significance.", &[
167            p("features", ParamType::List, true, "Spatial features with target attribute values"),
168            p("weights_matrix", ParamType::Str, true, "Spatial weights: Queen, Rook, kNN, or InverseDistance"),
169            p("permutations", ParamType::U64, true, "Monte Carlo pseudo p-value permutation count"),
170        ]),
171    spec("GisGp.local_lisa_getis_ord_gi_star", "gis_gp.local_lisa_getis_ord_gi_star", Effect::Cold, "Record",
172        "Computes Local Indicators of Spatial Association (Anselin LISA) and Getis-Ord Gi* hotspot statistics.", &[
173            p("features", ParamType::List, true, "Feature points or polygons with attribute values"),
174            p("distance_band", ParamType::F64, true, "Critical distance threshold or bandwidth in meters"),
175            p("metric", ParamType::Str, true, "Metric to evaluate: lisa or getis_ord_gi_star"),
176        ]),
177    spec("GisGp.gwr_ripleys_k", "gis_gp.gwr_ripleys_k", Effect::Cold, "Record",
178        "Performs Geographically Weighted Regression (GWR) or multi-scale Ripley's K / Besag's L point pattern analysis.", &[
179            p("points", ParamType::List, true, "Point features with dependent and explanatory covariates"),
180            p("analysis", ParamType::Str, true, "Analysis mode: gwr or ripleys_k"),
181            p("bandwidth_or_radii", ParamType::List, true, "Kernel bandwidth or list of evaluation radii"),
182        ]),
183
184    // 2. Viewshed & Terrain Geomorphometry
185    spec("GisGp.viewshed_radial_cumulative", "gis_gp.viewshed_radial_cumulative", Effect::Compute, "FieldRef",
186        "Computes radial or cumulative line-of-sight viewshed visibility over a digital elevation model.", &[
187            p("dem", ParamType::FieldRef, true, "Elevation surface raster field"),
188            p("observer_points", ParamType::List, true, "Observer coordinates and viewer heights"),
189            p("max_distance_m", ParamType::F64, true, "Maximum line-of-sight sight distance in meters"),
190            p("target_offset_m", ParamType::F64, false, "Target above-ground height in meters"),
191            p("cumulative", ParamType::Bool, false, "Cumulative observer count visibility if true"),
192        ]),
193    spec("GisGp.tpi_tri_vrm_geomorphons", "gis_gp.tpi_tri_vrm_geomorphons", Effect::Pure, "Record",
194        "Derives Topographic Position Index (TPI), Terrain Ruggedness (TRI), Vector Ruggedness (VRM), and Geomorphons.", &[
195            p("dem", ParamType::FieldRef, true, "Input digital elevation model surface"),
196            p("scale_radius_cells", ParamType::U64, true, "Neighborhood radius in cells for TPI/TRI/VRM"),
197            p("flatness_threshold_deg", ParamType::F64, true, "Geomorphon zenith/nadir angle threshold in degrees"),
198        ]),
199
200    // 3. Map Algebra, Zonal, Contours & AHP
201    spec("GisGp.map_algebra_cell_compile", "gis_gp.map_algebra_cell_compile", Effect::Pure, "Record",
202        "Compiles a pure VibeScript cell expression into zero-heap map algebra and WGSL compute shader kernel.", &[
203            p("expression_ast", ParamType::Str, true, "Pure VibeScript cell mathematical formula or expression AST"),
204            p("raster_inputs", ParamType::Record, true, "Named map of input raster fields"),
205            p("target_format", ParamType::Str, true, "Target backend: wgsl or zero_heap_simd"),
206        ]),
207    spec("GisGp.zonal_statistics_reclassify", "gis_gp.zonal_statistics_reclassify", Effect::Cold, "Record",
208        "Calculates zonal statistical aggregates over defined spatial zones and performs raster cell value reclassification.", &[
209            p("raster", ParamType::FieldRef, true, "Value raster surface"),
210            p("zones", ParamType::GeometryRef, true, "Zone definitions: polygon feature layer or categorical raster"),
211            p("reclass_table", ParamType::List, false, "Optional slice reclassification mapping rules"),
212        ]),
213    spec("GisGp.marching_squares_contours", "gis_gp.marching_squares_contours", Effect::Cold, "GeometryRef",
214        "Extracts vector isoline contours from a continuous raster grid using the Marching Squares algorithm.", &[
215            p("raster", ParamType::FieldRef, true, "Continuous scalar raster surface"),
216            p("contour_interval", ParamType::F64, true, "Elevation or scalar contour step interval"),
217            p("base_contour", ParamType::F64, false, "Base datum elevation from which intervals are reckoned"),
218            p("smooth_lines", ParamType::Bool, false, "Apply sub-pixel linear interpolation smoothing"),
219        ]),
220    spec("GisGp.ahp_multi_criteria_overlay", "gis_gp.ahp_multi_criteria_overlay", Effect::Cold, "Record",
221        "Executes Saaty Analytic Hierarchy Process (AHP) multi-criteria weighted linear combination suitability overlay.", &[
222            p("criteria_layers", ParamType::List, true, "Normalized criterion raster layers in [0.0, 1.0]"),
223            p("pairwise_matrix", ParamType::List, true, "Saaty 1-9 pairwise comparison matrix rows"),
224            p("suitability_scale", ParamType::Str, false, "Suitability scale: standard_0_100 or unit_interval"),
225        ]),
226
227    // 4. Hydrology, Cost-Distance & Network Topology
228    spec("GisGp.twi_spi_sti_rusle", "gis_gp.twi_spi_sti_rusle", Effect::Compute, "Record",
229        "Derives Topographic Wetness (TWI), Stream Power (SPI), Sediment Transport (STI), and RUSLE soil loss surfaces.", &[
230            p("dem", ParamType::FieldRef, true, "Hydrologically conditioned elevation model"),
231            p("slope_rad", ParamType::FieldRef, true, "Surface slope in radians"),
232            p("flow_accumulation", ParamType::FieldRef, true, "Upslope contributing catchment area"),
233            p("rusle_factors", ParamType::Record, true, "RUSLE parameters (rainfall R, soil K, cover C, practice P)"),
234        ]),
235    spec("GisGp.watershed_cost_distance_lcp", "gis_gp.watershed_cost_distance_lcp", Effect::Cold, "Record",
236        "Calculates cumulative cost distance surface, hydrological watersheds, and Least Cost Path (LCP) corridors.", &[
237            p("friction_surface", ParamType::FieldRef, true, "Traversal resistance / cost raster surface"),
238            p("source_points", ParamType::List, true, "Source origin coordinates"),
239            p("destination_points", ParamType::List, true, "Destination target coordinates for LCP"),
240            p("flow_direction", ParamType::FieldRef, false, "Optional D8 flow direction grid for watershed delineation"),
241        ]),
242    spec("GisGp.network_astar_isochrone_tsp", "gis_gp.network_astar_isochrone_tsp", Effect::Cold, "Record",
243        "Computes turn-restricted A* shortest path, service area isochrones, and Traveling Salesperson (TSP) route.", &[
244            p("network_graph", ParamType::Record, true, "Topological line network with edge weights and turn restrictions"),
245            p("origin", ParamType::Record, true, "Origin coordinate pair"),
246            p("destinations", ParamType::List, true, "Destination coordinate pairs or waypoints"),
247            p("cutoff_cost", ParamType::F64, true, "Maximum impedance cutoff for drive-time / walk-time isochrone polygons"),
248        ]),
249    spec("GisGp.network_mst_maxflow_centrality", "gis_gp.network_mst_maxflow_centrality", Effect::Cold, "Record",
250        "Computes Minimum Spanning Tree (MST), maximum network flow (Edmonds-Karp), and topological centrality indices.", &[
251            p("network_graph", ParamType::Record, true, "Edge capacity, length, and directional connectivity graph"),
252            p("source_node", ParamType::U64, true, "Source terminal node ID"),
253            p("sink_node", ParamType::U64, true, "Sink terminal node ID"),
254            p("centrality_metric", ParamType::Str, true, "Centrality metric: betweenness, closeness, or eigenvector"),
255        ]),
256];
257
258/// Returns the 16 capability schema entries for the catalog.
259pub fn geo_spatial_stats_algebra_entries() -> Vec<CapabilitySchemaEntry> {
260    GEO_SPATIAL_STATS_ALGEBRA_RAW.iter().map(|s| {
261        let effect_class = match s.effect {
262            Effect::Pure => EffectClass::Pure,
263            Effect::Compute | Effect::Cold => EffectClass::Read,
264            Effect::Async | Effect::External => EffectClass::External,
265        };
266        let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
267            .with_description(s.description);
268        for p in s.params {
269            entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
270        }
271        entry
272    }).collect()
273}
274
275/// Standard entrypoint matching the `entries()` convention across all capability modules.
276pub fn entries() -> Vec<SchemaEntry> {
277    geo_spatial_stats_algebra_entries()
278}
279
280/// Looks up a capability schema entry by either invoke ID or lowercase call path.
281pub fn lookup_geo_spatial_stats_algebra_entry(call_path: &str) -> Option<CapabilitySchemaEntry> {
282    let s = GEO_SPATIAL_STATS_ALGEBRA_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)?;
283    let effect_class = match s.effect {
284        Effect::Pure => EffectClass::Pure,
285        Effect::Compute | Effect::Cold => EffectClass::Read,
286        Effect::Async | Effect::External => EffectClass::External,
287    };
288    let mut entry = SchemaEntry::new(s.invoke_id, effect_class, HonestyLabel::Always, s.returns)
289        .with_description(s.description);
290    for p in s.params {
291        entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
292    }
293    Some(entry)
294}
295
296/// Looks up raw operation specification by invoke ID or call path.
297pub fn lookup_geo_spatial_stats_algebra_spec(call_path: &str) -> Option<&'static GeoSpatialStatsSpec> {
298    GEO_SPATIAL_STATS_ALGEBRA_RAW.iter().find(|s| s.call_path == call_path || s.invoke_id == call_path)
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn test_geo_spatial_stats_algebra_count_and_uniqueness() {
307        assert_eq!(GEO_SPATIAL_STATS_ALGEBRA_RAW.len(), 16);
308        assert_eq!(GEO_SPATIAL_STATS_ALGEBRA_INVOKE_IDS.len(), 16);
309        for (i, spec) in GEO_SPATIAL_STATS_ALGEBRA_RAW.iter().enumerate() {
310            assert_eq!(spec.invoke_id, GEO_SPATIAL_STATS_ALGEBRA_INVOKE_IDS[i]);
311            assert!(spec.invoke_id.starts_with("GisGp."));
312            assert!(spec.call_path.starts_with("gis_gp."));
313            assert!(!spec.returns.is_empty());
314            assert!(!spec.description.is_empty());
315        }
316        let mut ids: Vec<&str> = GEO_SPATIAL_STATS_ALGEBRA_INVOKE_IDS.to_vec();
317        ids.sort();
318        ids.dedup();
319        assert_eq!(ids.len(), 16, "All 16 invoke IDs must be unique");
320
321        let mut paths: Vec<&str> = GEO_SPATIAL_STATS_ALGEBRA_RAW.iter().map(|s| s.call_path).collect();
322        paths.sort();
323        paths.dedup();
324        assert_eq!(paths.len(), 16, "All 16 call paths must be unique");
325    }
326
327    #[test]
328    fn test_entries_conversion_and_lookup() {
329        assert!(lookup_geo_spatial_stats_algebra_entry("GisGp.empirical_variogram").is_some());
330        assert!(lookup_geo_spatial_stats_algebra_entry("gis_gp.empirical_variogram").is_some());
331        assert!(lookup_geo_spatial_stats_algebra_entry("GisGp.ordinary_kriging").is_some());
332        assert!(lookup_geo_spatial_stats_algebra_entry("gis_gp.ordinary_kriging").is_some());
333        assert!(lookup_geo_spatial_stats_algebra_entry("GisGp.map_algebra_cell_compile").is_some());
334        assert!(lookup_geo_spatial_stats_algebra_entry("gis_gp.map_algebra_cell_compile").is_some());
335        assert!(lookup_geo_spatial_stats_algebra_entry("GisGp.twi_spi_sti_rusle").is_some());
336        assert!(lookup_geo_spatial_stats_algebra_entry("GisGp.network_astar_isochrone_tsp").is_some());
337        assert!(lookup_geo_spatial_stats_algebra_entry("GisGp.unknown_call").is_none());
338
339        let converted = geo_spatial_stats_algebra_entries();
340        assert_eq!(converted.len(), 16);
341        for (i, entry) in converted.iter().enumerate() {
342            assert_eq!(entry.id, GEO_SPATIAL_STATS_ALGEBRA_INVOKE_IDS[i]);
343            assert_eq!(entry.honesty, HonestyLabel::Always);
344        }
345
346        let alias_entries = entries();
347        assert_eq!(alias_entries.len(), 16);
348    }
349
350    #[test]
351    fn test_map_algebra_suitability_complex_decl_validation() {
352        let decl = map_algebra_suitability_complex_decl();
353        assert!(decl.validate().is_ok());
354        assert_eq!(decl.name, "MapAlgebraSuitabilityComplex");
355        assert_eq!(decl.complex_id, "urn:qualia:topology:map-algebra-suitability");
356        assert_eq!(decl.states.len(), 5);
357        assert_eq!(decl.transitions.len(), 4);
358        assert_eq!(decl.invariants.len(), 4);
359        assert_eq!(decl.initial_state, "RawBands");
360        assert_eq!(decl.target_state, "LeastCostRouted");
361
362        let bad_initial = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "NonExistent", "A");
363        assert!(bad_initial.validate().is_err());
364
365        let bad_target = ComplexDecl::new("C", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "NonExistent");
366        assert!(bad_target.validate().is_err());
367
368        let empty_name = ComplexDecl::new("", "id", vec!["A".into()], vec!["t".into()], vec![], "A", "A");
369        assert!(empty_name.validate().is_err());
370    }
371
372    #[test]
373    fn test_map_algebra_kriging_network_fixture_exists() {
374        let manifest_dir = env!("CARGO_MANIFEST_DIR");
375        let fixture_path = std::path::Path::new(manifest_dir)
376            .join("fixtures")
377            .join("geography")
378            .join("map_algebra_kriging_network.vibe");
379        assert!(
380            fixture_path.exists(),
381            "Fixture map_algebra_kriging_network.vibe must exist at {:?}",
382            fixture_path
383        );
384    }
385}