Skip to main content

qualia_core_db/modalities/
accrual.rs

1//! Accrual, slow variables, and irreversible loss modality (§GAP-11, accrual.md).
2//!
3//! Models standing stocks with multi-dimensional time-depth (biomass, habitat structure,
4//! hydrological function, genetic distinctness, custodial relation), temporal asymmetry
5//! (formation time vs destruction time), and irreversibility classes (`AC-AX-1` to `AC-AX-6`).
6//! Zero-heap hot path.
7
8use crate::q_hash;
9
10/// Maturity class representing temporal depth of an entity.
11#[repr(u8)]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
13pub enum MaturityClass {
14    /// Recently established; little accumulated time-depth.
15    #[default]
16    Juvenile = 0,
17    /// Reached reproductive/functional maturity.
18    Mature = 1,
19    /// Old-growth depth — centuries-scale structure present.
20    OldGrowth = 2,
21    /// Multi-century continuous presence.
22    Centennial = 3,
23    /// Millennial or longer accrual (e.g. ancient soil, custodial lineage).
24    DeepTime = 4,
25}
26
27impl MaturityClass {
28    /// Decode a `u8` into the maturity class; out-of-range values map to
29    /// `Juvenile`.
30    pub const fn from_u8(val: u8) -> Self {
31        match val {
32            0 => Self::Juvenile,
33            1 => Self::Mature,
34            2 => Self::OldGrowth,
35            3 => Self::Centennial,
36            4 => Self::DeepTime,
37            _ => Self::Juvenile,
38        }
39    }
40}
41
42/// Irreversibility classification of loss or degradation.
43#[repr(u8)]
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
45pub enum IrreversibilityClass {
46    /// Readily reversible within seasonal or short horizons (months to few years).
47    #[default]
48    Reversible = 0,
49    /// Slow recovery within standard planning horizons (decades; e.g. biomass regrowth).
50    SlowReversible = 1,
51    /// Recovery horizon exceeds human planning timescale (>100 years; e.g. tree hollows, mature soil profile).
52    HorizonExceeding = 2,
53    /// Irreversible loss (extinction, erased language/custodial lineage).
54    Absolute = 3,
55}
56
57impl IrreversibilityClass {
58    /// Decode a `u8` into the irreversibility class; out-of-range values map
59    /// to `Reversible` (the least-severe default).
60    pub const fn from_u8(val: u8) -> Self {
61        match val {
62            0 => Self::Reversible,
63            1 => Self::SlowReversible,
64            2 => Self::HorizonExceeding,
65            3 => Self::Absolute,
66            _ => Self::Reversible,
67        }
68    }
69}
70
71/// Multi-dimensional accrual profile representing non-collapsible slow variables.
72#[derive(Debug, Clone, Copy, PartialEq, Default)]
73pub struct AccrualProfile {
74    /// Biomass stock magnitude (normalised or physical kg).
75    pub biomass: f32,
76    /// Structural habitat complexity (e.g. tree hollows, complex deadwood).
77    pub structural_complexity: f32,
78    /// Hydrological retention / water-cycle buffering function.
79    pub hydrological_function: f32,
80    /// Genetic and phylogenetic distinctness.
81    pub genetic_distinctness: f32,
82    /// Custodial and cultural relationship depth.
83    pub custodial_depth: f32,
84}
85
86impl AccrualProfile {
87    /// Scale profile by a factor in `[0.0, 1.0]`.
88    pub fn scale(&self, factor: f32) -> Self {
89        let f = factor.clamp(0.0, 1.0);
90        Self {
91            biomass: self.biomass * f,
92            structural_complexity: self.structural_complexity * f,
93            hydrological_function: self.hydrological_function * f,
94            genetic_distinctness: self.genetic_distinctness * f,
95            custodial_depth: self.custodial_depth * f,
96        }
97    }
98
99    /// Subtract lost profile from base, saturating at 0.0.
100    pub fn subtract(&self, lost: &Self) -> Self {
101        Self {
102            biomass: (self.biomass - lost.biomass).max(0.0),
103            structural_complexity: (self.structural_complexity - lost.structural_complexity)
104                .max(0.0),
105            hydrological_function: (self.hydrological_function - lost.hydrological_function)
106                .max(0.0),
107            genetic_distinctness: (self.genetic_distinctness - lost.genetic_distinctness).max(0.0),
108            custodial_depth: (self.custodial_depth - lost.custodial_depth).max(0.0),
109        }
110    }
111}
112
113/// A standing ecological or social stock entity (`AC-AX-1`).
114#[derive(Debug, Clone, Copy, PartialEq)]
115pub struct StockEntity {
116    /// Identity of the stock (subject hash).
117    pub entity_id: u64,
118    /// Temporal-depth classification.
119    pub maturity: MaturityClass,
120    /// Observed age of continuous accrual in years.
121    pub accrual_age_years: f32,
122    /// Declared formation timescale in seconds (e.g. 30 years).
123    pub formation_time_s: u64,
124    /// Destruction vulnerability timescale in seconds (e.g. 2 nights).
125    pub destruction_time_s: u64,
126    /// Current multi-dimensional accrual state.
127    pub profile: AccrualProfile,
128    /// Baseline irreversibility class for losses to this stock.
129    pub irreversibility: IrreversibilityClass,
130}
131
132/// Compute the temporal asymmetry ratio (`AC-AX-3`): `formation_time / destruction_time`.
133/// Higher values denote greater fragility and slow-variable vulnerability.
134pub fn asymmetry_ratio(formation_time_s: u64, destruction_time_s: u64) -> f64 {
135    if destruction_time_s == 0 {
136        f64::INFINITY
137    } else {
138        formation_time_s as f64 / destruction_time_s as f64
139    }
140}
141
142/// An acute loss or destruction event (`AC-AX-6`).
143#[derive(Debug, Clone, Copy, PartialEq)]
144pub struct LossEvent {
145    /// Identity of the event.
146    pub event_id: u64,
147    /// Stock the event applies to.
148    pub stock_id: u64,
149    /// `q_hash` of the cause IRI (e.g. `event:bushfire`).
150    pub cause_hash: u64,
151    /// Event time (seconds since epoch).
152    pub timestamp_epoch: u32,
153    /// Extent of destruction in percentage `[0.0, 100.0]`.
154    pub extent_loss_pct: f32,
155    /// Overrides the stock's baseline irreversibility when the event itself
156    /// changes the recovery class (e.g. topsoil sterilisation).
157    pub irreversibility_override: Option<IrreversibilityClass>,
158}
159
160/// Outcome report of an accrual loss event.
161#[derive(Debug, Clone, Copy, PartialEq)]
162pub struct AccrualLossReport {
163    /// Stock the report describes.
164    pub stock_id: u64,
165    /// Irreversibility applied (event override or stock baseline).
166    pub effective_irreversibility: IrreversibilityClass,
167    /// Profile before the event.
168    pub pre_loss_profile: AccrualProfile,
169    /// Profile magnitude destroyed by the event.
170    pub lost_profile: AccrualProfile,
171    /// Profile remaining after the event.
172    pub residual_profile: AccrualProfile,
173    /// True when the loss crosses a critical slow-variable threshold
174    /// (≥20% HorizonExceeding/Absolute loss, or ≥50% depletion of structural
175    /// complexity or genetic distinctness).
176    pub is_critical_stock_breached: bool,
177}
178
179/// Evaluates the impact of a loss event on a standing stock entity.
180/// Zero-heap hot path.
181pub fn eval_accrual_loss(stock: &StockEntity, event: &LossEvent) -> AccrualLossReport {
182    let loss_fraction = (event.extent_loss_pct / 100.0).clamp(0.0, 1.0);
183    let lost_profile = stock.profile.scale(loss_fraction);
184    let residual_profile = stock.profile.subtract(&lost_profile);
185
186    let effective_irreversibility = event
187        .irreversibility_override
188        .unwrap_or(stock.irreversibility);
189
190    // Critical stock breached if loss is HorizonExceeding or Absolute and exceeds 20% extent,
191    // or if structural hollows / genetic distinctness are depleted past 50%.
192    let is_critical_stock_breached = matches!(
193        effective_irreversibility,
194        IrreversibilityClass::HorizonExceeding | IrreversibilityClass::Absolute
195    ) && (loss_fraction >= 0.20
196        || lost_profile.structural_complexity >= stock.profile.structural_complexity * 0.50
197        || lost_profile.genetic_distinctness >= stock.profile.genetic_distinctness * 0.50);
198
199    AccrualLossReport {
200        stock_id: stock.entity_id,
201        effective_irreversibility,
202        pre_loss_profile: stock.profile,
203        lost_profile,
204        residual_profile,
205        is_critical_stock_breached,
206    }
207}
208
209/// Predicate URI for loss event in graph assertions (`accrual:LossEvent`).
210#[inline]
211pub fn loss_event_predicate() -> u64 {
212    q_hash("qualia:accrual:LossEvent")
213}
214
215/// Predicate URI for irreversibility class (`accrual:irreversibilityClass`).
216#[inline]
217pub fn irreversibility_predicate() -> u64 {
218    q_hash("qualia:accrual:irreversibilityClass")
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn test_asymmetry_ratio() {
227        // 30 years growth (~946,080,000s) vs 2 nights burn (~172,800s)
228        let thirty_years = 30 * 365 * 86400;
229        let two_nights = 2 * 86400;
230        let ratio = asymmetry_ratio(thirty_years, two_nights);
231        assert!((ratio - 5475.0).abs() < 1.0);
232    }
233
234    #[test]
235    fn test_eval_accrual_loss_critical_breach() {
236        let stock = StockEntity {
237            entity_id: 0x111,
238            maturity: MaturityClass::OldGrowth,
239            accrual_age_years: 120.0,
240            formation_time_s: 120 * 365 * 86400,
241            destruction_time_s: 2 * 86400,
242            profile: AccrualProfile {
243                biomass: 5000.0,
244                structural_complexity: 85.0,
245                hydrological_function: 90.0,
246                genetic_distinctness: 75.0,
247                custodial_depth: 95.0,
248            },
249            irreversibility: IrreversibilityClass::HorizonExceeding,
250        };
251
252        // 80% destruction fire event
253        let fire_event = LossEvent {
254            event_id: 0x999,
255            stock_id: 0x111,
256            cause_hash: q_hash("event:bushfire"),
257            timestamp_epoch: 1700000000,
258            extent_loss_pct: 80.0,
259            irreversibility_override: None,
260        };
261
262        let report = eval_accrual_loss(&stock, &fire_event);
263        assert_eq!(
264            report.effective_irreversibility,
265            IrreversibilityClass::HorizonExceeding
266        );
267        assert!(report.is_critical_stock_breached);
268        assert_eq!(report.lost_profile.structural_complexity, 68.0);
269        assert_eq!(report.residual_profile.structural_complexity, 17.0);
270    }
271
272    #[test]
273    fn test_eval_accrual_loss_reversible() {
274        let stock = StockEntity {
275            entity_id: 0x222,
276            maturity: MaturityClass::Juvenile,
277            accrual_age_years: 1.0,
278            formation_time_s: 365 * 86400,
279            destruction_time_s: 7 * 86400,
280            profile: AccrualProfile {
281                biomass: 100.0,
282                structural_complexity: 5.0,
283                hydrological_function: 10.0,
284                genetic_distinctness: 10.0,
285                custodial_depth: 5.0,
286            },
287            irreversibility: IrreversibilityClass::Reversible,
288        };
289
290        let event = LossEvent {
291            event_id: 0x888,
292            stock_id: 0x222,
293            cause_hash: q_hash("event:seasonal_grazing"),
294            timestamp_epoch: 1700000000,
295            extent_loss_pct: 30.0,
296            irreversibility_override: None,
297        };
298
299        let report = eval_accrual_loss(&stock, &event);
300        assert!(!report.is_critical_stock_breached);
301        assert_eq!(
302            report.effective_irreversibility,
303            IrreversibilityClass::Reversible
304        );
305    }
306}