1use serde::{Deserialize, Serialize};
33
34use crate::record::EpistemicStatus;
35
36use super::accumulate::{
37 Interaction, InteractionKind, SystemBurden, SystemicImplication, accumulate, interactions,
38 systemic_implications,
39};
40use super::factor::{EvidenceTier, Factor};
41use super::physiology::{PhysiologicalState, state_modulator, whole_body_profile};
42use super::system_key;
43use super::systems::body_system;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum Aspect {
49 SystemicLoad,
51 Stress,
53 Resilience,
55 Convergence,
57 InteractionLoad,
59 PhysiologicalDemand,
61}
62
63impl Aspect {
64 pub fn all() -> [Aspect; 6] {
66 [
67 Aspect::SystemicLoad,
68 Aspect::Stress,
69 Aspect::Resilience,
70 Aspect::Convergence,
71 Aspect::InteractionLoad,
72 Aspect::PhysiologicalDemand,
73 ]
74 }
75
76 pub fn label(self) -> &'static str {
78 match self {
79 Aspect::SystemicLoad => "Systemic load",
80 Aspect::Stress => "Stress load",
81 Aspect::Resilience => "Resilience & support",
82 Aspect::Convergence => "Converging factors",
83 Aspect::InteractionLoad => "Combined-effect load",
84 Aspect::PhysiologicalDemand => "Physiological demand",
85 }
86 }
87
88 pub fn plain_label(self) -> &'static str {
90 match self {
91 Aspect::SystemicLoad => "how much is adding up across your body",
92 Aspect::Stress => "load on the stress-response systems",
93 Aspect::Resilience => "what's helping and supporting recovery",
94 Aspect::Convergence => "several things pointing at the same place",
95 Aspect::InteractionLoad => "things that may combine",
96 Aspect::PhysiologicalDemand => "the extra work of your current life stage",
97 }
98 }
99
100 pub fn higher_is_supportive(self) -> bool {
103 matches!(self, Aspect::Resilience)
104 }
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum ScoreBand {
111 Settled,
113 Building,
115 Heightened,
117 Marked,
119}
120
121impl ScoreBand {
122 fn from_score(score_milli: u32) -> ScoreBand {
123 match score_milli {
124 0..=99 => ScoreBand::Settled,
125 100..=349 => ScoreBand::Building,
126 350..=649 => ScoreBand::Heightened,
127 _ => ScoreBand::Marked,
128 }
129 }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub enum ContributionKind {
136 System,
138 Interaction,
140 Convergence,
142 State,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149pub struct Contribution {
150 pub kind: ContributionKind,
151 pub source_id: String,
153 pub label: String,
155 pub weighted_milli: u32,
157 pub evidence: EvidenceTier,
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct AspectScore {
164 pub aspect: Aspect,
165 pub score_milli: u32,
167 pub band: ScoreBand,
168 pub contributions: Vec<Contribution>,
170 pub dominant_evidence: EvidenceTier,
172 pub epistemic_status: EpistemicStatus,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(rename_all = "snake_case")]
183pub enum ForumClass {
184 Internum,
185 Externum,
186}
187
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198pub struct ScoreCard {
199 pub aspects: Vec<AspectScore>,
200}
201
202impl ScoreCard {
203 pub fn aspect(&self, aspect: Aspect) -> Option<&AspectScore> {
205 self.aspects.iter().find(|a| a.aspect == aspect)
206 }
207
208 pub const fn forum_class(&self) -> ForumClass {
210 ForumClass::Internum
211 }
212
213 pub const fn sensitivity_class(&self) -> &'static str {
219 "Sanctuary"
220 }
221}
222
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct SystemAspectWeight {
231 pub system_id: String,
232 pub aspect: Aspect,
233 pub weight_pct: u32,
234}
235
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
239pub struct WeightModel {
240 pub system_weights: Vec<SystemAspectWeight>,
241}
242
243impl WeightModel {
244 pub fn weight_for(&self, system_id: &str, aspect: Aspect) -> u32 {
246 self.system_weights
247 .iter()
248 .find(|w| w.aspect == aspect && system_key(&w.system_id) == system_key(system_id))
249 .map(|w| w.weight_pct)
250 .unwrap_or(0)
251 }
252}
253
254pub fn seed_weight_model() -> WeightModel {
258 let rows: &[(&str, u32, u32)] = &[
260 ("nervous", 100, 60),
261 ("endocrine", 90, 50),
262 ("ecs", 80, 70), ("circulatory", 50, 40),
264 ("digestive", 40, 50),
265 ("immune_lymphatic", 40, 60),
266 ("glymphatic", 60, 80), ("muscular", 30, 50),
268 ("respiratory", 40, 30),
269 ];
270 let mut system_weights = Vec::new();
271 for (id, stress, resilience) in rows {
272 if *stress > 0 {
273 system_weights.push(SystemAspectWeight {
274 system_id: id.to_string(),
275 aspect: Aspect::Stress,
276 weight_pct: *stress,
277 });
278 }
279 if *resilience > 0 {
280 system_weights.push(SystemAspectWeight {
281 system_id: id.to_string(),
282 aspect: Aspect::Resilience,
283 weight_pct: *resilience,
284 });
285 }
286 }
287 WeightModel { system_weights }
288}
289
290fn clamp1000(v: u64) -> u32 {
295 v.min(1000) as u32
296}
297
298fn system_evidence(factors: &[Factor], system_id: &str) -> EvidenceTier {
300 factors
301 .iter()
302 .flat_map(|f| &f.targets)
303 .filter(|t| system_key(&t.system_id) == system_key(system_id))
304 .map(|t| t.evidence)
305 .max()
306 .unwrap_or(EvidenceTier::CommunityAnecdotal)
307}
308
309fn dominant(contributions: &[Contribution]) -> EvidenceTier {
310 contributions
311 .iter()
312 .map(|c| c.evidence)
313 .max()
314 .unwrap_or(EvidenceTier::CommunityAnecdotal)
315}
316
317fn finish(aspect: Aspect, raw: u64, mut contributions: Vec<Contribution>) -> AspectScore {
318 contributions.sort_by(|a, b| {
320 b.weighted_milli
321 .cmp(&a.weighted_milli)
322 .then(a.label.cmp(&b.label))
323 });
324 let score_milli = clamp1000(raw);
325 AspectScore {
326 aspect,
327 score_milli,
328 band: ScoreBand::from_score(score_milli),
329 dominant_evidence: dominant(&contributions),
330 contributions,
331 epistemic_status: EpistemicStatus::Hypothesis,
332 }
333}
334
335fn interaction_severity(kind: InteractionKind) -> u32 {
337 match kind {
338 InteractionKind::HerbDrug => 300, InteractionKind::Compounding => 200, InteractionKind::Opposing => 60, }
342}
343
344pub fn score_card(
351 factors: &[Factor],
352 convergence_threshold: usize,
353 state: PhysiologicalState,
354 weights: &WeightModel,
355) -> ScoreCard {
356 let raw_burdens = accumulate(factors);
357 let burdens: Vec<SystemBurden> = state_modulator(state).apply_to_burdens(&raw_burdens);
358 let implications: Vec<SystemicImplication> =
359 systemic_implications(factors, convergence_threshold);
360 let ix: Vec<Interaction> = interactions(factors);
361
362 let mut aspects = Vec::new();
363 aspects.push(score_systemic_load(&burdens, factors));
364 aspects.push(score_weighted(Aspect::Stress, &burdens, factors, weights));
365 aspects.push(score_resilience(&burdens, factors, weights));
366 aspects.push(score_convergence(&implications));
367 aspects.push(score_interactions(&ix));
368 aspects.push(score_physiological_demand(state));
369 ScoreCard { aspects }
370}
371
372fn score_systemic_load(burdens: &[SystemBurden], factors: &[Factor]) -> AspectScore {
374 let mut raw = 0u64;
375 let mut contributions = Vec::new();
376 for b in burdens {
377 if b.net_milli == 0 {
378 continue;
379 }
380 raw += b.net_milli as u64;
381 contributions.push(Contribution {
382 kind: ContributionKind::System,
383 source_id: b.system_id.clone(),
384 label: system_label(&b.system_id),
385 weighted_milli: b.net_milli,
386 evidence: system_evidence(factors, &b.system_id),
387 });
388 }
389 finish(Aspect::SystemicLoad, raw, contributions)
390}
391
392fn score_weighted(
394 aspect: Aspect,
395 burdens: &[SystemBurden],
396 factors: &[Factor],
397 weights: &WeightModel,
398) -> AspectScore {
399 let mut raw = 0u64;
400 let mut contributions = Vec::new();
401 for b in burdens {
402 let w = weights.weight_for(&b.system_id, aspect);
403 if w == 0 || b.net_milli == 0 {
404 continue;
405 }
406 let weighted = (b.net_milli as u64 * w as u64) / 100;
407 if weighted == 0 {
408 continue;
409 }
410 raw += weighted;
411 contributions.push(Contribution {
412 kind: ContributionKind::System,
413 source_id: b.system_id.clone(),
414 label: system_label(&b.system_id),
415 weighted_milli: weighted as u32,
416 evidence: system_evidence(factors, &b.system_id),
417 });
418 }
419 finish(aspect, raw, contributions)
420}
421
422fn score_resilience(
424 burdens: &[SystemBurden],
425 factors: &[Factor],
426 weights: &WeightModel,
427) -> AspectScore {
428 let mut raw = 0u64;
429 let mut contributions = Vec::new();
430 for b in burdens {
431 let w = weights.weight_for(&b.system_id, Aspect::Resilience);
432 if w == 0 || b.supportive_milli == 0 {
433 continue;
434 }
435 let weighted = (b.supportive_milli as u64 * w as u64) / 100;
436 if weighted == 0 {
437 continue;
438 }
439 raw += weighted;
440 contributions.push(Contribution {
441 kind: ContributionKind::System,
442 source_id: b.system_id.clone(),
443 label: system_label(&b.system_id),
444 weighted_milli: weighted as u32,
445 evidence: system_evidence(factors, &b.system_id),
446 });
447 }
448 finish(Aspect::Resilience, raw, contributions)
449}
450
451fn score_convergence(implications: &[SystemicImplication]) -> AspectScore {
454 let mut raw = 0u64;
455 let mut contributions = Vec::new();
456 for im in implications {
457 let n = im.converging_factors.len() as u64;
458 let weighted = (im.net_milli as u64 * n) / 1;
460 raw += weighted;
461 contributions.push(Contribution {
462 kind: ContributionKind::Convergence,
463 source_id: im.system_id.clone(),
464 label: format!(
465 "{} ({} converging)",
466 im.system_label,
467 im.converging_factors.len()
468 ),
469 weighted_milli: clamp1000(weighted),
470 evidence: im.dominant_evidence,
471 });
472 }
473 finish(Aspect::Convergence, raw, contributions)
474}
475
476fn score_interactions(ix: &[Interaction]) -> AspectScore {
478 let mut raw = 0u64;
479 let mut contributions = Vec::new();
480 for it in ix {
481 let sev = interaction_severity(it.kind);
482 raw += sev as u64;
483 contributions.push(Contribution {
484 kind: ContributionKind::Interaction,
485 source_id: format!("{}+{}", it.factor_a, it.factor_b),
486 label: format!(
487 "{} & {} on {}",
488 it.factor_a,
489 it.factor_b,
490 system_label(&it.system_id)
491 ),
492 weighted_milli: sev,
493 evidence: EvidenceTier::Mechanistic,
496 });
497 }
498 finish(Aspect::InteractionLoad, raw, contributions)
499}
500
501fn score_physiological_demand(state: PhysiologicalState) -> AspectScore {
503 let mut raw = 0u64;
504 let mut contributions = Vec::new();
505 for e in whole_body_profile(state) {
506 let demand = (e.scale_pct.saturating_sub(100)) as u64;
508 if demand == 0 {
509 continue;
510 }
511 raw += demand;
512 contributions.push(Contribution {
513 kind: ContributionKind::State,
514 source_id: e.system_id.clone(),
515 label: e.system_label.clone(),
516 weighted_milli: demand as u32,
517 evidence: EvidenceTier::Mechanistic,
519 });
520 }
521 finish(Aspect::PhysiologicalDemand, raw, contributions)
522}
523
524fn system_label(system_id: &str) -> String {
525 body_system(system_id)
526 .map(|s| s.label.to_string())
527 .unwrap_or_else(|| system_id.to_string())
528}
529
530#[cfg(test)]
531mod tests {
532 use super::*;
533 use crate::anatomy::factor::{Effect, FactorKind, FactorTarget};
534 use crate::anatomy::physiology::{ReproductiveState, Trimester};
535
536 fn factor(id: &str, kind: FactorKind, targets: &[(&str, Effect, EvidenceTier, u32)]) -> Factor {
537 let mut f = Factor::new(id, kind, id);
538 f.targets = targets
539 .iter()
540 .map(|(s, e, ev, w)| FactorTarget {
541 system_id: s.to_string(),
542 effect: *e,
543 evidence: *ev,
544 weight_milli: *w,
545 })
546 .collect();
547 f
548 }
549
550 fn baseline() -> PhysiologicalState {
551 PhysiologicalState::Baseline
552 }
553
554 #[test]
555 fn card_has_one_score_per_aspect_in_order() {
556 let card = score_card(&[], 1, baseline(), &seed_weight_model());
557 assert_eq!(card.aspects.len(), Aspect::all().len());
558 for (got, want) in card.aspects.iter().zip(Aspect::all()) {
559 assert_eq!(got.aspect, want);
560 }
561 for a in &card.aspects {
563 assert_eq!(a.band, ScoreBand::Settled);
564 assert!(a.contributions.is_empty());
565 assert_eq!(a.epistemic_status, EpistemicStatus::Hypothesis);
566 }
567 }
568
569 #[test]
570 fn every_score_traces_to_its_underlying_considerations() {
571 let factors = vec![
573 factor(
574 "cond:chronic-stress",
575 FactorKind::Condition,
576 &[(
577 "nervous",
578 Effect::Adverse,
579 EvidenceTier::ClinicalEvidence,
580 400,
581 )],
582 ),
583 factor(
584 "life:poor-sleep",
585 FactorKind::Lifestyle,
586 &[("nervous", Effect::Adverse, EvidenceTier::Mechanistic, 300)],
587 ),
588 ];
589 let card = score_card(&factors, 2, baseline(), &seed_weight_model());
590
591 let load = card.aspect(Aspect::SystemicLoad).unwrap();
593 assert!(load.score_milli > 0);
594 assert!(load.contributions.iter().any(|c| c.source_id == "nervous"));
595
596 let stress = card.aspect(Aspect::Stress).unwrap();
598 assert!(stress.score_milli > 0);
599 let nervous = stress
600 .contributions
601 .iter()
602 .find(|c| c.source_id == "nervous")
603 .unwrap();
604 assert_eq!(nervous.kind, ContributionKind::System);
605 assert!(!nervous.label.is_empty(), "human-readable linkage");
606 assert_eq!(stress.dominant_evidence, EvidenceTier::ClinicalEvidence);
608
609 let conv = card.aspect(Aspect::Convergence).unwrap();
611 assert!(conv.score_milli > 0);
612 assert!(conv.contributions.iter().any(|c| c.source_id == "nervous"));
613 }
614
615 #[test]
616 fn resilience_reads_the_supportive_side_and_higher_is_good() {
617 let factors = vec![factor(
618 "act:meditation-and-sleep",
619 FactorKind::Lifestyle,
620 &[(
621 "nervous",
622 Effect::Supportive,
623 EvidenceTier::Mechanistic,
624 500,
625 )],
626 )];
627 let card = score_card(&factors, 1, baseline(), &seed_weight_model());
628 let res = card.aspect(Aspect::Resilience).unwrap();
629 assert!(res.score_milli > 0, "support shows up as resilience");
630 assert!(res.contributions.iter().any(|c| c.source_id == "nervous"));
631 assert!(Aspect::Resilience.higher_is_supportive());
632 assert_eq!(
634 card.aspect(Aspect::SystemicLoad).unwrap().band,
635 ScoreBand::Settled
636 );
637 }
638
639 #[test]
640 fn interaction_load_scores_a_herb_drug_pair() {
641 let factors = vec![
642 factor(
643 "med:warfarin",
644 FactorKind::Medication,
645 &[(
646 "circulatory",
647 Effect::Adverse,
648 EvidenceTier::ClinicalEvidence,
649 400,
650 )],
651 ),
652 factor(
653 "herb:ginkgo",
654 FactorKind::Herb,
655 &[(
656 "circulatory",
657 Effect::Adverse,
658 EvidenceTier::TraditionalUse,
659 300,
660 )],
661 ),
662 ];
663 let card = score_card(&factors, 1, baseline(), &seed_weight_model());
664 let ix = card.aspect(Aspect::InteractionLoad).unwrap();
665 assert_eq!(
666 ix.score_milli,
667 interaction_severity(InteractionKind::HerbDrug)
668 );
669 assert_eq!(ix.contributions.len(), 1);
670 assert_eq!(ix.contributions[0].kind, ContributionKind::Interaction);
671 }
672
673 #[test]
674 fn physiological_demand_reflects_the_life_stage_and_state_modulates_load() {
675 let med = factor(
677 "med:nephrotoxic",
678 FactorKind::Medication,
679 &[(
680 "urinary",
681 Effect::Adverse,
682 EvidenceTier::ClinicalEvidence,
683 400,
684 )],
685 );
686 let t3 = PhysiologicalState::Reproductive(ReproductiveState::Pregnant(Trimester::Third));
687 let base_card = score_card(
688 std::slice::from_ref(&med),
689 1,
690 baseline(),
691 &seed_weight_model(),
692 );
693 let preg_card = score_card(std::slice::from_ref(&med), 1, t3, &seed_weight_model());
694
695 assert_eq!(
697 base_card.aspect(Aspect::PhysiologicalDemand).unwrap().band,
698 ScoreBand::Settled
699 );
700 let demand = preg_card.aspect(Aspect::PhysiologicalDemand).unwrap();
701 assert!(demand.score_milli > 0);
702 assert!(
703 demand
704 .contributions
705 .iter()
706 .any(|c| c.source_id == "urinary")
707 );
708
709 let base_load = base_card.aspect(Aspect::SystemicLoad).unwrap().score_milli;
711 let preg_load = preg_card.aspect(Aspect::SystemicLoad).unwrap().score_milli;
712 assert!(
713 preg_load > base_load,
714 "state modulates the load: {preg_load} > {base_load}"
715 );
716 }
717
718 #[test]
719 fn bands_are_coarse_and_monotone() {
720 assert_eq!(ScoreBand::from_score(0), ScoreBand::Settled);
721 assert_eq!(ScoreBand::from_score(99), ScoreBand::Settled);
722 assert_eq!(ScoreBand::from_score(100), ScoreBand::Building);
723 assert_eq!(ScoreBand::from_score(349), ScoreBand::Building);
724 assert_eq!(ScoreBand::from_score(350), ScoreBand::Heightened);
725 assert_eq!(ScoreBand::from_score(649), ScoreBand::Heightened);
726 assert_eq!(ScoreBand::from_score(650), ScoreBand::Marked);
727 assert_eq!(ScoreBand::from_score(5000), ScoreBand::Marked);
728 }
729
730 #[test]
731 fn a_score_card_is_forum_internum_selfhood_content_at_sanctuary_class() {
732 let card = score_card(&[], 1, baseline(), &seed_weight_model());
735 assert_eq!(card.forum_class(), ForumClass::Internum);
736 assert_eq!(card.sensitivity_class(), "Sanctuary");
737 }
738
739 #[test]
740 fn deterministic_and_serde_round_trips() {
741 let factors = vec![factor(
742 "x",
743 FactorKind::Condition,
744 &[("endocrine", Effect::Adverse, EvidenceTier::Mechanistic, 300)],
745 )];
746 let a = score_card(&factors, 1, baseline(), &seed_weight_model());
747 let b = score_card(&factors, 1, baseline(), &seed_weight_model());
748 assert_eq!(a, b, "deterministic");
749 let json = serde_json::to_string(&a).unwrap();
750 let back: ScoreCard = serde_json::from_str(&json).unwrap();
751 assert_eq!(a, back);
752 }
753}