Skip to main content

qualia_core_db/domains/biosphere/
microbial_colony.rs

1//! Microbial colony, biofilm dynamics, and multi-scale coordinate transforms.
2//!
3//! Enforces the BIO-MC-1 fail-closed scale-band rule to prevent unit confusion
4//! when projecting nanometer/micrometer microbial coordinates into millimeter
5//! scene space, alongside Monod/logistic biofilm growth and zero-heap NQuin emission.
6
7use crate::foundation::frame_layout::pack_float_object;
8use crate::query::resolver::INLINE_TAG_INTEGER;
9use crate::{q_hash, NQuin};
10
11/// Physical measurement scale-bands spanning microscopic to macroscopic realms.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(u8)]
14pub enum ScaleBandUnit {
15    Nanometer = 0,
16    Micrometer = 1,
17    Millimeter = 2,
18    Meter = 3,
19}
20
21/// Coordinate frame anchoring local microbial space to macroscopic scene millimeter space.
22#[derive(Debug, Clone, Copy, PartialEq)]
23#[repr(C)]
24pub struct ScaleBandFrame {
25    pub unit: ScaleBandUnit,
26    pub origin_scene_mm: [f64; 3],
27    pub um_per_local_unit: f64,
28}
29
30/// Explicit affine transformation across scale-bands.
31#[derive(Debug, Clone, Copy, PartialEq)]
32#[repr(C)]
33pub struct ScaleBandTransform {
34    pub source_unit: ScaleBandUnit,
35    pub target_unit: ScaleBandUnit,
36    pub scale_factor: f64,
37    pub translation_mm: [f64; 3],
38}
39
40/// Taxon classification for microbial agents.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42#[repr(u8)]
43pub enum MicrobialTaxonKind {
44    Cyanobacteria = 0,
45    Rhizobia = 1,
46    Actinobacteria = 2,
47    DiatomMicroalgae = 3,
48}
49
50/// Physiological and population state of a microbial colony/biofilm.
51#[derive(Debug, Clone, Copy, PartialEq)]
52#[repr(C)]
53pub struct MicrobialColonyState {
54    pub colony_id: u64,
55    pub taxon: MicrobialTaxonKind,
56    pub cell_count: f64,
57    pub cell_length_um: f32,
58    pub cell_width_um: f32,
59    pub division_rate_per_hour: f32,
60    pub quorum_sensing_concentration_nm: f32,
61    pub biofilm_eps_thickness_um: f32,
62    pub substrate_nutrient_concentration: f32,
63}
64
65/// Errors occurring during microbial colony simulation or projection.
66#[derive(Debug, Clone, PartialEq)]
67pub enum MicrobialError {
68    MissingScaleBandTransform,
69    IncompatibleScaleBandUnit { expected: ScaleBandUnit, actual: ScaleBandUnit },
70    InvalidCoordinate(f64),
71    NegativeParameter(f32),
72    BufferOverflow { needed: usize, available: usize },
73}
74
75impl std::fmt::Display for MicrobialError {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        match self {
78            Self::MissingScaleBandTransform => write!(f, "BIO-MC-1: Missing explicit ScaleBandTransform for micro/nano coordinates"),
79            Self::IncompatibleScaleBandUnit { expected, actual } => {
80                write!(f, "Incompatible scale band unit: expected {expected:?}, got {actual:?}")
81            }
82            Self::InvalidCoordinate(c) => write!(f, "Invalid non-finite coordinate: {c}"),
83            Self::NegativeParameter(p) => write!(f, "Negative parameter: {p}"),
84            Self::BufferOverflow { needed, available } => write!(f, "Buffer overflow: needed {needed}, got {available}"),
85        }
86    }
87}
88
89impl std::error::Error for MicrobialError {}
90
91pub const PRED_MICROBIAL_TAXON: u64 = q_hash("qualia:biosphere#microbialTaxon");
92pub const PRED_CELL_COUNT: u64 = q_hash("qualia:biosphere#cellCount");
93pub const PRED_QUORUM_SENSING: u64 = q_hash("qualia:biosphere#quorumSensingConcentration");
94pub const PRED_BIOFILM_EPS_THICKNESS: u64 = q_hash("qualia:biosphere#biofilmEpsThickness");
95pub const PRED_SUBSTRATE_NUTRIENT: u64 = q_hash("qualia:biosphere#substrateNutrientConcentration");
96pub const METADATA_PROVENANCE_SIMULATION: u64 = 1u64 << 28;
97
98/// BIO-MC-1: Projects local microbial coordinates into scene millimeter coordinates.
99///
100/// Fails closed (`Err(MicrobialError::MissingScaleBandTransform)`) whenever
101/// `Micrometer` or `Nanometer` coordinates are mixed into scene space without an
102/// explicit `ScaleBandTransform` (or when `transform.source_unit != pos_unit`).
103pub fn project_microbial_to_scene_mm_checked(
104    local_pos: [f64; 3],
105    pos_unit: ScaleBandUnit,
106    transform: Option<&ScaleBandTransform>,
107) -> Result<[f64; 3], MicrobialError> {
108    for &c in &local_pos {
109        if !c.is_finite() {
110            return Err(MicrobialError::InvalidCoordinate(c));
111        }
112    }
113
114    match pos_unit {
115        ScaleBandUnit::Micrometer | ScaleBandUnit::Nanometer => {
116            let t = transform.ok_or(MicrobialError::MissingScaleBandTransform)?;
117            if t.source_unit != pos_unit {
118                return Err(MicrobialError::IncompatibleScaleBandUnit {
119                    expected: t.source_unit,
120                    actual: pos_unit,
121                });
122            }
123            if t.target_unit != ScaleBandUnit::Millimeter {
124                return Err(MicrobialError::IncompatibleScaleBandUnit {
125                    expected: ScaleBandUnit::Millimeter,
126                    actual: t.target_unit,
127                });
128            }
129            Ok([
130                local_pos[0] * t.scale_factor + t.translation_mm[0],
131                local_pos[1] * t.scale_factor + t.translation_mm[1],
132                local_pos[2] * t.scale_factor + t.translation_mm[2],
133            ])
134        }
135        ScaleBandUnit::Millimeter => {
136            if let Some(t) = transform {
137                if t.source_unit != ScaleBandUnit::Millimeter {
138                    return Err(MicrobialError::IncompatibleScaleBandUnit {
139                        expected: t.source_unit,
140                        actual: pos_unit,
141                    });
142                }
143                Ok([
144                    local_pos[0] * t.scale_factor + t.translation_mm[0],
145                    local_pos[1] * t.scale_factor + t.translation_mm[1],
146                    local_pos[2] * t.scale_factor + t.translation_mm[2],
147                ])
148            } else {
149                Ok(local_pos)
150            }
151        }
152        ScaleBandUnit::Meter => {
153            if let Some(t) = transform {
154                if t.source_unit != ScaleBandUnit::Meter {
155                    return Err(MicrobialError::IncompatibleScaleBandUnit {
156                        expected: t.source_unit,
157                        actual: pos_unit,
158                    });
159                }
160                Ok([
161                    local_pos[0] * t.scale_factor + t.translation_mm[0],
162                    local_pos[1] * t.scale_factor + t.translation_mm[1],
163                    local_pos[2] * t.scale_factor + t.translation_mm[2],
164                ])
165            } else {
166                Ok([local_pos[0] * 1000.0, local_pos[1] * 1000.0, local_pos[2] * 1000.0])
167            }
168        }
169    }
170}
171
172/// Zero-heap step executing Monod kinetics, logistic carrying capacity, and quorum-sensing EPS production.
173pub fn step_microbial_biofilm_zero_heap(
174    colony: &mut MicrobialColonyState,
175    dt_hours: f32,
176    substrate_replenishment_rate: f32,
177) -> Result<(), MicrobialError> {
178    if dt_hours < 0.0 || !dt_hours.is_finite() {
179        return Err(MicrobialError::NegativeParameter(dt_hours));
180    }
181    if substrate_replenishment_rate < 0.0 || !substrate_replenishment_rate.is_finite() {
182        return Err(MicrobialError::NegativeParameter(substrate_replenishment_rate));
183    }
184    if colony.cell_count < 0.0
185        || colony.substrate_nutrient_concentration < 0.0
186        || colony.quorum_sensing_concentration_nm < 0.0
187        || colony.biofilm_eps_thickness_um < 0.0
188    {
189        return Err(MicrobialError::NegativeParameter(colony.substrate_nutrient_concentration));
190    }
191
192    let s = colony.substrate_nutrient_concentration;
193    let ks = 0.5f32; // Monod half-saturation constant
194    let monod = if s > 0.0 { s / (ks + s) } else { 0.0 };
195    let mu = colony.division_rate_per_hour * monod;
196
197    let carrying_capacity = 1.0e11f64;
198    let n = colony.cell_count;
199    let dn = n * (mu as f64) * (1.0 - (n / carrying_capacity)).max(0.0) * (dt_hours as f64);
200    colony.cell_count = (n + dn).max(0.0);
201
202    let yield_coeff = 1.0e9f64; // cells per unit nutrient
203    let substrate_consumed = (dn / yield_coeff) as f32;
204    colony.substrate_nutrient_concentration =
205        (s - substrate_consumed + substrate_replenishment_rate * dt_hours).max(0.0);
206
207    // Quorum sensing autoinducer accumulation
208    let qs_produced = (colony.cell_count * 1.0e-9) as f32 * dt_hours;
209    colony.quorum_sensing_concentration_nm += qs_produced;
210
211    // Quorum-sensing threshold triggers biofilm EPS secretion
212    if colony.quorum_sensing_concentration_nm >= 10.0 {
213        let eps_rate = 0.15f32; // um per hour
214        colony.biofilm_eps_thickness_um += eps_rate * dt_hours;
215    }
216
217    Ok(())
218}
219
220/// Emits parity-valid NQuins representing microbial colony and biofilm status.
221pub fn emit_microbial_quins_zero_heap(
222    colony: &MicrobialColonyState,
223    origin_did_hash: u64,
224    is_simulation: bool,
225    out_quins: &mut [NQuin],
226) -> Result<usize, MicrobialError> {
227    if out_quins.len() < 5 {
228        return Err(MicrobialError::BufferOverflow { needed: 5, available: out_quins.len() });
229    }
230
231    let prov = if is_simulation { METADATA_PROVENANCE_SIMULATION } else { 0 };
232    let metadata = (0b01u64 << 61) | prov;
233    let subj = origin_did_hash ^ colony.colony_id;
234
235    let props: [(u64, u64); 5] = [
236        (PRED_MICROBIAL_TAXON, INLINE_TAG_INTEGER | (colony.taxon as u64)),
237        (PRED_CELL_COUNT, pack_float_object(colony.cell_count as f32)),
238        (PRED_QUORUM_SENSING, pack_float_object(colony.quorum_sensing_concentration_nm)),
239        (PRED_BIOFILM_EPS_THICKNESS, pack_float_object(colony.biofilm_eps_thickness_um)),
240        (PRED_SUBSTRATE_NUTRIENT, pack_float_object(colony.substrate_nutrient_concentration)),
241    ];
242
243    for (idx, (pred, obj)) in props.into_iter().enumerate() {
244        let parity = NQuin::calculate_parity(subj, pred, obj, origin_did_hash, metadata);
245        out_quins[idx] = NQuin { subject: subj, predicate: pred, object: obj, context: origin_did_hash, metadata, parity };
246    }
247
248    Ok(5)
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::specialized_libs::computational_geometry::allocation_counter::assert_zero_alloc;
255
256    #[test]
257    fn test_missing_scale_band_transform_fails_closed() {
258        let pos = [100.0, 200.0, 50.0];
259        let err = project_microbial_to_scene_mm_checked(pos, ScaleBandUnit::Micrometer, None);
260        assert_eq!(err, Err(MicrobialError::MissingScaleBandTransform));
261
262        let err_nano = project_microbial_to_scene_mm_checked(pos, ScaleBandUnit::Nanometer, None);
263        assert_eq!(err_nano, Err(MicrobialError::MissingScaleBandTransform));
264    }
265
266    #[test]
267    fn test_incompatible_scale_band_unit_fails() {
268        let pos = [100.0, 200.0, 50.0];
269        let t = ScaleBandTransform {
270            source_unit: ScaleBandUnit::Nanometer,
271            target_unit: ScaleBandUnit::Millimeter,
272            scale_factor: 1e-6,
273            translation_mm: [0.0, 0.0, 0.0],
274        };
275        let err = project_microbial_to_scene_mm_checked(pos, ScaleBandUnit::Micrometer, Some(&t));
276        assert!(matches!(err, Err(MicrobialError::IncompatibleScaleBandUnit { .. })));
277    }
278
279    #[test]
280    fn test_scale_band_projection_success() {
281        let pos_um = [1000.0, 2000.0, 500.0];
282        let t = ScaleBandTransform {
283            source_unit: ScaleBandUnit::Micrometer,
284            target_unit: ScaleBandUnit::Millimeter,
285            scale_factor: 0.001,
286            translation_mm: [10.0, 20.0, 30.0],
287        };
288        let scene_mm = project_microbial_to_scene_mm_checked(pos_um, ScaleBandUnit::Micrometer, Some(&t)).unwrap();
289        assert!((scene_mm[0] - 11.0).abs() < 1e-6);
290        assert!((scene_mm[1] - 22.0).abs() < 1e-6);
291        assert!((scene_mm[2] - 30.5).abs() < 1e-6);
292    }
293
294    #[test]
295    fn test_biofilm_growth_and_quorum_sensing() {
296        let mut colony = MicrobialColonyState {
297            colony_id: 1,
298            taxon: MicrobialTaxonKind::Cyanobacteria,
299            cell_count: 1.0e6,
300            cell_length_um: 4.0,
301            cell_width_um: 1.0,
302            division_rate_per_hour: 0.2,
303            quorum_sensing_concentration_nm: 0.0,
304            biofilm_eps_thickness_um: 0.5,
305            substrate_nutrient_concentration: 5.0,
306        };
307
308        step_microbial_biofilm_zero_heap(&mut colony, 10.0, 0.1).unwrap();
309        assert!(colony.cell_count > 1.0e6);
310        assert!(colony.quorum_sensing_concentration_nm > 0.0);
311
312        // High quorum sensing triggers EPS thickening
313        colony.quorum_sensing_concentration_nm = 15.0;
314        let eps_before = colony.biofilm_eps_thickness_um;
315        step_microbial_biofilm_zero_heap(&mut colony, 2.0, 0.1).unwrap();
316        assert!(colony.biofilm_eps_thickness_um > eps_before);
317    }
318
319    #[test]
320    fn test_negative_parameter_rejected() {
321        let mut colony = MicrobialColonyState {
322            colony_id: 1,
323            taxon: MicrobialTaxonKind::Rhizobia,
324            cell_count: 1.0e5,
325            cell_length_um: 2.0,
326            cell_width_um: 0.8,
327            division_rate_per_hour: 0.3,
328            quorum_sensing_concentration_nm: 1.0,
329            biofilm_eps_thickness_um: 0.1,
330            substrate_nutrient_concentration: 2.0,
331        };
332        assert!(step_microbial_biofilm_zero_heap(&mut colony, -1.0, 0.1).is_err());
333    }
334
335    #[test]
336    fn test_emit_microbial_quins_and_zero_heap() {
337        let colony = MicrobialColonyState {
338            colony_id: 77,
339            taxon: MicrobialTaxonKind::Actinobacteria,
340            cell_count: 5.0e7,
341            cell_length_um: 3.5,
342            cell_width_um: 0.6,
343            division_rate_per_hour: 0.15,
344            quorum_sensing_concentration_nm: 12.5,
345            biofilm_eps_thickness_um: 1.8,
346            substrate_nutrient_concentration: 3.2,
347        };
348
349        let mut out = [NQuin::default(); 5];
350        assert_zero_alloc("emit_microbial_quins", || {
351            let count = emit_microbial_quins_zero_heap(&colony, 9999, false, &mut out).unwrap();
352            assert_eq!(count, 5);
353        });
354
355        for q in out.iter() {
356            assert!(q.verify_ecc_parity());
357            assert_eq!((q.metadata >> 28) & 1, 0); // FieldObservation
358        }
359
360        let mut small_out = [NQuin::default(); 2];
361        let err = emit_microbial_quins_zero_heap(&colony, 9999, false, &mut small_out);
362        assert!(matches!(err, Err(MicrobialError::BufferOverflow { .. })));
363    }
364}