1use super::{EffectClass, HonestyLabel, SchemaArg, SchemaEntry};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum Effect {
12 Pure,
13 Compute,
14 Cold,
15 Async,
16 External,
17}
18
19impl Effect {
20 pub const fn as_str(&self) -> &'static str {
21 match self {
22 Self::Pure => "pure", Self::Compute => "compute", Self::Cold => "cold",
23 Self::Async => "async", Self::External => "external",
24 }
25 }
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ParamType {
31 F64, I64, U64, Bool, Str, Record, List, FieldRef, GeometryRef,
32}
33
34impl ParamType {
35 pub const fn as_str(&self) -> &'static str {
36 match self {
37 Self::F64 => "f64", Self::I64 => "i64", Self::U64 => "u64",
38 Self::Bool => "bool", Self::Str => "string", Self::Record => "Record",
39 Self::List => "List", Self::FieldRef => "FieldRef", Self::GeometryRef => "GeometryRef",
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ParamSchema {
47 pub name: &'static str,
48 pub param_type: ParamType,
49 pub required: bool,
50 pub description: &'static str,
51}
52
53const fn p(name: &'static str, ty: ParamType, req: bool, desc: &'static str) -> ParamSchema {
54 ParamSchema { name, param_type: ty, required: req, description: desc }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub struct OperationSchema {
60 pub invoke_id: &'static str,
61 pub effect: Effect,
62 pub params: &'static [ParamSchema],
63 pub returns: &'static str,
64 pub description: &'static str,
65}
66
67const fn op(id: &'static str, eff: Effect, ret: &'static str, desc: &'static str, params: &'static [ParamSchema]) -> OperationSchema {
68 OperationSchema { invoke_id: id, effect: eff, params, returns: ret, description: desc }
69}
70
71pub const STRATA_6_LAYER_NAMES: [&str; 6] = [
73 "bedrock", "saprolite", "regolith", "sand", "silt", "snow_ice",
74];
75
76#[derive(Debug, Clone, PartialEq)]
78pub struct StrataColumnComplexDecl {
79 pub name: String,
80 pub m64_submagic: u8,
81 pub sentinel2_province: u16,
82 pub bedrock: f64,
83 pub saprolite: f64,
84 pub regolith: f64,
85 pub sand: f64,
86 pub silt: f64,
87 pub snow_ice: f64,
88}
89
90impl StrataColumnComplexDecl {
91 pub const EXPECTED_SUBMAGIC: u8 = 0x02;
92
93 pub fn new(
94 name: impl Into<String>, m64_submagic: u8, sentinel2_province: u16,
95 bedrock: f64, saprolite: f64, regolith: f64, sand: f64, silt: f64, snow_ice: f64,
96 ) -> Self {
97 Self {
98 name: name.into(), m64_submagic, sentinel2_province,
99 bedrock, saprolite, regolith, sand, silt, snow_ice,
100 }
101 }
102
103 pub fn from_layers(
104 name: impl Into<String>, m64_submagic: u8, sentinel2_province: u16, layers: [f64; 6],
105 ) -> Self {
106 Self::new(
107 name, m64_submagic, sentinel2_province,
108 layers[0], layers[1], layers[2], layers[3], layers[4], layers[5],
109 )
110 }
111
112 pub fn layer_thicknesses(&self) -> [f64; 6] {
113 [self.bedrock, self.saprolite, self.regolith, self.sand, self.silt, self.snow_ice]
114 }
115
116 pub fn total_thickness(&self) -> f64 {
117 self.bedrock + self.saprolite + self.regolith + self.sand + self.silt + self.snow_ice
118 }
119
120 pub fn validate(&self) -> Result<(), &'static str> {
121 if self.m64_submagic != Self::EXPECTED_SUBMAGIC {
122 return Err("m64_submagic must equal 0x02 for StrataColumnComplex");
123 }
124 for &t in &self.layer_thicknesses() {
125 if t < 0.0 || t.is_nan() || t.is_infinite() {
126 return Err("all 6 layer thicknesses must be finite non-negative values");
127 }
128 }
129 if self.bedrock <= 0.0 {
130 return Err("bedrock base layer thickness must be strictly positive");
131 }
132 if self.sentinel2_province >= 323 {
133 return Err("sentinel2_province must be in range 0..322 for ESA Sentinel-2 LUT");
134 }
135 Ok(())
136 }
137
138 pub fn is_expected_layer(index: usize, name: &str) -> bool {
139 STRATA_6_LAYER_NAMES.get(index).map_or(false, |&expected| expected == name)
140 }
141}
142
143pub const GEO_GEOMORPH_STRATA_INVOKE_IDS: &[&str] = &[
145 "Terrain.erode_fixed824", "Terrain.erode_coupled_6species", "Terrain.erode_droplet",
146 "Terrain.carve_meander_channel", "Terrain.hydro_priority_flood", "Terrain.hydro_flow_dinf",
147 "Terrain.hydro_fastscape_spl", "Terrain.coastal_wave_cliff", "Terrain.thermal_talus_creep",
148 "Terrain.landslide_debris_runout", "Terrain.glacier_sia_carve", "Terrain.snow_wind_avalanche",
149 "Terrain.aeolian_sand_saltation", "Terrain.strata_pack_m64", "Terrain.strata_constituents8",
150 "Terrain.sentinel2_biome_albedo", "Terrain.geomorph_qa_audit",
151];
152
153pub const GEO_GEOMORPH_STRATA_OPERATIONS: &[OperationSchema] = &[
155 op("Terrain.erode_fixed824", Effect::Cold, "FieldRef", "Bit-exact 8.24 fixed-point hydraulic pipe step.", &[
156 p("input", ParamType::FieldRef, true, "Input elevation field"), p("dt_secs", ParamType::F64, true, "Delta time in seconds"), p("iterations", ParamType::U64, true, "Iteration count"), p("rain_rate", ParamType::F64, true, "Rainfall in mm/hr"), p("pipe_len_m", ParamType::F64, true, "Pipe length in meters"),
157 ]),
158 op("Terrain.erode_coupled_6species", Effect::Cold, "FieldRef", "Coupled 6-species bedrock/saprolite/regolith/sand/silt/snow erosion.", &[
159 p("input", ParamType::FieldRef, true, "Input elevation field"), p("strata", ParamType::Record, true, "6-layer strata thickness record"), p("dt_years", ParamType::F64, true, "Geological time step in years"), p("shear_stress", ParamType::F64, true, "Critical shear threshold"), p("carrying_capacity", ParamType::F64, true, "Sediment capacity factor"),
160 ]),
161 op("Terrain.erode_droplet", Effect::Cold, "FieldRef", "Lagrangian particle droplet erosion.", &[
162 p("input", ParamType::FieldRef, true, "Input elevation field"), p("droplet_count", ParamType::U64, true, "Droplet count"), p("inertia", ParamType::F64, true, "Momentum inertia factor"), p("capacity", ParamType::F64, true, "Sediment capacity coefficient"), p("evaporation", ParamType::F64, true, "Evaporation rate"),
163 ]),
164 op("Terrain.carve_meander_channel", Effect::Cold, "FieldRef", "Asymmetric cutbank/point-bar river meander carve.", &[
165 p("input", ParamType::FieldRef, true, "Input elevation field"), p("curvature_weight", ParamType::F64, true, "Meander curvature weight"), p("cutbank_steepness", ParamType::F64, true, "Outer cutbank steepness"), p("point_bar_deposit", ParamType::F64, true, "Inner bar deposition factor"),
166 ]),
167 op("Terrain.hydro_priority_flood", Effect::Cold, "FieldRef", "Barnes 2014 pit filling & breach carving.", &[
168 p("input", ParamType::FieldRef, true, "Input elevation field"), p("min_slope_deg", ParamType::F64, true, "Minimum gradient slope in degrees"), p("carve_breaches", ParamType::Bool, true, "Carve depression breaches"),
169 ]),
170 op("Terrain.hydro_flow_dinf", Effect::Cold, "FieldRef", "Tarboton 1997 D-Infinity & D8 flow accumulation.", &[
171 p("input", ParamType::FieldRef, true, "Conditioned elevation field"), p("use_dinf", ParamType::Bool, true, "D-Infinity continuous routing"), p("weight_field", ParamType::FieldRef, false, "Runoff weight field"),
172 ]),
173 op("Terrain.hydro_fastscape_spl", Effect::Cold, "FieldRef", "Implicit O(N) FastScape Stream Power Law bedrock incision.", &[
174 p("input", ParamType::FieldRef, true, "Input elevation field"), p("k_coeff", ParamType::F64, true, "Erodibility K"), p("m_exp", ParamType::F64, true, "Area exponent m"), p("n_exp", ParamType::F64, true, "Slope exponent n"), p("uplift_rate", ParamType::F64, true, "Uplift rate m/yr"), p("dt_years", ParamType::F64, true, "Time step years"),
175 ]),
176 op("Terrain.coastal_wave_cliff", Effect::Cold, "FieldRef", "Coastal wave-cut notch, terrace & cliff collapse.", &[
177 p("input", ParamType::FieldRef, true, "Coastal elevation field"), p("sea_level_m", ParamType::F64, true, "Sea level in meters"), p("wave_energy", ParamType::F64, true, "Wave energy coefficient"), p("cliff_collapse_angle_deg", ParamType::F64, true, "Collapse angle degrees"), p("notch_depth_m", ParamType::F64, true, "Notch depth meters"),
178 ]),
179 op("Terrain.thermal_talus_creep", Effect::Cold, "FieldRef", "8-neighbor anisotropic talus creep & freeze-thaw weathering.", &[
180 p("input", ParamType::FieldRef, true, "Input elevation field"), p("repose_angle_deg", ParamType::F64, true, "Repose angle in degrees"), p("talus_rate", ParamType::F64, true, "Diffusion creep rate"), p("freeze_thaw_cycles", ParamType::U64, true, "Freeze-thaw cycles"),
181 ]),
182 op("Terrain.landslide_debris_runout", Effect::Cold, "Record", "Mohr-Coulomb infinite-slope failure & debris runout.", &[
183 p("input", ParamType::FieldRef, true, "Input elevation field"), p("friction_angle_deg", ParamType::F64, true, "Internal friction angle phi"), p("cohesion_kpa", ParamType::F64, true, "Cohesion c in kPa"), p("pore_pressure_ratio", ParamType::F64, true, "Ru pore pressure factor"),
184 ]),
185 op("Terrain.glacier_sia_carve", Effect::Cold, "FieldRef", "Shallow Ice Approximation alpine glacier flow & basal quarrying.", &[
186 p("input", ParamType::FieldRef, true, "Topography field"), p("ela_alt_m", ParamType::F64, true, "ELA altitude in meters"), p("sliding_coeff", ParamType::F64, true, "Basal sliding coefficient"), p("quarrying_rate", ParamType::F64, true, "Plucking abrasion rate"), p("dt_years", ParamType::F64, true, "Epoch years"),
187 ]),
188 op("Terrain.snow_wind_avalanche", Effect::Cold, "FieldRef", "Wind snow drift transport & critical slope avalanche.", &[
189 p("input", ParamType::FieldRef, true, "Input elevation field"), p("wind_direction_deg", ParamType::F64, true, "Wind azimuth degrees"), p("wind_speed_m_s", ParamType::F64, true, "Wind speed m/s"), p("critical_slope_deg", ParamType::F64, true, "Avalanche slope degrees"), p("deposition_rate", ParamType::F64, true, "Deposition fraction"),
190 ]),
191 op("Terrain.aeolian_sand_saltation", Effect::Cold, "FieldRef", "Werner saltation & barchan dune slipface avalanche.", &[
192 p("input", ParamType::FieldRef, true, "Terrain field"), p("wind_bearing_deg", ParamType::F64, true, "Wind direction degrees"), p("shear_velocity", ParamType::F64, true, "Friction velocity u*"), p("saltation_length_m", ParamType::F64, true, "Hop length in meters"), p("slipface_angle_deg", ParamType::F64, true, "Slipface angle degrees"),
193 ]),
194 op("Terrain.strata_pack_m64", Effect::Compute, "Record", "Pack 6-layer stratigraphic column into 64B .m64 0x02 cells with CRC-32C.", &[
195 p("elevation", ParamType::FieldRef, true, "Elevation field"), p("strata_layers", ParamType::Record, true, "6-layer thicknesses"), p("cell_resolution_m", ParamType::F64, true, "Grid spacing in meters"), p("sentinel2_province", ParamType::U64, true, "Sentinel-2 province ID [0..322]"),
196 ]),
197 op("Terrain.strata_constituents8", Effect::Pure, "Record", "Extract 8 normalized surface constituent splat weights.", &[
198 p("strata_column", ParamType::Record, true, ".m64 strata container record"), p("surface_depth_m", ParamType::F64, true, "Sampling depth in meters"),
199 ]),
200 op("Terrain.sentinel2_biome_albedo", Effect::Pure, "Record", "Evaluate 323-province ESA Sentinel-2 L2A biome spectral LUT.", &[
201 p("strata_column", ParamType::Record, true, ".m64 strata container record"), p("province_id", ParamType::U64, true, "ESA Sentinel-2 biome province ID [0..322]"),
202 ]),
203 op("Terrain.geomorph_qa_audit", Effect::Compute, "Record", "Compute Hypsometric Integral, Strahler Rb, Hack's h, concavity theta, and mass conservation gate.", &[
204 p("initial_terrain", ParamType::FieldRef, true, "Pre-erosion topography field"), p("eroded_terrain", ParamType::FieldRef, true, "Post-erosion topography field"), p("tolerance_mass_kg", ParamType::F64, true, "Mass discrepancy tolerance"),
205 ]),
206];
207
208pub fn lookup_geo_geomorph_strata_operation(invoke_id: &str) -> Option<&'static OperationSchema> {
210 GEO_GEOMORPH_STRATA_OPERATIONS.iter().find(|op| op.invoke_id == invoke_id)
211}
212
213pub fn entries() -> Vec<SchemaEntry> {
215 GEO_GEOMORPH_STRATA_OPERATIONS
216 .iter()
217 .map(|op| {
218 let effect_class = match op.effect {
219 Effect::Pure => EffectClass::Pure,
220 Effect::Compute | Effect::Cold => EffectClass::Read,
221 Effect::Async | Effect::External => EffectClass::External,
222 };
223 let mut entry = SchemaEntry::new(
224 op.invoke_id,
225 effect_class,
226 HonestyLabel::Always,
227 op.returns,
228 )
229 .with_description(op.description);
230 for p in op.params {
231 entry = entry.with_arg(
232 SchemaArg::new(p.name, p.param_type.as_str(), p.required)
233 .with_description(p.description),
234 );
235 }
236 entry
237 })
238 .collect()
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn test_geomorph_strata_operations_count_and_uniqueness() {
247 assert_eq!(GEO_GEOMORPH_STRATA_OPERATIONS.len(), 17);
248 assert_eq!(GEO_GEOMORPH_STRATA_INVOKE_IDS.len(), 17);
249 for (i, op) in GEO_GEOMORPH_STRATA_OPERATIONS.iter().enumerate() {
250 assert_eq!(op.invoke_id, GEO_GEOMORPH_STRATA_INVOKE_IDS[i]);
251 assert!(op.invoke_id.starts_with("Terrain."));
252 assert!(!op.returns.is_empty());
253 assert!(!op.description.is_empty());
254 }
255 let mut ids: Vec<&str> = GEO_GEOMORPH_STRATA_INVOKE_IDS.to_vec();
256 ids.sort();
257 ids.dedup();
258 assert_eq!(ids.len(), 17, "All 17 Geomorph Strata invoke IDs must be unique");
259 }
260
261 #[test]
262 fn test_entries_conversion_and_lookup() {
263 assert!(lookup_geo_geomorph_strata_operation("Terrain.erode_fixed824").is_some());
264 assert!(lookup_geo_geomorph_strata_operation("Terrain.strata_pack_m64").is_some());
265 assert!(lookup_geo_geomorph_strata_operation("Terrain.geomorph_qa_audit").is_some());
266 assert!(lookup_geo_geomorph_strata_operation("Terrain.unknown_op").is_none());
267
268 let converted = entries();
269 assert_eq!(converted.len(), 17);
270 for (i, entry) in converted.iter().enumerate() {
271 assert_eq!(entry.id, GEO_GEOMORPH_STRATA_INVOKE_IDS[i]);
272 assert_eq!(entry.honesty, HonestyLabel::Always);
273 }
274 }
275
276 #[test]
277 fn test_strata_column_complex_decl_validation() {
278 let valid = StrataColumnComplexDecl::new(
279 "kosciuszko_glacial_strata",
280 0x02,
281 0,
282 850.0,
283 18.0,
284 6.0,
285 3.5,
286 1.5,
287 2.0,
288 );
289 assert!(valid.validate().is_ok());
290 assert_eq!(valid.total_thickness(), 881.0);
291 assert_eq!(valid.layer_thicknesses().len(), 6);
292
293 for (idx, name) in STRATA_6_LAYER_NAMES.iter().enumerate() {
294 assert!(StrataColumnComplexDecl::is_expected_layer(idx, name));
295 }
296
297 let bad_magic = StrataColumnComplexDecl::new("test", 0x01, 0, 800.0, 10.0, 5.0, 3.0, 1.0, 1.0);
298 assert!(bad_magic.validate().is_err());
299
300 let neg_thickness = StrataColumnComplexDecl::new("test", 0x02, 0, 800.0, -10.0, 5.0, 3.0, 1.0, 1.0);
301 assert!(neg_thickness.validate().is_err());
302
303 let zero_bedrock = StrataColumnComplexDecl::new("test", 0x02, 0, 0.0, 10.0, 5.0, 3.0, 1.0, 1.0);
304 assert!(zero_bedrock.validate().is_err());
305
306 let bad_province = StrataColumnComplexDecl::new("test", 0x02, 323, 800.0, 10.0, 5.0, 3.0, 1.0, 1.0);
307 assert!(bad_province.validate().is_err());
308 }
309
310 #[test]
311 fn test_strata_column_fixture_exists() {
312 let manifest_dir = env!("CARGO_MANIFEST_DIR");
313 let fixture_path = std::path::Path::new(manifest_dir)
314 .join("fixtures")
315 .join("geography")
316 .join("strata_column_complex.vibe");
317 assert!(
318 fixture_path.exists(),
319 "Fixture strata_column_complex.vibe must exist at {:?}",
320 fixture_path
321 );
322 }
323}