qualia_core_db/domains/biosphere/
ecological_coupling.rs1use crate::foundation::frame_layout::pack_float_object;
8use crate::query::resolver::INLINE_TAG_INTEGER;
9use crate::{q_hash, NQuin};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(u8)]
14pub enum TrophicCouplingKind {
15 EctomycorrhizalCarbonPhosphorusExchange = 0,
17 ArbuscularMycorrhizalUptake = 1,
19 RhizobialNitrogenFixation = 2,
21 SaprotrophicLitterDecomposition = 3,
23 AvianInsectPollination = 4,
25 SoilMoistureCanopyTranspiration = 5,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq)]
31#[repr(C)]
32pub struct EcologicalCouplingSpec {
33 pub source_entity_did_hash: u64,
35 pub target_entity_did_hash: u64,
37 pub coupling_kind: TrophicCouplingKind,
39 pub flux_rate: f32,
41 pub min_soil_moisture: f32,
43 pub max_soil_moisture: f32,
45 pub temperature_optimum_c: f32,
47 pub is_simulation: bool,
49 pub active: bool,
51}
52
53#[derive(Debug, Clone, PartialEq)]
55pub enum CouplingError {
56 InvalidMoisture(f32),
57 NegativeFluxRate(f32),
58 BufferOverflow { needed: usize, available: usize },
59 InvalidThreshold { min: f32, max: f32 },
60}
61
62impl std::fmt::Display for CouplingError {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 match self {
65 Self::InvalidMoisture(m) => write!(f, "Invalid moisture {m}; must be in [0.0, 1.0]"),
66 Self::NegativeFluxRate(flux) => write!(f, "Negative flux rate: {flux}"),
67 Self::BufferOverflow { needed, available } => {
68 write!(f, "Buffer overflow: needed {needed}, got {available}")
69 }
70 Self::InvalidThreshold { min, max } => {
71 write!(f, "Invalid moisture thresholds: min {min} must be <= max {max} within [0.0, 1.0]")
72 }
73 }
74 }
75}
76
77impl std::error::Error for CouplingError {}
78
79pub const PRED_TROPHIC_COUPLING_KIND: u64 = q_hash("qualia:biosphere#trophicCouplingKind");
80pub const PRED_TROPHIC_EXCHANGE_FLUX: u64 = q_hash("qualia:biosphere#trophicExchangeFlux");
81
82pub const METADATA_PROVENANCE_SIMULATION: u64 = 1u64 << 28;
84
85pub fn evaluate_ecological_coupling_zero_heap(
90 couplings: &[EcologicalCouplingSpec],
91 soil_moisture: f32,
92 out_quins: &mut [NQuin],
93) -> Result<usize, CouplingError> {
94 if soil_moisture < 0.0 || soil_moisture > 1.0 || !soil_moisture.is_finite() {
95 return Err(CouplingError::InvalidMoisture(soil_moisture));
96 }
97
98 for spec in couplings.iter() {
99 if spec.flux_rate < 0.0 || !spec.flux_rate.is_finite() {
100 return Err(CouplingError::NegativeFluxRate(spec.flux_rate));
101 }
102 if spec.min_soil_moisture < 0.0
103 || spec.max_soil_moisture > 1.0
104 || spec.min_soil_moisture > spec.max_soil_moisture
105 || !spec.min_soil_moisture.is_finite()
106 || !spec.max_soil_moisture.is_finite()
107 {
108 return Err(CouplingError::InvalidThreshold {
109 min: spec.min_soil_moisture,
110 max: spec.max_soil_moisture,
111 });
112 }
113 }
114
115 let needed = couplings.len() * 2;
116 if out_quins.len() < needed {
117 return Err(CouplingError::BufferOverflow {
118 needed,
119 available: out_quins.len(),
120 });
121 }
122
123 let mut idx = 0;
124 for spec in couplings.iter() {
125 let active_flux = if spec.active
126 && soil_moisture >= spec.min_soil_moisture
127 && soil_moisture <= spec.max_soil_moisture
128 {
129 let span = (spec.max_soil_moisture - spec.min_soil_moisture).max(1e-4);
130 let norm = (soil_moisture - spec.min_soil_moisture) / span;
131 let factor = (4.0 * norm * (1.0 - norm)).clamp(0.0, 1.0);
133 spec.flux_rate * factor
134 } else {
135 0.0
136 };
137
138 let prov = if spec.is_simulation {
139 METADATA_PROVENANCE_SIMULATION
140 } else {
141 0
142 };
143 let metadata = (0b01u64 << 61) | prov;
144 let subj = spec.source_entity_did_hash;
145 let ctx = spec.target_entity_did_hash;
146
147 let obj_kind = INLINE_TAG_INTEGER | (spec.coupling_kind as u64);
149 let p1 = NQuin::calculate_parity(subj, PRED_TROPHIC_COUPLING_KIND, obj_kind, ctx, metadata);
150 out_quins[idx] = NQuin {
151 subject: subj,
152 predicate: PRED_TROPHIC_COUPLING_KIND,
153 object: obj_kind,
154 context: ctx,
155 metadata,
156 parity: p1,
157 };
158 idx += 1;
159
160 let obj_flux = pack_float_object(active_flux);
162 let p2 = NQuin::calculate_parity(subj, PRED_TROPHIC_EXCHANGE_FLUX, obj_flux, ctx, metadata);
163 out_quins[idx] = NQuin {
164 subject: subj,
165 predicate: PRED_TROPHIC_EXCHANGE_FLUX,
166 object: obj_flux,
167 context: ctx,
168 metadata,
169 parity: p2,
170 };
171 idx += 1;
172 }
173
174 Ok(idx)
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180 use crate::foundation::frame_layout::unpack_float_object;
181 use crate::specialized_libs::computational_geometry::allocation_counter::assert_zero_alloc;
182
183 #[test]
184 fn test_coupling_moisture_gating() {
185 let specs = [EcologicalCouplingSpec {
186 source_entity_did_hash: 100,
187 target_entity_did_hash: 200,
188 coupling_kind: TrophicCouplingKind::EctomycorrhizalCarbonPhosphorusExchange,
189 flux_rate: 10.0,
190 min_soil_moisture: 0.2,
191 max_soil_moisture: 0.8,
192 temperature_optimum_c: 22.0,
193 is_simulation: true,
194 active: true,
195 }];
196
197 let mut out = [NQuin::default(); 2];
198
199 evaluate_ecological_coupling_zero_heap(&specs, 0.5, &mut out).unwrap();
201 let flux_mid = unpack_float_object(out[1].object);
202 assert!((flux_mid - 10.0).abs() < 1e-4);
203
204 evaluate_ecological_coupling_zero_heap(&specs, 0.1, &mut out).unwrap();
206 let flux_low = unpack_float_object(out[1].object);
207 assert_eq!(flux_low, 0.0);
208 }
209
210 #[test]
211 fn test_provenance_bit_encoding() {
212 let specs = [
213 EcologicalCouplingSpec {
214 source_entity_did_hash: 1,
215 target_entity_did_hash: 2,
216 coupling_kind: TrophicCouplingKind::RhizobialNitrogenFixation,
217 flux_rate: 5.0,
218 min_soil_moisture: 0.1,
219 max_soil_moisture: 0.9,
220 temperature_optimum_c: 20.0,
221 is_simulation: false, active: true,
223 },
224 EcologicalCouplingSpec {
225 source_entity_did_hash: 3,
226 target_entity_did_hash: 4,
227 coupling_kind: TrophicCouplingKind::AvianInsectPollination,
228 flux_rate: 2.0,
229 min_soil_moisture: 0.0,
230 max_soil_moisture: 1.0,
231 temperature_optimum_c: 25.0,
232 is_simulation: true, active: true,
234 },
235 ];
236
237 let mut out = [NQuin::default(); 4];
238 evaluate_ecological_coupling_zero_heap(&specs, 0.4, &mut out).unwrap();
239
240 for q in &out {
242 assert!(q.verify_ecc_parity());
243 }
244 assert_eq!((out[0].metadata >> 28) & 1, 0);
246 assert_eq!((out[1].metadata >> 28) & 1, 0);
247 assert_eq!((out[2].metadata >> 28) & 1, 1);
249 assert_eq!((out[3].metadata >> 28) & 1, 1);
250 }
251
252 #[test]
253 fn test_negative_cases_rejected() {
254 let invalid_flux = [EcologicalCouplingSpec {
255 source_entity_did_hash: 1,
256 target_entity_did_hash: 2,
257 coupling_kind: TrophicCouplingKind::SaprotrophicLitterDecomposition,
258 flux_rate: -3.0, min_soil_moisture: 0.2,
260 max_soil_moisture: 0.8,
261 temperature_optimum_c: 20.0,
262 is_simulation: true,
263 active: true,
264 }];
265 let mut out = [NQuin::default(); 2];
266 assert!(evaluate_ecological_coupling_zero_heap(&invalid_flux, 0.5, &mut out).is_err());
267
268 let valid = [EcologicalCouplingSpec {
269 source_entity_did_hash: 1,
270 target_entity_did_hash: 2,
271 coupling_kind: TrophicCouplingKind::SaprotrophicLitterDecomposition,
272 flux_rate: 3.0,
273 min_soil_moisture: 0.2,
274 max_soil_moisture: 0.8,
275 temperature_optimum_c: 20.0,
276 is_simulation: true,
277 active: true,
278 }];
279 assert!(evaluate_ecological_coupling_zero_heap(&valid, 1.5, &mut out).is_err());
281 assert!(evaluate_ecological_coupling_zero_heap(&valid, -0.1, &mut out).is_err());
282
283 let mut small_out = [NQuin::default(); 1];
285 assert!(matches!(
286 evaluate_ecological_coupling_zero_heap(&valid, 0.5, &mut small_out),
287 Err(CouplingError::BufferOverflow { .. })
288 ));
289 }
290
291 #[test]
292 fn test_ecological_coupling_zero_heap() {
293 let specs = [EcologicalCouplingSpec {
294 source_entity_did_hash: 55,
295 target_entity_did_hash: 66,
296 coupling_kind: TrophicCouplingKind::SoilMoistureCanopyTranspiration,
297 flux_rate: 15.0,
298 min_soil_moisture: 0.15,
299 max_soil_moisture: 0.85,
300 temperature_optimum_c: 24.0,
301 is_simulation: true,
302 active: true,
303 }];
304
305 let mut out = [NQuin::default(); 2];
306 assert_zero_alloc("evaluate_ecological_coupling", || {
307 let count = evaluate_ecological_coupling_zero_heap(&specs, 0.5, &mut out).unwrap();
308 assert_eq!(count, 2);
309 });
310 assert!(out[0].verify_ecc_parity());
311 assert!(out[1].verify_ecc_parity());
312 }
313}