Skip to main content

wellfare_core/anatomy/
physiology.rs

1//! P1 — the **reproductive-continuum state model** (plan of record:
2//! `docs/plans/reproductive-continuum-and-maternal-fetal-dyad.md`, §3.1–§3.2, §8).
3//!
4//! This is the continuum-as-baseline layer the plan's whole argument turns on: reproduction and the
5//! maternal–fetal continuum are **first-class baseline biology**, not a `reproductive` subsystem sitting
6//! quietly as 1-of-17 (§0, §1.1). So the model gains a **physiological-state axis** — a state machine over
7//! the continuum (menarche → cyclical phases → conception → gestation → birth → the fourth trimester →
8//! lactation → perimenopause → menopause) — and a **[`StateModulator`]** that re-parameterises *all* the
9//! body systems by the current state, the structural sibling of [`EnvironmentModulator`](super::temporal::EnvironmentModulator)
10//! but keyed by physiological state rather than the weather.
11//!
12//! **Baseline, not deviation — and not pathology.** A state is represented as heightened whole-body
13//! *engagement* ([`whole_body_profile`]), never as adverse "burden": pregnancy is not a disease, and the
14//! modulator does not manufacture load out of a healthy state. What the modulator *does* is change how an
15//! *external* load lands — a nephrotoxic medication is a bigger ask of the renal system when filtration is
16//! already elevated in pregnancy. The heightened engagement is the state; the adverse thing (if any) is
17//! the external factor.
18//!
19//! **Honesty (§6, §10 — unchanged).** Everything here is **coarse and illustrative**: the per-system
20//! scale table is a *seed* of well-established baseline-physiology *directions* (like the existing
21//! `seed_knowledge_base`), not precise clinical magnitudes, and it is integer-only (no float health
22//! arithmetic). The authoritative milestone content, the dignity-centered framing, and any specifics that
23//! go past structural "consider discussing with a clinician / midwife" are **curation-grade — Timothy's /
24//! an expert's to supply (§9)**, not agent-inventable. Nothing here is a diagnosis or a fitness-to-do-X
25//! claim.
26
27use 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// ===========================================================================
39// The continuum states
40// ===========================================================================
41
42/// A phase of the menstrual cycle. The recurring ~monthly timeline (§1.3); ordered as it progresses.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum CyclePhase {
46    /// Menstruation — the shedding phase that (by convention) opens the cycle.
47    Menstrual,
48    /// Follicular — post-menstrual, follicle maturation.
49    Follicular,
50    /// Ovulatory — around ovulation.
51    Ovulatory,
52    /// Luteal — post-ovulatory, pre-menstrual.
53    Luteal,
54}
55
56impl CyclePhase {
57    /// The phase the cycle advances to next (wraps `Luteal → Menstrual`).
58    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    /// Accessibility-first plain wording (non-diagnostic).
68    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/// A trimester of pregnancy — the staged ~40-week timeline (§1.3).
79#[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    /// The next trimester, or `None` after the third (birth follows, not a fourth trimester of *pregnancy*
89    /// — the "fourth trimester" is [`ReproductiveState::Postpartum`], a distinct state of the mother's body).
90    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    /// The conventional gestational-week span (inclusive start, inclusive end) of this trimester. Coarse
99    /// clinical convention, not a per-person claim.
100    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    /// Plain-language label.
109    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/// A point on the reproductive continuum — **baseline biology**, modelled as a whole-body physiological
119/// state rather than an event on the `reproductive` system (§1.1). This is the "dignity of people born
120/// female" spine: the continuum is the model, not the steady state.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
122#[serde(rename_all = "snake_case")]
123pub enum ReproductiveState {
124    /// Before menarche (the first period) — the pre-cyclical baseline.
125    PreMenarche,
126    /// The recurring cycle, at a given [`CyclePhase`].
127    Cycling(CyclePhase),
128    /// Pregnancy, at a given [`Trimester`].
129    Pregnant(Trimester),
130    /// The **fourth trimester** — early postpartum recovery of *the mother's* body (§3.5). A first-class
131    /// state, deliberately kept in frame rather than dropped at birth.
132    Postpartum,
133    /// Lactation.
134    Lactating,
135    /// Perimenopause — the transition (cycles becoming irregular).
136    Perimenopause,
137    /// After menopause (cycles have ceased).
138    PostMenopause,
139}
140
141impl ReproductiveState {
142    /// The valid successor states along the continuum. A state machine, not a free jump: it encodes the
143    /// biological ordering (menarche opens cycling; conception can happen from any cycle phase; gestation
144    /// advances by trimester then to postpartum; postpartum leads to lactation and/or the cycle's return;
145    /// perimenopause precedes menopause). `PostMenopause` is terminal.
146    ///
147    /// Pregnancy can end at any trimester (→ `Postpartum`), which the transitions allow; this models the
148    /// state graph, it does not assert anything about a person's course.
149    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    /// Whether `next` is a valid continuum transition from `self`.
170    pub fn can_transition_to(self, next: ReproductiveState) -> bool {
171        self.next_states().contains(&next)
172    }
173
174    /// Accessibility-first plain wording (non-diagnostic, dignity-centered — the everyday name, not a
175    /// clinical label). Richer per-state framing is curation-grade (§9) and deferred.
176    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/// The physiological-state axis. Currently the reproductive continuum plus a neutral [`Baseline`]; the
191/// enum leaves room for other whole-body physiological states later without inventing them now.
192///
193/// [`Baseline`]: PhysiologicalState::Baseline
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub enum PhysiologicalState {
197    /// No active continuum modulation. **Not** a "normal/default" value-judgement (that framing is exactly
198    /// the male-default bias §0 corrects) — just the absence of an active whole-body state modulation
199    /// (e.g. the state has not been declared, or does not apply to this body's biology).
200    Baseline,
201    /// A point on the reproductive continuum.
202    Reproductive(ReproductiveState),
203}
204
205impl PhysiologicalState {
206    /// Plain-language label.
207    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// ===========================================================================
216// Whole-body modulation — the StateModulator (§3.2)
217// ===========================================================================
218
219/// Per-system whole-body modulation induced by a physiological state — the structural sibling of
220/// [`EnvironmentModulator`], but keyed by the current state and applying across the whole body.
221///
222/// `system_scale_pct` gives, per system id, a scale in percent (`100` = unchanged, `>100` = the system is
223/// more heavily engaged in this state, `<100` = less). A system absent from the list is `100`. The scale
224/// expresses how much **more of an ask an external load is** on an already-more-engaged system in this
225/// state — see [`apply_to_burdens`](StateModulator::apply_to_burdens). It never fabricates burden from the
226/// healthy state itself.
227#[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    /// The scale (percent) this state applies to `system_id` (default `100` if unlisted).
235    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    /// Scale one adverse-load magnitude on a system by this state (integer math; clamped to the model
244    /// ceiling 1000).
245    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    /// Apply the state modulation to a set of `SystemBurden()`s: the **adverse** load on each system is
250    /// scaled by that system's state engagement, then `net` is recomputed (`adverse − supportive`, floored
251    /// at 0). Supportive load is left as entered. This models "the same external load lands harder on a
252    /// system this state already engages more" without pathologising the state.
253    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    /// Re-express this modulation as a temporal [`EnvironmentModulator`] over `[from_minute, to_minute]`,
274    /// for one system — so a physiological state can be dropped onto a [`Timeline`](super::temporal::Timeline)
275    /// and scale that system's adverse contributions the same way the weather does. One modulator per
276    /// engaged system (the timeline layer matches a single `target_system`).
277    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
297/// The **illustrative seed** per-system engagement for a physiological state (§8: "illustrative-but-honest
298/// seed like the existing knowledge seed"). Encodes only well-established baseline-physiology *directions*
299/// — coarse, not precise magnitudes; the authoritative per-state/per-system content + framing is
300/// curation-grade and Timothy's/an expert's to supply (§9.2/§9.3). Systems not listed stay at `100`.
301fn seed_scale_table(state: PhysiologicalState) -> &'static [(&'static str, u32)] {
302    use PhysiologicalState::*;
303    use ReproductiveState::*;
304    match state {
305        Baseline | Reproductive(PreMenarche) => &[],
306        // Cyclical phases — mild, phase-dependent shifts.
307        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        // Pregnancy — a whole-body reconfiguration deepening by trimester (blood volume/cardiac output,
314        // renal filtration, respiratory tidal volume, endocrine, musculoskeletal load).
315        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        // The fourth trimester — recovery: hormone shift, musculoskeletal recovery, sleep/mood load.
339        Reproductive(Postpartum) => &[
340            ("endocrine", 130),
341            ("nervous", 115),
342            ("circulatory", 110),
343            ("skeletal", 115),
344            ("muscular", 115),
345        ],
346        // Lactation — endocrine (prolactin/oxytocin) + nutritional/skeletal (calcium) demand.
347        Reproductive(Lactating) => &[("endocrine", 125), ("digestive", 115), ("skeletal", 110)],
348        // Perimenopause — endocrine variability, bone, vasomotor/mood.
349        Reproductive(Perimenopause) => &[
350            ("endocrine", 135),
351            ("nervous", 115),
352            ("skeletal", 115),
353            ("circulatory", 110),
354        ],
355        // Post-menopause — bone-density and cardiovascular-risk shifts.
356        Reproductive(PostMenopause) => {
357            &[("skeletal", 120), ("circulatory", 115), ("endocrine", 110)]
358        }
359    }
360}
361
362/// The illustrative-seed [`StateModulator`] for a physiological state.
363pub 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// ===========================================================================
374// The whole-body engagement profile — the dignified, non-pathological view
375// ===========================================================================
376
377/// How heavily a state engages a body system — a **descriptive**, non-pathological classification (a state
378/// is not "burden"). Derived from the seed scale.
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
380#[serde(rename_all = "snake_case")]
381pub enum EngagementLevel {
382    /// Not notably changed by this state (`< 110%`).
383    Baseline,
384    /// More engaged (`110–124%`).
385    Elevated,
386    /// Substantially more engaged (`≥ 125%`).
387    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/// One system's engagement under a physiological state.
403#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
404pub struct SystemEngagement {
405    pub system_id: String,
406    /// Clinical label (progressive disclosure).
407    pub system_label: String,
408    /// Accessibility-first plain label.
409    pub plain_label: String,
410    /// The illustrative-seed engagement scale (percent).
411    pub scale_pct: u32,
412    pub level: EngagementLevel,
413}
414
415/// The whole-body engagement profile for a physiological state: the systems this state engages **above
416/// baseline**, in canonical [`BODY_SYSTEMS`] order, each with a coarse [`EngagementLevel`]. This is the
417/// dignified representation of "a state re-parameterises all systems" — heightened *engagement*, not
418/// adverse burden, and never a claim about a specific person. Systems at baseline are omitted.
419pub 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// ===========================================================================
439// BIO-WP-05: Endocrine, Ontogenetic & Laterality Modifiers for Densitometry
440// ===========================================================================
441
442/// Endocrine & reproductive-continuum phase for musculoskeletal turnover and
443/// ligamentous laxity calibration (Spec §5.5).
444#[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    /// Eu-gonadal baseline when no cyclic/gestational/menopausal phase applies.
455    AdultBaseline,
456    /// Age-related androgen decline (andropause).
457    Andropause,
458    /// Declared exogenous endocrine modulation (HRT / gender-affirming / medical suppression).
459    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/// Systemic endocrine, renal, and vitamin-D bone/ligament turnover state (Spec §5.3 & §5.5).
486#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
487pub struct EndocrineOsteoState {
488    pub phase: ReproductiveEndocrinePhase,
489    /// Relative estrogenic activity (`1.0` = young-adult baseline, `< 0.3` = hypoestrogenic).
490    pub estrogen_status_ratio: f64,
491    /// Relative androgenic activity (`1.0` = young-adult baseline).
492    pub androgen_status_ratio: f64,
493    /// Circulating relaxin concentration in ng/mL (`0.0` non-pregnant; `0.5..=3.0` pregnant).
494    pub relaxin_ng_ml: f64,
495    /// Serum 25(OH)D in ng/mL (`< 20.0` indicates deficiency / osteomalacic risk).
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub vitamin_d_25oh_ng_ml: Option<f64>,
498    /// Serum parathyroid hormone in pg/mL (`> 65.0` increases cortical porosity).
499    #[serde(default, skip_serializing_if = "Option::is_none")]
500    pub pth_pg_ml: Option<f64>,
501    /// Estimated GFR in mL/min/1.73 m^2 (`< 45.0` flags CKD-MBD mineral-bone shift).
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub egfr_ml_min_1_73m2: Option<f64>,
504    /// Chronic systemic glucocorticoid exposure (suppresses osteoblast formation & muscle quality).
505    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    /// Illustrative baseline endocrine parameters for a given [`ReproductiveEndocrinePhase`].
516    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    /// Validate all endocrine measurements are finite and within physical bounds.
547    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    /// Smooth relaxin-mediated ligamentous stiffness multiplier in `[0.65, 1.0]`
576    /// (matches `clinical_formulas::relaxin_ligament_stiffness_modifier`).
577    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    /// Joint ROM Swing-Twist cone laxity scale (`>= 1.0`; inverse of stiffness modifier).
583    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    /// Trabecular bone-turnover multiplier reflecting physiological lactation mobilization
589    /// (`~0.94`, a 6% transient calcium drawdown), menopausal estrogen loss, and glucocorticoids.
590    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    /// Additive intracortical porosity shift from hyperparathyroidism, CKD-MBD, or menopause.
607    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    /// Mineralization degree (`mu_min`) multiplier capturing vitamin-D deficiency / CKD-MBD
632    /// osteomalacic hypomineralization (`< 1.0` when 25(OH)D < 20 ng/mL or eGFR < 30).
633    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/// Coarse ontogenetic life stage derived from chronological or skeletal bone age (Spec §5.5).
650#[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/// Multi-axis ontogenetic age profile separating chronological, skeletal bone, and tissue ages.
662#[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    /// Construct from chronological age in months (`0..=1560`).
675    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    /// Override skeletal bone age (Greulich-Pyle / Tanner-Whitehouse) and update physeal status.
704    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    /// Age-related trabecular BMD multiplier relative to young-adult Peak Bone Mass (25–35y = 1.0).
720    /// Matches `clinical_formulas::age_trabecular_bmd_multiplier` while remaining well-defined when
721    /// chromosomal basis is `None` (no invented sex assumption).
722    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    /// Pediatric secondary mineralization factor (`< 1.0` in childhood, `1.0` once mature).
745    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    /// Intervertebral disc / cartilage hydration permill (`0..=1000`), declining in senescence.
755    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    /// Type-II motor-unit neuromuscular drive / RFD preservation factor in `[0.65, 1.0]`.
768    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/// Handedness classification.
782#[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/// Regional limb dominance classification (bridges [`DominantSide`]).
792#[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/// Visceral / thoracic organ situs classification.
812#[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/// Bilateral dominance and visceral situs profile (Spec §5.5).
821#[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    /// Physiological cortical/PCSA hypertrophy on the dominant side (`5.0..=15.0` percent typical).
828    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    /// Multiplicative cortical thickness / PCSA scaling factor (`>= 1.0` when `is_dominant_side`).
845    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/// Summary of physiological modifiers applied to bone and muscle profiles.
865#[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
877/// Apply age, endocrine/reproductive continuum, and bilateral laterality modifiers to
878/// baseline [`SkeletalDensityProfile`] and [`MuscleQualityProfile`] records (Spec §5.5).
879pub 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        // Menarche opens the cycle at menstruation.
977        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        // Conception is reachable from any cycle phase; the cycle also advances.
984        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        // Gestation advances by trimester, then to the fourth trimester (postpartum).
989        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        // Postpartum → lactation and/or the cycle returns.
994        assert!(Postpartum.can_transition_to(Lactating));
995        assert!(Postpartum.can_transition_to(Cycling(CyclePhase::Menstrual)));
996
997        // Perimenopause precedes menopause; post-menopause is terminal.
998        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        // Circulatory (blood volume / cardiac output) engagement rises across trimesters.
1029        assert!(t3.scale_for("circulatory") > t1.scale_for("circulatory"));
1030        // It is a *whole-body* reconfiguration — many systems engaged, not just "reproductive".
1031        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        // The third-trimester circulatory engagement is classified High.
1041        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        // A nephrotoxic medication: adverse renal (urinary) load. The state adds NO factors of its own.
1052        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        // In the third trimester (renal filtration elevated) the SAME med is a bigger ask on the kidneys.
1072        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        // A system the state does not engage is untouched.
1092        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        // One modulator per engaged system, each targeting Adverse on that system.
1132        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        // Third-trimester pregnancy increases relaxin ligament laxity scale > 1.0.
1160        let preg = EndocrineOsteoState::for_phase(ReproductiveEndocrinePhase::Pregnant(
1161            Trimester::Third,
1162        ));
1163        assert!(preg.ligament_laxity_scale().unwrap() > 1.25);
1164
1165        // Postmenopausal + 72y vs young adult dominant side.
1166        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        // Pediatric bone age preserves open physis and lower secondary mineralization.
1216        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}