Skip to main content

wellfare_core/anatomy/
accumulate.rs

1//! Non-temporal accumulation: roll a set of [`Factor`]s into per-system burden, find pairwise
2//! interactions, and emit systemic-implication **proposals** (never diagnoses).
3
4use serde::{Deserialize, Serialize};
5
6use crate::record::EpistemicStatus;
7
8use super::factor::{Effect, EvidenceTier, Factor, FactorKind};
9use super::systems::{BODY_SYSTEMS, body_system};
10use super::{push_unique, system_key};
11
12/// Aggregated load on one body system.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
14pub struct SystemBurden {
15    pub system_id: String,
16    pub adverse_milli: u32,
17    pub supportive_milli: u32,
18    /// `adverse - supportive`, floored at 0 (support cannot make a system "better than baseline" here).
19    pub net_milli: u32,
20    /// Factor ids contributing an adverse effect (the "convergence" set).
21    pub adverse_contributors: Vec<String>,
22    /// Factor ids contributing a supportive effect.
23    pub supportive_contributors: Vec<String>,
24}
25
26/// Roll a set of factors into per-system burden. Deterministic; systems appear in `BODY_SYSTEMS`
27/// order (unknown ids after, alphabetically); only systems with any contribution are returned.
28pub fn accumulate(factors: &[Factor]) -> Vec<SystemBurden> {
29    use std::collections::BTreeMap;
30    let mut by_system: BTreeMap<&str, SystemBurden> = BTreeMap::new();
31    for factor in factors {
32        for t in &factor.targets {
33            let entry = by_system
34                .entry(system_key(&t.system_id))
35                .or_insert_with(|| SystemBurden {
36                    system_id: t.system_id.clone(),
37                    ..Default::default()
38                });
39            match t.effect {
40                Effect::Adverse => {
41                    entry.adverse_milli = entry.adverse_milli.saturating_add(t.weight_milli);
42                    push_unique(&mut entry.adverse_contributors, &factor.id);
43                }
44                Effect::Supportive => {
45                    entry.supportive_milli = entry.supportive_milli.saturating_add(t.weight_milli);
46                    push_unique(&mut entry.supportive_contributors, &factor.id);
47                }
48                Effect::Modulating => {}
49            }
50        }
51    }
52    for b in by_system.values_mut() {
53        b.net_milli = b.adverse_milli.saturating_sub(b.supportive_milli);
54    }
55    // Emit in canonical system order, then any unknown system ids alphabetically (BTreeMap order).
56    let mut out: Vec<SystemBurden> = Vec::new();
57    for sys in BODY_SYSTEMS {
58        if let Some(b) = by_system.remove(sys.id) {
59            out.push(b);
60        }
61    }
62    out.extend(by_system.into_values());
63    out
64}
65
66/// A compounding or opposing pair of factors on the same system.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct Interaction {
69    pub system_id: String,
70    pub factor_a: String,
71    pub factor_b: String,
72    pub kind: InteractionKind,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum InteractionKind {
78    /// A medication and a botanical (herb / tea / supplement) both loading the same system.
79    HerbDrug,
80    /// Two adverse factors compounding on one system.
81    Compounding,
82    /// An adverse and a supportive factor on one system (mitigation).
83    Opposing,
84}
85
86/// Find pairwise interactions among factors sharing a system. O(system × factors²) but bounded by a
87/// person's factor count; deterministic ordering.
88pub fn interactions(factors: &[Factor]) -> Vec<Interaction> {
89    let mut out = Vec::new();
90    for i in 0..factors.len() {
91        for j in (i + 1)..factors.len() {
92            let (a, b) = (&factors[i], &factors[j]);
93            for ta in &a.targets {
94                for tb in &b.targets {
95                    if system_key(&ta.system_id) != system_key(&tb.system_id) {
96                        continue;
97                    }
98                    if let Some(kind) = classify_interaction(a, ta.effect, b, tb.effect) {
99                        out.push(Interaction {
100                            system_id: ta.system_id.clone(),
101                            factor_a: a.id.clone(),
102                            factor_b: b.id.clone(),
103                            kind,
104                        });
105                    }
106                }
107            }
108        }
109    }
110    out
111}
112
113fn classify_interaction(a: &Factor, ea: Effect, b: &Factor, eb: Effect) -> Option<InteractionKind> {
114    let is_med = |f: &Factor| f.kind == FactorKind::Medication;
115    let is_botanical = |f: &Factor| {
116        matches!(
117            f.kind,
118            FactorKind::Herb | FactorKind::Tea | FactorKind::Supplement
119        )
120    };
121    // Herb–drug: one medication + one botanical touching the same system (either direction).
122    if (is_med(a) && is_botanical(b)) || (is_botanical(a) && is_med(b)) {
123        return Some(InteractionKind::HerbDrug);
124    }
125    match (ea, eb) {
126        (Effect::Adverse, Effect::Adverse) => Some(InteractionKind::Compounding),
127        (Effect::Adverse, Effect::Supportive) | (Effect::Supportive, Effect::Adverse) => {
128            Some(InteractionKind::Opposing)
129        }
130        _ => None,
131    }
132}
133
134/// A computed, contestable proposal about a system under accumulated load. **Never a diagnosis.**
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
136pub struct SystemicImplication {
137    pub system_id: String,
138    pub system_label: String,
139    pub net_milli: u32,
140    /// Factor ids converging adverse load on this system (≥ the convergence threshold).
141    pub converging_factors: Vec<String>,
142    /// The strongest evidence tier among the contributing adverse mappings (drives how it's shown).
143    pub dominant_evidence: EvidenceTier,
144    /// Interactions on this system worth surfacing.
145    pub interactions: Vec<Interaction>,
146    /// Always `Hypothesis` — a computed association, not a fact/diagnosis.
147    pub epistemic_status: EpistemicStatus,
148}
149
150/// Emit systemic-implication proposals for systems where at least `convergence_threshold` distinct
151/// factors converge adverse load (and net load is non-zero). Deterministic, canonical-system order.
152pub fn systemic_implications(
153    factors: &[Factor],
154    convergence_threshold: usize,
155) -> Vec<SystemicImplication> {
156    let burdens = accumulate(factors);
157    let all_interactions = interactions(factors);
158    let mut out = Vec::new();
159    for b in burdens {
160        if b.adverse_contributors.len() < convergence_threshold.max(1) || b.net_milli == 0 {
161            continue;
162        }
163        let dominant = dominant_evidence(factors, &b.system_id);
164        let sys_interactions: Vec<Interaction> = all_interactions
165            .iter()
166            .filter(|it| system_key(&it.system_id) == system_key(&b.system_id))
167            .cloned()
168            .collect();
169        out.push(SystemicImplication {
170            system_id: b.system_id.clone(),
171            system_label: body_system(&b.system_id)
172                .map(|s| s.label.to_string())
173                .unwrap_or_else(|| b.system_id.clone()),
174            net_milli: b.net_milli,
175            converging_factors: b.adverse_contributors,
176            dominant_evidence: dominant,
177            interactions: sys_interactions,
178            epistemic_status: EpistemicStatus::Hypothesis,
179        });
180    }
181    out
182}
183
184/// The strongest evidence tier among adverse mappings targeting `system_id` (default lowest).
185fn dominant_evidence(factors: &[Factor], system_id: &str) -> EvidenceTier {
186    factors
187        .iter()
188        .flat_map(|f| &f.targets)
189        .filter(|t| {
190            t.effect == Effect::Adverse && system_key(&t.system_id) == system_key(system_id)
191        })
192        .map(|t| t.evidence)
193        .max()
194        .unwrap_or(EvidenceTier::CommunityAnecdotal)
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    fn med(id: &str, system: &str, w: u32) -> Factor {
202        Factor::new(id, FactorKind::Medication, id).targeting(
203            system,
204            Effect::Adverse,
205            EvidenceTier::ClinicalEvidence,
206            w,
207        )
208    }
209    fn herb(id: &str, system: &str, effect: Effect, w: u32) -> Factor {
210        Factor::new(id, FactorKind::Herb, id).targeting(
211            system,
212            effect,
213            EvidenceTier::TraditionalUse,
214            w,
215        )
216    }
217
218    #[test]
219    fn accumulate_nets_adverse_minus_supportive_floored_at_zero() {
220        let factors = vec![
221            Factor::new("cond:nafld", FactorKind::Condition, "NAFLD").targeting(
222                "digestive",
223                Effect::Adverse,
224                EvidenceTier::ClinicalEvidence,
225                600,
226            ),
227            herb("herb:milk-thistle", "digestive", Effect::Supportive, 200),
228        ];
229        let burdens = accumulate(&factors);
230        let dig = burdens.iter().find(|b| b.system_id == "digestive").unwrap();
231        assert_eq!(dig.adverse_milli, 600);
232        assert_eq!(dig.supportive_milli, 200);
233        assert_eq!(dig.net_milli, 400);
234        assert_eq!(dig.adverse_contributors, vec!["cond:nafld".to_string()]);
235
236        // Support exceeding adverse floors net at 0 (never "better than baseline").
237        let more_support = vec![
238            med("med:x", "urinary", 100),
239            herb("herb:y", "urinary", Effect::Supportive, 500),
240        ];
241        let b = accumulate(&more_support);
242        assert_eq!(
243            b.iter()
244                .find(|b| b.system_id == "urinary")
245                .unwrap()
246                .net_milli,
247            0
248        );
249    }
250
251    #[test]
252    fn convergence_only_flags_systems_meeting_the_threshold() {
253        let factors = vec![
254            Factor::new("cond:nafld", FactorKind::Condition, "NAFLD").targeting(
255                "digestive",
256                Effect::Adverse,
257                EvidenceTier::ClinicalEvidence,
258                500,
259            ),
260            med("med:hepatotoxic", "digestive", 300),
261            med("med:nephro", "urinary", 400),
262        ];
263        let impl2 = systemic_implications(&factors, 2);
264        assert_eq!(
265            impl2.len(),
266            1,
267            "only 'digestive' has 2 converging adverse factors"
268        );
269        assert_eq!(impl2[0].system_id, "digestive");
270        assert_eq!(impl2[0].converging_factors.len(), 2);
271        assert_eq!(impl2[0].epistemic_status, EpistemicStatus::Hypothesis);
272        assert_eq!(impl2[0].dominant_evidence, EvidenceTier::ClinicalEvidence);
273
274        assert_eq!(systemic_implications(&factors, 1).len(), 2);
275    }
276
277    #[test]
278    fn herb_drug_interaction_is_detected_on_a_shared_system() {
279        let factors = vec![
280            med("med:warfarin", "circulatory", 400),
281            herb("herb:ginkgo", "circulatory", Effect::Adverse, 300),
282        ];
283        let ix = interactions(&factors);
284        assert_eq!(ix.len(), 1);
285        assert_eq!(ix[0].kind, InteractionKind::HerbDrug);
286        assert_eq!(ix[0].system_id, "circulatory");
287
288        let compounding = vec![
289            Factor::new("a", FactorKind::Condition, "a").targeting(
290                "respiratory",
291                Effect::Adverse,
292                EvidenceTier::ClinicalEvidence,
293                100,
294            ),
295            Factor::new("b", FactorKind::Condition, "b").targeting(
296                "respiratory",
297                Effect::Adverse,
298                EvidenceTier::ClinicalEvidence,
299                100,
300            ),
301        ];
302        assert_eq!(
303            interactions(&compounding)[0].kind,
304            InteractionKind::Compounding
305        );
306    }
307
308    #[test]
309    fn community_hot_take_stays_lowest_tier_and_only_a_hypothesis() {
310        let factors = vec![
311            Factor::new(
312                "post:reddit-123",
313                FactorKind::Herb,
314                "someone said this tea 'detoxes' the liver",
315            )
316            .targeting(
317                "digestive",
318                Effect::Adverse,
319                EvidenceTier::CommunityAnecdotal,
320                50,
321            ),
322        ];
323        let imps = systemic_implications(&factors, 1);
324        assert_eq!(imps.len(), 1);
325        assert_eq!(imps[0].dominant_evidence, EvidenceTier::CommunityAnecdotal);
326        assert_eq!(imps[0].epistemic_status, EpistemicStatus::Hypothesis);
327    }
328}