1use serde::{Deserialize, Serialize};
28
29use super::constitution::DominantSide;
30use super::densitometry::{MuscleQualityProfile, PhysealFusionStatus, SkeletalDensityProfile};
31use super::factor::Effect;
32use super::model::Karyotype;
33use super::system_key;
34use super::systems::BODY_SYSTEMS;
35use super::temporal::EnvironmentModulator;
36use crate::record::EpistemicStatus;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum CyclePhase {
46 Menstrual,
48 Follicular,
50 Ovulatory,
52 Luteal,
54}
55
56impl CyclePhase {
57 pub fn next(self) -> CyclePhase {
59 match self {
60 CyclePhase::Menstrual => CyclePhase::Follicular,
61 CyclePhase::Follicular => CyclePhase::Ovulatory,
62 CyclePhase::Ovulatory => CyclePhase::Luteal,
63 CyclePhase::Luteal => CyclePhase::Menstrual,
64 }
65 }
66
67 pub fn plain_label(self) -> &'static str {
69 match self {
70 CyclePhase::Menstrual => "period (menstrual phase)",
71 CyclePhase::Follicular => "follicular phase",
72 CyclePhase::Ovulatory => "around ovulation",
73 CyclePhase::Luteal => "luteal (premenstrual) phase",
74 }
75 }
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
80#[serde(rename_all = "snake_case")]
81pub enum Trimester {
82 First,
83 Second,
84 Third,
85}
86
87impl Trimester {
88 pub fn next(self) -> Option<Trimester> {
91 match self {
92 Trimester::First => Some(Trimester::Second),
93 Trimester::Second => Some(Trimester::Third),
94 Trimester::Third => None,
95 }
96 }
97
98 pub fn week_span(self) -> (u32, u32) {
101 match self {
102 Trimester::First => (1, 13),
103 Trimester::Second => (14, 27),
104 Trimester::Third => (28, 40),
105 }
106 }
107
108 pub fn plain_label(self) -> &'static str {
110 match self {
111 Trimester::First => "first trimester",
112 Trimester::Second => "second trimester",
113 Trimester::Third => "third trimester",
114 }
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "snake_case")]
123pub enum ReproductiveState {
124 PreMenarche,
126 Cycling(CyclePhase),
128 Pregnant(Trimester),
130 Postpartum,
133 Lactating,
135 Perimenopause,
137 PostMenopause,
139}
140
141impl ReproductiveState {
142 pub fn next_states(self) -> Vec<ReproductiveState> {
150 use ReproductiveState::*;
151 match self {
152 PreMenarche => vec![Cycling(CyclePhase::Menstrual)],
153 Cycling(phase) => vec![
154 Cycling(phase.next()),
155 Pregnant(Trimester::First),
156 Perimenopause,
157 ],
158 Pregnant(tri) => match tri.next() {
159 Some(next_tri) => vec![Pregnant(next_tri), Postpartum],
160 None => vec![Postpartum],
161 },
162 Postpartum => vec![Lactating, Cycling(CyclePhase::Menstrual)],
163 Lactating => vec![Cycling(CyclePhase::Menstrual), Postpartum],
164 Perimenopause => vec![PostMenopause],
165 PostMenopause => vec![],
166 }
167 }
168
169 pub fn can_transition_to(self, next: ReproductiveState) -> bool {
171 self.next_states().contains(&next)
172 }
173
174 pub fn plain_label(self) -> String {
177 use ReproductiveState::*;
178 match self {
179 PreMenarche => "before periods begin".to_string(),
180 Cycling(phase) => phase.plain_label().to_string(),
181 Pregnant(tri) => format!("pregnant — {}", tri.plain_label()),
182 Postpartum => "the fourth trimester (early recovery after birth)".to_string(),
183 Lactating => "breastfeeding".to_string(),
184 Perimenopause => "the change (perimenopause)".to_string(),
185 PostMenopause => "after menopause".to_string(),
186 }
187 }
188}
189
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub enum PhysiologicalState {
197 Baseline,
201 Reproductive(ReproductiveState),
203}
204
205impl PhysiologicalState {
206 pub fn plain_label(self) -> String {
208 match self {
209 PhysiologicalState::Baseline => "no reproductive-state modulation".to_string(),
210 PhysiologicalState::Reproductive(r) => r.plain_label(),
211 }
212 }
213}
214
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228pub struct StateModulator {
229 pub state: PhysiologicalState,
230 pub system_scale_pct: Vec<(String, u32)>,
231}
232
233impl StateModulator {
234 pub fn scale_for(&self, system_id: &str) -> u32 {
236 self.system_scale_pct
237 .iter()
238 .find(|(id, _)| system_key(id) == system_key(system_id))
239 .map(|(_, s)| *s)
240 .unwrap_or(100)
241 }
242
243 pub fn scale_adverse(&self, system_id: &str, adverse_milli: u32) -> u32 {
246 ((adverse_milli as u64 * self.scale_for(system_id) as u64) / 100).min(1000) as u32
247 }
248
249 pub fn apply_to_burdens(
254 &self,
255 burdens: &[super::accumulate::SystemBurden],
256 ) -> Vec<super::accumulate::SystemBurden> {
257 burdens
258 .iter()
259 .map(|b| {
260 let adverse = self.scale_adverse(&b.system_id, b.adverse_milli);
261 super::accumulate::SystemBurden {
262 system_id: b.system_id.clone(),
263 adverse_milli: adverse,
264 supportive_milli: b.supportive_milli,
265 net_milli: adverse.saturating_sub(b.supportive_milli),
266 adverse_contributors: b.adverse_contributors.clone(),
267 supportive_contributors: b.supportive_contributors.clone(),
268 }
269 })
270 .collect()
271 }
272
273 pub fn as_environment_modulators(
278 &self,
279 from_minute: i64,
280 to_minute: i64,
281 ) -> Vec<EnvironmentModulator> {
282 self.system_scale_pct
283 .iter()
284 .filter(|(_, scale)| *scale != 100)
285 .map(|(system, scale)| EnvironmentModulator {
286 label: format!("state:{}", self.state.plain_label()),
287 from_minute,
288 to_minute,
289 target_system: Some(system.clone()),
290 target_effect: Some(Effect::Adverse),
291 scale_pct: *scale,
292 })
293 .collect()
294 }
295}
296
297fn seed_scale_table(state: PhysiologicalState) -> &'static [(&'static str, u32)] {
302 use PhysiologicalState::*;
303 use ReproductiveState::*;
304 match state {
305 Baseline | Reproductive(PreMenarche) => &[],
306 Reproductive(Cycling(CyclePhase::Menstrual)) => &[("circulatory", 110), ("endocrine", 110)],
308 Reproductive(Cycling(CyclePhase::Follicular)) => &[("endocrine", 105)],
309 Reproductive(Cycling(CyclePhase::Ovulatory)) => &[("endocrine", 110)],
310 Reproductive(Cycling(CyclePhase::Luteal)) => {
311 &[("endocrine", 115), ("nervous", 110), ("circulatory", 105)]
312 }
313 Reproductive(Pregnant(Trimester::First)) => &[
316 ("circulatory", 115),
317 ("urinary", 115),
318 ("endocrine", 130),
319 ("digestive", 110),
320 ],
321 Reproductive(Pregnant(Trimester::Second)) => &[
322 ("circulatory", 130),
323 ("urinary", 125),
324 ("respiratory", 115),
325 ("endocrine", 135),
326 ("skeletal", 110),
327 ("muscular", 110),
328 ],
329 Reproductive(Pregnant(Trimester::Third)) => &[
330 ("circulatory", 140),
331 ("urinary", 130),
332 ("respiratory", 125),
333 ("endocrine", 135),
334 ("skeletal", 130),
335 ("muscular", 125),
336 ("digestive", 115),
337 ],
338 Reproductive(Postpartum) => &[
340 ("endocrine", 130),
341 ("nervous", 115),
342 ("circulatory", 110),
343 ("skeletal", 115),
344 ("muscular", 115),
345 ],
346 Reproductive(Lactating) => &[("endocrine", 125), ("digestive", 115), ("skeletal", 110)],
348 Reproductive(Perimenopause) => &[
350 ("endocrine", 135),
351 ("nervous", 115),
352 ("skeletal", 115),
353 ("circulatory", 110),
354 ],
355 Reproductive(PostMenopause) => {
357 &[("skeletal", 120), ("circulatory", 115), ("endocrine", 110)]
358 }
359 }
360}
361
362pub fn state_modulator(state: PhysiologicalState) -> StateModulator {
364 StateModulator {
365 state,
366 system_scale_pct: seed_scale_table(state)
367 .iter()
368 .map(|(id, s)| (id.to_string(), *s))
369 .collect(),
370 }
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
380#[serde(rename_all = "snake_case")]
381pub enum EngagementLevel {
382 Baseline,
384 Elevated,
386 High,
388}
389
390impl EngagementLevel {
391 fn from_scale(scale_pct: u32) -> EngagementLevel {
392 if scale_pct >= 125 {
393 EngagementLevel::High
394 } else if scale_pct >= 110 {
395 EngagementLevel::Elevated
396 } else {
397 EngagementLevel::Baseline
398 }
399 }
400}
401
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
404pub struct SystemEngagement {
405 pub system_id: String,
406 pub system_label: String,
408 pub plain_label: String,
410 pub scale_pct: u32,
412 pub level: EngagementLevel,
413}
414
415pub fn whole_body_profile(state: PhysiologicalState) -> Vec<SystemEngagement> {
420 let modulator = state_modulator(state);
421 let mut out = Vec::new();
422 for sys in BODY_SYSTEMS {
423 let scale = modulator.scale_for(sys.id);
424 if scale <= 100 {
425 continue;
426 }
427 out.push(SystemEngagement {
428 system_id: sys.id.to_string(),
429 system_label: sys.label.to_string(),
430 plain_label: sys.plain_label.to_string(),
431 scale_pct: scale,
432 level: EngagementLevel::from_scale(scale),
433 });
434 }
435 out
436}
437
438#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
445#[serde(rename_all = "snake_case")]
446pub enum ReproductiveEndocrinePhase {
447 PreMenarche,
448 Cycling(CyclePhase),
449 Pregnant(Trimester),
450 Postpartum,
451 Lactating,
452 Perimenopause,
453 PostMenopause,
454 AdultBaseline,
456 Andropause,
458 ExogenousHormoneTherapy,
460}
461
462impl From<ReproductiveState> for ReproductiveEndocrinePhase {
463 fn from(s: ReproductiveState) -> Self {
464 match s {
465 ReproductiveState::PreMenarche => Self::PreMenarche,
466 ReproductiveState::Cycling(p) => Self::Cycling(p),
467 ReproductiveState::Pregnant(t) => Self::Pregnant(t),
468 ReproductiveState::Postpartum => Self::Postpartum,
469 ReproductiveState::Lactating => Self::Lactating,
470 ReproductiveState::Perimenopause => Self::Perimenopause,
471 ReproductiveState::PostMenopause => Self::PostMenopause,
472 }
473 }
474}
475
476impl From<PhysiologicalState> for ReproductiveEndocrinePhase {
477 fn from(s: PhysiologicalState) -> Self {
478 match s {
479 PhysiologicalState::Baseline => Self::AdultBaseline,
480 PhysiologicalState::Reproductive(r) => Self::from(r),
481 }
482 }
483}
484
485#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
487pub struct EndocrineOsteoState {
488 pub phase: ReproductiveEndocrinePhase,
489 pub estrogen_status_ratio: f64,
491 pub androgen_status_ratio: f64,
493 pub relaxin_ng_ml: f64,
495 #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub vitamin_d_25oh_ng_ml: Option<f64>,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
500 pub pth_pg_ml: Option<f64>,
501 #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub egfr_ml_min_1_73m2: Option<f64>,
504 pub glucocorticoid_exposure: bool,
506}
507
508impl Default for EndocrineOsteoState {
509 fn default() -> Self {
510 Self::for_phase(ReproductiveEndocrinePhase::AdultBaseline)
511 }
512}
513
514impl EndocrineOsteoState {
515 pub fn for_phase(phase: ReproductiveEndocrinePhase) -> Self {
517 let (estrogen, androgen, relaxin) = match phase {
518 ReproductiveEndocrinePhase::PreMenarche => (0.25, 0.25, 0.0),
519 ReproductiveEndocrinePhase::Cycling(CyclePhase::Menstrual) => (0.65, 1.0, 0.0),
520 ReproductiveEndocrinePhase::Cycling(CyclePhase::Follicular) => (0.95, 1.0, 0.0),
521 ReproductiveEndocrinePhase::Cycling(CyclePhase::Ovulatory) => (1.25, 1.0, 0.15),
522 ReproductiveEndocrinePhase::Cycling(CyclePhase::Luteal) => (1.05, 1.0, 0.25),
523 ReproductiveEndocrinePhase::Pregnant(Trimester::First) => (1.60, 1.0, 1.20),
524 ReproductiveEndocrinePhase::Pregnant(Trimester::Second) => (2.00, 1.0, 1.50),
525 ReproductiveEndocrinePhase::Pregnant(Trimester::Third) => (2.40, 1.0, 2.20),
526 ReproductiveEndocrinePhase::Postpartum => (0.45, 0.90, 0.35),
527 ReproductiveEndocrinePhase::Lactating => (0.35, 0.90, 0.0),
528 ReproductiveEndocrinePhase::Perimenopause => (0.55, 0.90, 0.0),
529 ReproductiveEndocrinePhase::PostMenopause => (0.15, 0.80, 0.0),
530 ReproductiveEndocrinePhase::AdultBaseline => (1.00, 1.00, 0.0),
531 ReproductiveEndocrinePhase::Andropause => (0.80, 0.55, 0.0),
532 ReproductiveEndocrinePhase::ExogenousHormoneTherapy => (1.00, 1.00, 0.0),
533 };
534 Self {
535 phase,
536 estrogen_status_ratio: estrogen,
537 androgen_status_ratio: androgen,
538 relaxin_ng_ml: relaxin,
539 vitamin_d_25oh_ng_ml: None,
540 pth_pg_ml: None,
541 egfr_ml_min_1_73m2: None,
542 glucocorticoid_exposure: false,
543 }
544 }
545
546 pub fn validate(&self) -> Result<(), String> {
548 if !self.estrogen_status_ratio.is_finite() || self.estrogen_status_ratio < 0.0 {
549 return Err("estrogen_status_ratio must be finite and non-negative".into());
550 }
551 if !self.androgen_status_ratio.is_finite() || self.androgen_status_ratio < 0.0 {
552 return Err("androgen_status_ratio must be finite and non-negative".into());
553 }
554 if !self.relaxin_ng_ml.is_finite() || self.relaxin_ng_ml < 0.0 {
555 return Err("relaxin_ng_ml must be finite and non-negative".into());
556 }
557 if let Some(vd) = self.vitamin_d_25oh_ng_ml {
558 if !vd.is_finite() || vd < 0.0 {
559 return Err("vitamin_d_25oh_ng_ml must be finite and non-negative".into());
560 }
561 }
562 if let Some(pth) = self.pth_pg_ml {
563 if !pth.is_finite() || pth < 0.0 {
564 return Err("pth_pg_ml must be finite and non-negative".into());
565 }
566 }
567 if let Some(egfr) = self.egfr_ml_min_1_73m2 {
568 if !egfr.is_finite() || egfr < 0.0 {
569 return Err("egfr_ml_min_1_73m2 must be finite and non-negative".into());
570 }
571 }
572 Ok(())
573 }
574
575 pub fn ligament_stiffness_modifier(&self) -> Result<f64, String> {
578 self.validate()?;
579 Ok(1.0 - 0.35 * (self.relaxin_ng_ml / (self.relaxin_ng_ml + 0.5)))
580 }
581
582 pub fn ligament_laxity_scale(&self) -> Result<f64, String> {
584 let stiffness = self.ligament_stiffness_modifier()?;
585 Ok((1.0 / stiffness).clamp(1.0, 1.6))
586 }
587
588 pub fn trabecular_turnover_multiplier(&self) -> f64 {
591 let phase_factor = match self.phase {
592 ReproductiveEndocrinePhase::Lactating => 0.94,
593 ReproductiveEndocrinePhase::Pregnant(Trimester::Third) => 0.97,
594 ReproductiveEndocrinePhase::Postpartum => 0.96,
595 ReproductiveEndocrinePhase::Perimenopause => 0.92,
596 ReproductiveEndocrinePhase::PostMenopause => 0.80,
597 ReproductiveEndocrinePhase::Andropause => 0.90,
598 _ => 1.0,
599 };
600 let hormone_support = (0.75 + 0.25 * (0.6 * self.estrogen_status_ratio + 0.4 * self.androgen_status_ratio))
601 .clamp(0.70, 1.10);
602 let gc_penalty = if self.glucocorticoid_exposure { 0.85 } else { 1.0 };
603 (phase_factor * hormone_support * gc_penalty).clamp(0.45, 1.15)
604 }
605
606 pub fn cortical_porosity_delta(&self) -> f64 {
608 let mut delta = 0.0;
609 if matches!(
610 self.phase,
611 ReproductiveEndocrinePhase::Perimenopause | ReproductiveEndocrinePhase::PostMenopause
612 ) {
613 delta += 0.03;
614 }
615 if let Some(pth) = self.pth_pg_ml {
616 if pth > 65.0 {
617 delta += ((pth - 65.0) / 500.0).min(0.08);
618 }
619 }
620 if let Some(egfr) = self.egfr_ml_min_1_73m2 {
621 if egfr < 45.0 {
622 delta += ((45.0 - egfr) / 300.0).min(0.08);
623 }
624 }
625 if self.glucocorticoid_exposure {
626 delta += 0.02;
627 }
628 delta
629 }
630
631 pub fn mineralization_mu_modifier(&self) -> f64 {
634 let mut mu = 1.0;
635 if let Some(vd) = self.vitamin_d_25oh_ng_ml {
636 if vd < 20.0 {
637 mu *= (0.65 + 0.35 * (vd / 20.0)).clamp(0.65, 1.0);
638 }
639 }
640 if let Some(egfr) = self.egfr_ml_min_1_73m2 {
641 if egfr < 30.0 {
642 mu *= (0.75 + 0.25 * (egfr / 30.0)).clamp(0.75, 1.0);
643 }
644 }
645 mu
646 }
647}
648
649#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
651#[serde(rename_all = "snake_case")]
652pub enum OntogeneticStage {
653 FetalNeonatal,
654 Pediatric,
655 Adolescent,
656 YoungAdultPeak,
657 MiddleAdult,
658 Senescent,
659}
660
661#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
663pub struct AgeOntogenyProfile {
664 pub chronological_age_months: u16,
665 #[serde(default, skip_serializing_if = "Option::is_none")]
666 pub skeletal_bone_age_months: Option<u16>,
667 #[serde(default, skip_serializing_if = "Option::is_none")]
668 pub tissue_biological_age_months: Option<u16>,
669 pub physeal_status: PhysealFusionStatus,
670 pub life_stage: OntogeneticStage,
671}
672
673impl AgeOntogenyProfile {
674 pub fn from_age_months(chronological_age_months: u16) -> Result<Self, String> {
676 if chronological_age_months > 1560 {
677 return Err(format!(
678 "chronological_age_months {chronological_age_months} exceeds 1560"
679 ));
680 }
681 let life_stage = match chronological_age_months {
682 0..=11 => OntogeneticStage::FetalNeonatal,
683 12..=143 => OntogeneticStage::Pediatric,
684 144..=239 => OntogeneticStage::Adolescent,
685 240..=420 => OntogeneticStage::YoungAdultPeak,
686 421..=779 => OntogeneticStage::MiddleAdult,
687 _ => OntogeneticStage::Senescent,
688 };
689 let physeal_status = match chronological_age_months {
690 0..=167 => PhysealFusionStatus::OpenCartilaginousPhysis,
691 168..=240 => PhysealFusionStatus::PartiallyFused,
692 _ => PhysealFusionStatus::ClosedMatureDiaphysis,
693 };
694 Ok(Self {
695 chronological_age_months,
696 skeletal_bone_age_months: None,
697 tissue_biological_age_months: None,
698 physeal_status,
699 life_stage,
700 })
701 }
702
703 pub fn with_skeletal_bone_age_months(mut self, bone_age_months: u16) -> Result<Self, String> {
705 if bone_age_months > 1560 {
706 return Err(format!(
707 "skeletal_bone_age_months {bone_age_months} exceeds 1560"
708 ));
709 }
710 self.skeletal_bone_age_months = Some(bone_age_months);
711 self.physeal_status = match bone_age_months {
712 0..=167 => PhysealFusionStatus::OpenCartilaginousPhysis,
713 168..=240 => PhysealFusionStatus::PartiallyFused,
714 _ => PhysealFusionStatus::ClosedMatureDiaphysis,
715 };
716 Ok(self)
717 }
718
719 pub fn age_trabecular_bmd_multiplier(
723 &self,
724 karyotype: Option<Karyotype>,
725 postmenopausal: bool,
726 ) -> f64 {
727 let age_years = (self.skeletal_bone_age_months.unwrap_or(self.chronological_age_months) as f64) / 12.0;
728 if age_years < 25.0 {
729 0.45 + 0.55 * (age_years / 25.0)
730 } else if age_years <= 35.0 {
731 1.0
732 } else {
733 let years_past_peak = age_years - 35.0;
734 let base_decline = 0.006 * years_past_peak;
735 if matches!(karyotype, Some(Karyotype::Xx)) && postmenopausal {
736 let estrogen_withdrawal = 0.18 * (1.0 - (-0.10 * years_past_peak).exp());
737 (1.0 - base_decline - estrogen_withdrawal).max(0.35)
738 } else {
739 (1.0 - base_decline).max(0.40)
740 }
741 }
742 }
743
744 pub fn pediatric_mineralization_mu(&self) -> f64 {
746 let age_m = self.skeletal_bone_age_months.unwrap_or(self.chronological_age_months) as f64;
747 if age_m >= 216.0 {
748 1.0
749 } else {
750 (0.72 + 0.28 * (age_m / 216.0)).clamp(0.72, 1.0)
751 }
752 }
753
754 pub fn disc_hydration_permill(&self) -> u16 {
756 let bio_years = self
757 .tissue_biological_age_months
758 .unwrap_or(self.chronological_age_months) as f64
759 / 12.0;
760 if bio_years <= 25.0 {
761 880
762 } else {
763 (880.0 - 3.2 * (bio_years - 25.0)).clamp(580.0, 880.0).round() as u16
764 }
765 }
766
767 pub fn neural_drive_factor(&self) -> f64 {
769 let bio_years = self
770 .tissue_biological_age_months
771 .unwrap_or(self.chronological_age_months) as f64
772 / 12.0;
773 if bio_years <= 40.0 {
774 1.0
775 } else {
776 (1.0 - 0.0065 * (bio_years - 40.0)).clamp(0.65, 1.0)
777 }
778 }
779}
780
781#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
783#[serde(rename_all = "snake_case")]
784pub enum Handedness {
785 Left,
786 Right,
787 Ambidextrous,
788 Unspecified,
789}
790
791#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
793#[serde(rename_all = "snake_case")]
794pub enum LimbDominance {
795 Left,
796 Right,
797 Symmetric,
798 Unspecified,
799}
800
801impl From<DominantSide> for LimbDominance {
802 fn from(d: DominantSide) -> Self {
803 match d {
804 DominantSide::Left => Self::Left,
805 DominantSide::Right => Self::Right,
806 DominantSide::Ambidextrous => Self::Symmetric,
807 }
808 }
809}
810
811#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
813#[serde(rename_all = "snake_case")]
814pub enum SitusClassification {
815 SitusSolitus,
816 SitusInversusTotalis,
817 SitusAmbiguusHeterotaxy,
818}
819
820#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
822pub struct LateralityProfile {
823 pub handedness: Handedness,
824 pub upper_limb_dominance: LimbDominance,
825 pub lower_limb_dominance: LimbDominance,
826 pub situs: SitusClassification,
827 pub dominant_asymmetry_pct: f64,
829}
830
831impl Default for LateralityProfile {
832 fn default() -> Self {
833 Self {
834 handedness: Handedness::Unspecified,
835 upper_limb_dominance: LimbDominance::Unspecified,
836 lower_limb_dominance: LimbDominance::Unspecified,
837 situs: SitusClassification::SitusSolitus,
838 dominant_asymmetry_pct: 8.0,
839 }
840 }
841}
842
843impl LateralityProfile {
844 pub fn side_hypertrophy_multiplier(&self, is_dominant_side: bool) -> Result<f64, String> {
846 if !self.dominant_asymmetry_pct.is_finite()
847 || !(0.0..=30.0).contains(&self.dominant_asymmetry_pct)
848 {
849 return Err("dominant_asymmetry_pct must be finite and in [0.0, 30.0]".into());
850 }
851 if !is_dominant_side
852 || matches!(
853 self.upper_limb_dominance,
854 LimbDominance::Symmetric | LimbDominance::Unspecified
855 )
856 {
857 Ok(1.0)
858 } else {
859 Ok(1.0 + self.dominant_asymmetry_pct / 100.0)
860 }
861 }
862}
863
864#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
866pub struct PhysiologicalModifierSummary {
867 pub trabecular_bmd_multiplier: f64,
868 pub mineralization_multiplier: f64,
869 pub cortical_porosity_delta: f64,
870 pub ligament_laxity_scale: f64,
871 pub side_hypertrophy_multiplier: f64,
872 pub disc_hydration_permill: u16,
873 pub neural_drive_factor: f64,
874 pub epistemic_status: EpistemicStatus,
875}
876
877pub fn apply_physiological_modifiers_to_density(
880 bone: &SkeletalDensityProfile,
881 muscle: &MuscleQualityProfile,
882 endocrine: &EndocrineOsteoState,
883 age: &AgeOntogenyProfile,
884 laterality: &LateralityProfile,
885 karyotype: Option<Karyotype>,
886 is_dominant_side: bool,
887) -> Result<(SkeletalDensityProfile, MuscleQualityProfile, PhysiologicalModifierSummary), String> {
888 bone.validate()?;
889 endocrine.validate()?;
890 let ligament_laxity_scale = endocrine.ligament_laxity_scale()?;
891 let side_hypertrophy_multiplier = laterality.side_hypertrophy_multiplier(is_dominant_side)?;
892
893 let postmenopausal = matches!(
894 endocrine.phase,
895 ReproductiveEndocrinePhase::PostMenopause
896 );
897 let age_trab_mult = age.age_trabecular_bmd_multiplier(karyotype, postmenopausal);
898 let endo_trab_mult = endocrine.trabecular_turnover_multiplier();
899 let trabecular_bmd_multiplier = (age_trab_mult * endo_trab_mult).clamp(0.25, 1.25);
900
901 let mineralization_multiplier =
902 (age.pediatric_mineralization_mu() * endocrine.mineralization_mu_modifier()).clamp(0.45, 1.15);
903 let cortical_porosity_delta = endocrine.cortical_porosity_delta();
904 let disc_hydration_permill = age.disc_hydration_permill();
905 let neural_drive_factor = age.neural_drive_factor();
906
907 let mut out_bone = bone.clone();
908 out_bone.trabecular_apparent_density_g_cm3 =
909 (bone.trabecular_apparent_density_g_cm3 * trabecular_bmd_multiplier).max(0.01);
910 out_bone.trabecular_bv_tv = (bone.trabecular_bv_tv * trabecular_bmd_multiplier).clamp(0.01, 1.0);
911 out_bone.cortical_thickness_mm =
912 (bone.cortical_thickness_mm * side_hypertrophy_multiplier * age_trab_mult.sqrt()).max(0.2);
913 out_bone.cortical_porosity_ratio =
914 (bone.cortical_porosity_ratio + cortical_porosity_delta).clamp(0.0, 0.95);
915 out_bone.mineralization_degree_mu =
916 (bone.mineralization_degree_mu * mineralization_multiplier).clamp(0.2, 1.5);
917 out_bone.physeal_fusion = age.physeal_status;
918 out_bone.epistemic_status = EpistemicStatus::Hypothesis;
919
920 let mut out_muscle = muscle.clone();
921 out_muscle.pcsa_cm2 = muscle.pcsa_cm2 * side_hypertrophy_multiplier;
922 let gc_imat_shift = if endocrine.glucocorticoid_exposure { 0.06 } else { 0.0 };
923 out_muscle.imat_fraction = (muscle.imat_fraction + gc_imat_shift).clamp(0.0, 1.0);
924 out_muscle.neural_activation_factor =
925 (muscle.neural_activation_factor * neural_drive_factor).clamp(0.0, 1.0);
926 out_muscle.recompute_quality_eta();
927 out_muscle.epistemic_status = EpistemicStatus::Hypothesis;
928
929 let summary = PhysiologicalModifierSummary {
930 trabecular_bmd_multiplier,
931 mineralization_multiplier,
932 cortical_porosity_delta,
933 ligament_laxity_scale,
934 side_hypertrophy_multiplier,
935 disc_hydration_permill,
936 neural_drive_factor,
937 epistemic_status: EpistemicStatus::Hypothesis,
938 };
939
940 Ok((out_bone, out_muscle, summary))
941}
942
943#[cfg(test)]
944mod tests {
945 use super::*;
946 use crate::anatomy::accumulate::{SystemBurden, accumulate};
947 use crate::anatomy::factor::{EvidenceTier, Factor, FactorKind};
948
949 #[test]
950 fn cycle_phase_progresses_and_wraps() {
951 assert_eq!(CyclePhase::Menstrual.next(), CyclePhase::Follicular);
952 assert_eq!(CyclePhase::Follicular.next(), CyclePhase::Ovulatory);
953 assert_eq!(CyclePhase::Ovulatory.next(), CyclePhase::Luteal);
954 assert_eq!(
955 CyclePhase::Luteal.next(),
956 CyclePhase::Menstrual,
957 "wraps to a new cycle"
958 );
959 }
960
961 #[test]
962 fn trimesters_advance_then_end_at_birth_not_a_fourth_pregnancy_trimester() {
963 assert_eq!(Trimester::First.next(), Some(Trimester::Second));
964 assert_eq!(Trimester::Second.next(), Some(Trimester::Third));
965 assert_eq!(
966 Trimester::Third.next(),
967 None,
968 "birth follows the third, not a fourth trimester of pregnancy"
969 );
970 assert_eq!(Trimester::Third.week_span(), (28, 40));
971 }
972
973 #[test]
974 fn continuum_transitions_encode_the_biological_ordering() {
975 use ReproductiveState::*;
976 assert!(PreMenarche.can_transition_to(Cycling(CyclePhase::Menstrual)));
978 assert!(
979 !PreMenarche.can_transition_to(Pregnant(Trimester::First)),
980 "no jump straight to pregnancy"
981 );
982
983 assert!(Cycling(CyclePhase::Luteal).can_transition_to(Pregnant(Trimester::First)));
985 assert!(Cycling(CyclePhase::Luteal).can_transition_to(Cycling(CyclePhase::Menstrual)));
986 assert!(Cycling(CyclePhase::Follicular).can_transition_to(Perimenopause));
987
988 assert!(Pregnant(Trimester::First).can_transition_to(Pregnant(Trimester::Second)));
990 assert!(Pregnant(Trimester::Third).can_transition_to(Postpartum));
991 assert!(!Pregnant(Trimester::Third).can_transition_to(Pregnant(Trimester::First)));
992
993 assert!(Postpartum.can_transition_to(Lactating));
995 assert!(Postpartum.can_transition_to(Cycling(CyclePhase::Menstrual)));
996
997 assert!(Perimenopause.can_transition_to(PostMenopause));
999 assert!(PostMenopause.next_states().is_empty());
1000 }
1001
1002 #[test]
1003 fn baseline_and_pre_menarche_do_not_modulate() {
1004 assert!(
1005 state_modulator(PhysiologicalState::Baseline)
1006 .system_scale_pct
1007 .is_empty()
1008 );
1009 assert!(whole_body_profile(PhysiologicalState::Baseline).is_empty());
1010 assert_eq!(
1011 state_modulator(PhysiologicalState::Reproductive(
1012 ReproductiveState::PreMenarche
1013 ))
1014 .scale_for("circulatory"),
1015 100
1016 );
1017 }
1018
1019 #[test]
1020 fn pregnancy_engages_the_whole_body_and_deepens_by_trimester() {
1021 let t1 = state_modulator(PhysiologicalState::Reproductive(
1022 ReproductiveState::Pregnant(Trimester::First),
1023 ));
1024 let t3 = state_modulator(PhysiologicalState::Reproductive(
1025 ReproductiveState::Pregnant(Trimester::Third),
1026 ));
1027
1028 assert!(t3.scale_for("circulatory") > t1.scale_for("circulatory"));
1030 let profile = whole_body_profile(PhysiologicalState::Reproductive(
1032 ReproductiveState::Pregnant(Trimester::Third),
1033 ));
1034 assert!(
1035 profile.len() >= 5,
1036 "third-trimester pregnancy engages many systems: {}",
1037 profile.len()
1038 );
1039 assert!(profile.iter().all(|e| e.scale_pct > 100));
1040 let circ = profile
1042 .iter()
1043 .find(|e| e.system_id == "circulatory")
1044 .unwrap();
1045 assert_eq!(circ.level, EngagementLevel::High);
1046 assert!(!circ.plain_label.is_empty(), "accessibility label present");
1047 }
1048
1049 #[test]
1050 fn modulator_scales_an_external_adverse_load_not_the_state_itself() {
1051 let med = Factor::new(
1053 "med:nephrotoxic",
1054 FactorKind::Medication,
1055 "a kidney-taxing medication",
1056 )
1057 .targeting(
1058 "urinary",
1059 Effect::Adverse,
1060 EvidenceTier::ClinicalEvidence,
1061 400,
1062 );
1063 let burdens = accumulate(&[med]);
1064 let renal_base = burdens
1065 .iter()
1066 .find(|b| b.system_id == "urinary")
1067 .unwrap()
1068 .net_milli;
1069 assert_eq!(renal_base, 400);
1070
1071 let preg = state_modulator(PhysiologicalState::Reproductive(
1073 ReproductiveState::Pregnant(Trimester::Third),
1074 ));
1075 let modulated = preg.apply_to_burdens(&burdens);
1076 let renal_preg = modulated
1077 .iter()
1078 .find(|b| b.system_id == "urinary")
1079 .unwrap()
1080 .net_milli;
1081 assert!(
1082 renal_preg > renal_base,
1083 "the external load lands harder: {renal_preg} > {renal_base}"
1084 );
1085 assert_eq!(
1086 renal_preg,
1087 400 * 130 / 100,
1088 "scaled by the seed renal engagement (130%)"
1089 );
1090
1091 let unrelated = vec![SystemBurden {
1093 system_id: "sensory".into(),
1094 adverse_milli: 200,
1095 supportive_milli: 0,
1096 net_milli: 200,
1097 adverse_contributors: vec!["x".into()],
1098 supportive_contributors: vec![],
1099 }];
1100 assert_eq!(preg.apply_to_burdens(&unrelated)[0].net_milli, 200);
1101 }
1102
1103 #[test]
1104 fn support_is_not_scaled_and_net_floors_at_zero() {
1105 let preg = state_modulator(PhysiologicalState::Reproductive(
1106 ReproductiveState::Pregnant(Trimester::Third),
1107 ));
1108 let b = vec![SystemBurden {
1109 system_id: "urinary".into(),
1110 adverse_milli: 100,
1111 supportive_milli: 500,
1112 net_milli: 0,
1113 adverse_contributors: vec!["a".into()],
1114 supportive_contributors: vec!["b".into()],
1115 }];
1116 let out = preg.apply_to_burdens(&b);
1117 assert_eq!(out[0].adverse_milli, 130, "adverse scaled 100→130");
1118 assert_eq!(out[0].supportive_milli, 500, "support unchanged");
1119 assert_eq!(
1120 out[0].net_milli, 0,
1121 "still floored at 0 (support exceeds scaled adverse)"
1122 );
1123 }
1124
1125 #[test]
1126 fn state_can_drive_a_timeline_via_environment_modulators() {
1127 let preg = state_modulator(PhysiologicalState::Reproductive(
1128 ReproductiveState::Pregnant(Trimester::Second),
1129 ));
1130 let mods = preg.as_environment_modulators(0, 40 * 7 * 24 * 60);
1131 assert_eq!(mods.len(), preg.system_scale_pct.len());
1133 let renal = mods
1134 .iter()
1135 .find(|m| m.target_system.as_deref() == Some("urinary"))
1136 .unwrap();
1137 assert_eq!(renal.target_effect, Some(Effect::Adverse));
1138 assert_eq!(renal.scale_pct, 125);
1139 }
1140
1141 #[test]
1142 fn serde_round_trips() {
1143 let state = PhysiologicalState::Reproductive(ReproductiveState::Pregnant(Trimester::Third));
1144 let json = serde_json::to_string(&state_modulator(state)).unwrap();
1145 let back: StateModulator = serde_json::from_str(&json).unwrap();
1146 assert_eq!(state_modulator(state), back);
1147 }
1148
1149 #[test]
1150 fn endocrine_and_ontogeny_modifiers_adjust_density_and_laxity_honestly() {
1151 use super::super::densitometry::SpeciesDensitometryPreset;
1152
1153 let baseline_bone =
1154 SkeletalDensityProfile::from_preset(SpeciesDensitometryPreset::HumanYoungAdultFemale);
1155 let baseline_muscle =
1156 MuscleQualityProfile::new("quadriceps", 420.0, 10.0, 0.20, 40.0, 50.0, 0.04, 1.0)
1157 .unwrap();
1158
1159 let preg = EndocrineOsteoState::for_phase(ReproductiveEndocrinePhase::Pregnant(
1161 Trimester::Third,
1162 ));
1163 assert!(preg.ligament_laxity_scale().unwrap() > 1.25);
1164
1165 let postmeno =
1167 EndocrineOsteoState::for_phase(ReproductiveEndocrinePhase::PostMenopause);
1168 let elderly_age = AgeOntogenyProfile::from_age_months(72 * 12).unwrap();
1169 assert_eq!(elderly_age.life_stage, OntogeneticStage::Senescent);
1170 assert_eq!(
1171 elderly_age.physeal_status,
1172 PhysealFusionStatus::ClosedMatureDiaphysis
1173 );
1174
1175 let young_age = AgeOntogenyProfile::from_age_months(28 * 12).unwrap();
1176 let lat = LateralityProfile {
1177 handedness: Handedness::Right,
1178 upper_limb_dominance: LimbDominance::Right,
1179 lower_limb_dominance: LimbDominance::Right,
1180 situs: SitusClassification::SitusSolitus,
1181 dominant_asymmetry_pct: 10.0,
1182 };
1183
1184 let (bone_young_dom, muscle_young_dom, _) = apply_physiological_modifiers_to_density(
1185 &baseline_bone,
1186 &baseline_muscle,
1187 &EndocrineOsteoState::default(),
1188 &young_age,
1189 &lat,
1190 Some(Karyotype::Xx),
1191 true,
1192 )
1193 .unwrap();
1194 let (bone_postmeno, muscle_postmeno, summary_pm) =
1195 apply_physiological_modifiers_to_density(
1196 &baseline_bone,
1197 &baseline_muscle,
1198 &postmeno,
1199 &elderly_age,
1200 &lat,
1201 Some(Karyotype::Xx),
1202 false,
1203 )
1204 .unwrap();
1205
1206 assert!(bone_young_dom.cortical_thickness_mm > baseline_bone.cortical_thickness_mm);
1207 assert!(muscle_young_dom.pcsa_cm2 > baseline_muscle.pcsa_cm2);
1208 assert!(
1209 bone_postmeno.trabecular_apparent_density_g_cm3
1210 < bone_young_dom.trabecular_apparent_density_g_cm3
1211 );
1212 assert!(muscle_postmeno.effective_quality_eta < muscle_young_dom.effective_quality_eta);
1213 assert_eq!(summary_pm.epistemic_status, EpistemicStatus::Hypothesis);
1214
1215 let child = AgeOntogenyProfile::from_age_months(10 * 12).unwrap();
1217 assert_eq!(child.physeal_status, PhysealFusionStatus::OpenCartilaginousPhysis);
1218 assert!(child.pediatric_mineralization_mu() < 1.0);
1219 }
1220}