Skip to main content

vibe/capability_schema/
geo_vector_gp_entries.rs

1//! Vector geoprocessing and planar parcel topology schemas (GEO-S6 / R6-V).
2//!
3//! Provides machine schema definitions for all 24 `GisGp.*` host capability invocations
4//! covering overlay operations (clip, intersection, union, difference, sym_difference,
5//! identity, update), proximity buffers, dissolve, boundary extraction, sliver elimination,
6//! line simplification (Douglas-Peucker, Visvalingam-Whyatt), Chaikin smoothing, convex/concave hulls,
7//! pole of inaccessibility (polylabel), Delaunay/Voronoi, grid tessellations (HexagonFlatTop, etc.),
8//! spatial joins, Hausdorff/Fréchet metrics, KDE raster surface, and DBSCAN/KMeans clustering.
9
10use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
11
12/// Effect classification for VibeScript 0.2 capability operations.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum Effect {
15    Pure, Compute, Cold, Async, External,
16}
17
18impl Effect {
19    pub const fn as_str(&self) -> &'static str {
20        match self {
21            Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
22            Self::Async => "async", Self::External => "external",
23        }
24    }
25}
26
27/// Parameter type for vector geoprocessing operations.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum ParamType {
30    F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
31}
32
33impl ParamType {
34    pub const fn as_str(&self) -> &'static str {
35        match self {
36            Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64",
37            Self::Bool => "bool", Self::Str => "string", Self::Record => "Record",
38            Self::List => "List", Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
39        }
40    }
41}
42
43/// Parameter schema descriptor.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct ParamSchema {
46    pub name: &'static str,
47    pub param_type: ParamType,
48    pub required: bool,
49    pub description: &'static str,
50}
51
52const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
53    ParamSchema { name, param_type: ty, required: req, description: desc }
54}
55
56/// Operation schema descriptor for vector geoprocessing operations.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct OperationSchema {
59    pub invoke_id: &'static str,
60    pub effect: Effect,
61    pub params: &'static [ParamSchema],
62    pub returns: &'static str,
63    pub description: &'static str,
64}
65
66const fn op(id: &'static str, eff: Effect, ret: &'static str, desc: &'static str, params: &'static [ParamSchema]) -> OperationSchema {
67    OperationSchema { invoke_id: id, effect: eff, params, returns: ret, description: desc }
68}
69
70/// Declarative specification for a cadastral planar parcel topology complex.
71#[derive(Debug, Clone, PartialEq)]
72pub struct CadastralTopologyComplexDecl {
73    pub complex_id: String,
74    pub must_not_overlap: bool,
75    pub must_not_have_gaps: bool,
76    pub snap_tolerance_m: f64,
77    pub min_sliver_area_m2: f64,
78    pub crs_epsg: u32,
79}
80
81impl CadastralTopologyComplexDecl {
82    pub fn new(
83        complex_id: impl Into<String>,
84        must_not_overlap: bool,
85        must_not_have_gaps: bool,
86        snap_tolerance_m: f64,
87        min_sliver_area_m2: f64,
88        crs_epsg: u32,
89    ) -> Self {
90        Self {
91            complex_id: complex_id.into(),
92            must_not_overlap,
93            must_not_have_gaps,
94            snap_tolerance_m,
95            min_sliver_area_m2,
96            crs_epsg,
97        }
98    }
99
100    pub fn validate(&self) -> Result<(), &'static str> {
101        if self.complex_id.is_empty() { return Err("complex_id must not be empty"); }
102        if self.snap_tolerance_m <= 0.0 { return Err("snap_tolerance_m must be greater than zero"); }
103        if self.min_sliver_area_m2 <= 0.0 { return Err("min_sliver_area_m2 must be greater than zero"); }
104        if self.crs_epsg == 0 { return Err("crs_epsg must be greater than zero"); }
105        Ok(())
106    }
107}
108
109/// Canonical sequence of all 24 Vector Geoprocessing capability invoke IDs.
110pub const GEO_VECTOR_GP_INVOKE_IDS: &[&str] = &[
111    "GisGp.clip", "GisGp.intersection", "GisGp.union", "GisGp.difference",
112    "GisGp.sym_difference", "GisGp.identity_overlay", "GisGp.update_overlay", "GisGp.buffer",
113    "GisGp.multi_ring_buffer", "GisGp.dissolve", "GisGp.polygon_to_lines",
114    "GisGp.snap_eliminate_slivers", "GisGp.simplify_dp", "GisGp.simplify_vw",
115    "GisGp.smooth_chaikin", "GisGp.convex_hull", "GisGp.concave_hull",
116    "GisGp.centroid_polylabel", "GisGp.delaunay_voronoi", "GisGp.tessellate_grid",
117    "GisGp.spatial_join", "GisGp.hausdorff_frechet", "GisGp.kernel_density",
118    "GisGp.cluster_dbscan_kmeans",
119];
120
121/// Canonical sequence of all 24 Vector Geoprocessing operation schemas.
122pub const GEO_VECTOR_GP_OPERATIONS: &[OperationSchema] = &[
123    op("GisGp.clip", Effect::Cold, "GeometryRef", "Clip input geometry layer to the extent of a clipping mask polygon.", &[
124        p("input", ParamType::GeometryRef, true, "Input geometry or layer"),
125        p("clip_mask", ParamType::GeometryRef, true, "Clipping mask polygon geometry"),
126    ]),
127    op("GisGp.intersection", Effect::Cold, "GeometryRef", "Compute topological intersection of two geometries preserving attributes.", &[
128        p("geom_a", ParamType::GeometryRef, true, "First input geometry"),
129        p("geom_b", ParamType::GeometryRef, true, "Second input geometry"),
130    ]),
131    op("GisGp.union", Effect::Cold, "GeometryRef", "Compute topological union of two geometries or planar polygonal partitions.", &[
132        p("geom_a", ParamType::GeometryRef, true, "First input geometry"),
133        p("geom_b", ParamType::GeometryRef, true, "Second input geometry"),
134    ]),
135    op("GisGp.difference", Effect::Cold, "GeometryRef", "Compute topological difference (erase) removing mask from input geometry.", &[
136        p("input", ParamType::GeometryRef, true, "Base geometry"),
137        p("erase_mask", ParamType::GeometryRef, true, "Mask geometry to erase from input"),
138    ]),
139    op("GisGp.sym_difference", Effect::Cold, "GeometryRef", "Compute symmetrical difference (exclusive OR) between two geometries.", &[
140        p("geom_a", ParamType::GeometryRef, true, "First input geometry"),
141        p("geom_b", ParamType::GeometryRef, true, "Second input geometry"),
142    ]),
143    op("GisGp.identity_overlay", Effect::Cold, "GeometryRef", "Compute geometric intersection with identity retaining all input features.", &[
144        p("input", ParamType::GeometryRef, true, "Input primary geometry"),
145        p("identity_layer", ParamType::GeometryRef, true, "Identity overlay geometry"),
146    ]),
147    op("GisGp.update_overlay", Effect::Cold, "GeometryRef", "Update input geometry by replacing overlapping regions with update geometry.", &[
148        p("input", ParamType::GeometryRef, true, "Base input geometry"),
149        p("update_geom", ParamType::GeometryRef, true, "Replacement geometry stamp"),
150    ]),
151    op("GisGp.buffer", Effect::Cold, "GeometryRef", "Generate fixed-distance buffer zone polygon around input geometry.", &[
152        p("geom", ParamType::GeometryRef, true, "Input geometry"),
153        p("distance_m", ParamType::F64, true, "Buffer distance in meters"),
154        p("quad_segs", ParamType::U64, false, "Segments per quadrant (default 8)"),
155    ]),
156    op("GisGp.multi_ring_buffer", Effect::Cold, "Record", "Generate concentric multi-ring buffer zones at specified radial intervals.", &[
157        p("geom", ParamType::GeometryRef, true, "Input geometry"),
158        p("distances", ParamType::List, true, "List of increasing buffer distances in meters"),
159        p("dissolve", ParamType::Bool, false, "Whether to dissolve rings into non-overlapping bands"),
160    ]),
161    op("GisGp.dissolve", Effect::Cold, "GeometryRef", "Dissolve boundaries between adjacent polygons sharing identical attributes.", &[
162        p("geoms", ParamType::List, true, "List of input polygon geometries"),
163        p("by_field", ParamType::Str, false, "Optional attribute field name to group and dissolve by"),
164    ]),
165    op("GisGp.polygon_to_lines", Effect::Cold, "GeometryRef", "Extract planar boundary linestrings and shared cadastral boundary edges from polygons.", &[
166        p("geom", ParamType::GeometryRef, true, "Input polygon or multipolygon"),
167        p("identify_shared", ParamType::Bool, false, "Label shared inter-parcel edges"),
168    ]),
169    op("GisGp.snap_eliminate_slivers", Effect::Cold, "Record", "Snap adjacent vertices within tolerance and merge sliver polygons into neighbors.", &[
170        p("geoms", ParamType::List, true, "Cadastral polygon parcel collection"),
171        p("snap_tolerance_m", ParamType::F64, true, "Vertex snapping tolerance in meters"),
172        p("min_sliver_area_m2", ParamType::F64, true, "Minimum area threshold for sliver polygon elimination"),
173    ]),
174    op("GisGp.simplify_dp", Effect::Pure, "GeometryRef", "Simplify geometry vertices using Douglas-Peucker polyline decimation.", &[
175        p("geom", ParamType::GeometryRef, true, "Input geometry"),
176        p("tolerance_m", ParamType::F64, true, "Perpendicular distance error tolerance in meters"),
177    ]),
178    op("GisGp.simplify_vw", Effect::Cold, "GeometryRef", "Simplify geometry vertices using Visvalingam-Whyatt area-based effective triangles.", &[
179        p("geom", ParamType::GeometryRef, true, "Input geometry"),
180        p("min_area_m2", ParamType::F64, true, "Minimum triangle area threshold in square meters"),
181    ]),
182    op("GisGp.smooth_chaikin", Effect::Cold, "GeometryRef", "Smooth polyline or polygon rings using Chaikin corner-cutting subdivision.", &[
183        p("geom", ParamType::GeometryRef, true, "Input polyline or polygon geometry"),
184        p("iterations", ParamType::U64, false, "Subdivision refinement passes (1..5, default 2)"),
185    ]),
186    op("GisGp.convex_hull", Effect::Cold, "GeometryRef", "Compute smallest convex bounding polygon enclosing input points or geometry vertices.", &[
187        p("geom", ParamType::GeometryRef, true, "Input geometry or point collection"),
188    ]),
189    op("GisGp.concave_hull", Effect::Cold, "GeometryRef", "Compute alpha-shape concave hull boundary hugging the geometry perimeter.", &[
190        p("geom", ParamType::GeometryRef, true, "Input geometry or point collection"),
191        p("concavity_alpha", ParamType::F64, true, "Concavity factor or alpha parameter (0.0..1.0)"),
192    ]),
193    op("GisGp.centroid_polylabel", Effect::Pure, "Record", "Compute visual centroid or pole of inaccessibility (polylabel) inside polygon interior.", &[
194        p("geom", ParamType::GeometryRef, true, "Input polygon geometry"),
195        p("precision", ParamType::F64, false, "Convergence precision tolerance (default 1.0)"),
196    ]),
197    op("GisGp.delaunay_voronoi", Effect::Cold, "Record", "Construct 2D Delaunay triangulation and dual Voronoi Thiessen polygon partition.", &[
198        p("points", ParamType::List, true, "Seed point locations or coordinate pairs"),
199        p("clip_extent", ParamType::Record, false, "Bounding envelope for Voronoi diagram boundary"),
200    ]),
201    op("GisGp.tessellate_grid", Effect::Cold, "Record", "Generate regular spatial tessellation covering bounding envelope.", &[
202        p("bbox", ParamType::Record, true, "Bounding box extent record (min_x, min_y, max_x, max_y)"),
203        p("cell_shape", ParamType::Str, true, "Tessellation shape: HexagonFlatTop, HexagonPointyTop, Square, Triangle"),
204        p("cell_size_m", ParamType::F64, true, "Hexagon diameter or cell edge size in meters"),
205    ]),
206    op("GisGp.spatial_join", Effect::Cold, "Record", "Perform spatial predicate join transferring target attributes to source features.", &[
207        p("target_layer", ParamType::List, true, "Target feature geometries to receive attributes"),
208        p("join_layer", ParamType::List, true, "Join feature geometries providing attributes"),
209        p("match_predicate", ParamType::Str, true, "Topological predicate: Intersects, Within, Contains, Closest"),
210        p("join_type", ParamType::Str, false, "Join cardinality: OneToOne or OneToMany"),
211    ]),
212    op("GisGp.hausdorff_frechet", Effect::Pure, "Record", "Compute Hausdorff and discrete Fréchet trajectory similarity distance metrics.", &[
213        p("geom_a", ParamType::GeometryRef, true, "First polyline or polygon boundary"),
214        p("geom_b", ParamType::GeometryRef, true, "Second polyline or polygon boundary"),
215    ]),
216    op("GisGp.kernel_density", Effect::Compute, "FieldRef", "Compute 2D kernel density estimation (KDE) surface over point events with bandwidth.", &[
217        p("points", ParamType::List, true, "Input point locations with optional weights"),
218        p("bandwidth_m", ParamType::F64, true, "Kernel search radius bandwidth in meters"),
219        p("cell_size_m", ParamType::F64, true, "Output raster surface grid cell resolution in meters"),
220    ]),
221    op("GisGp.cluster_dbscan_kmeans", Effect::Cold, "Record", "Cluster spatial points using density-based DBSCAN or centroid-based K-Means.", &[
222        p("points", ParamType::List, true, "Input point coordinates list"),
223        p("algorithm", ParamType::Str, true, "Clustering algorithm: dbscan or kmeans"),
224        p("eps_or_k", ParamType::F64, true, "Epsilon neighborhood radius (DBSCAN) or cluster count k (KMeans)"),
225        p("min_points", ParamType::U64, false, "Minimum core points for DBSCAN (unused for KMeans)"),
226    ]),
227];
228
229/// Looks up a Vector Geoprocessing operation schema by its canonical invoke ID.
230pub fn lookup_geo_vector_gp_operation(invoke_id: &str) -> Option<&'static OperationSchema> {
231    GEO_VECTOR_GP_OPERATIONS.iter().find(|op| op.invoke_id == invoke_id)
232}
233
234/// Returns the 24 Vector Geoprocessing capability schema entries for the catalog.
235pub fn entries() -> Vec<SchemaEntry> {
236    GEO_VECTOR_GP_OPERATIONS.iter().map(|op| {
237        let effect_class = match op.effect {
238            Effect::Pure => EffectClass::Pure,
239            Effect::Compute | Effect::Cold => EffectClass::Read,
240            Effect::Async | Effect::External => EffectClass::External,
241        };
242        let mut entry = SchemaEntry::new(op.invoke_id, effect_class, HonestyLabel::Always, op.returns)
243            .with_description(op.description);
244        for p in op.params {
245            entry = entry.with_arg(SchemaArg::new(p.name, p.param_type.as_str(), p.required).with_description(p.description));
246        }
247        entry
248    }).collect()
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn test_geo_vector_gp_operations_count_and_uniqueness() {
257        assert_eq!(GEO_VECTOR_GP_OPERATIONS.len(), 24);
258        assert_eq!(GEO_VECTOR_GP_INVOKE_IDS.len(), 24);
259        for (i, op) in GEO_VECTOR_GP_OPERATIONS.iter().enumerate() {
260            assert_eq!(op.invoke_id, GEO_VECTOR_GP_INVOKE_IDS[i]);
261            assert!(op.invoke_id.starts_with("GisGp."));
262            assert!(!op.returns.is_empty());
263            assert!(!op.description.is_empty());
264        }
265        let mut ids: Vec<&str> = GEO_VECTOR_GP_INVOKE_IDS.to_vec();
266        ids.sort();
267        ids.dedup();
268        assert_eq!(ids.len(), 24, "All 24 invoke IDs must be unique");
269    }
270
271    #[test]
272    fn test_entries_conversion_and_lookup() {
273        assert!(lookup_geo_vector_gp_operation("GisGp.clip").is_some());
274        assert!(lookup_geo_vector_gp_operation("GisGp.buffer").is_some());
275        assert!(lookup_geo_vector_gp_operation("GisGp.snap_eliminate_slivers").is_some());
276        assert!(lookup_geo_vector_gp_operation("GisGp.delaunay_voronoi").is_some());
277        assert!(lookup_geo_vector_gp_operation("GisGp.kernel_density").is_some());
278        assert!(lookup_geo_vector_gp_operation("GisGp.cluster_dbscan_kmeans").is_some());
279        assert!(lookup_geo_vector_gp_operation("GisGp.unknown_op").is_none());
280
281        let converted = entries();
282        assert_eq!(converted.len(), 24);
283        for (i, entry) in converted.iter().enumerate() {
284            assert_eq!(entry.id, GEO_VECTOR_GP_INVOKE_IDS[i]);
285            assert_eq!(entry.honesty, HonestyLabel::Always);
286        }
287    }
288
289    #[test]
290    fn test_cadastral_topology_complex_decl_validation() {
291        let valid = CadastralTopologyComplexDecl::new(
292            "snowy_cadastral_fabric", true, true, 0.05, 1.0, 7855,
293        );
294        assert!(valid.validate().is_ok());
295        assert!(valid.must_not_overlap);
296        assert!(valid.must_not_have_gaps);
297        assert_eq!(valid.snap_tolerance_m, 0.05);
298        assert_eq!(valid.min_sliver_area_m2, 1.0);
299        assert_eq!(valid.crs_epsg, 7855);
300
301        let empty_id = CadastralTopologyComplexDecl::new("", true, true, 0.05, 1.0, 7855);
302        assert!(empty_id.validate().is_err());
303
304        let zero_snap = CadastralTopologyComplexDecl::new("test", true, true, 0.0, 1.0, 7855);
305        assert!(zero_snap.validate().is_err());
306
307        let neg_sliver = CadastralTopologyComplexDecl::new("test", true, true, 0.05, -1.0, 7855);
308        assert!(neg_sliver.validate().is_err());
309
310        let zero_crs = CadastralTopologyComplexDecl::new("test", true, true, 0.05, 1.0, 0);
311        assert!(zero_crs.validate().is_err());
312    }
313
314    #[test]
315    fn test_vector_geoprocessing_fixture_exists() {
316        let manifest_dir = env!("CARGO_MANIFEST_DIR");
317        let fixture_path = std::path::Path::new(manifest_dir)
318            .join("fixtures")
319            .join("geography")
320            .join("vector_geoprocessing.vibe");
321        assert!(
322            fixture_path.exists(),
323            "Fixture vector_geoprocessing.vibe must exist at {:?}",
324            fixture_path
325        );
326    }
327}