Skip to main content

wellfare_core/anatomy/
constitution.rs

1//! The person's **body constitution** — measurements, characteristics, and attributes they declare
2//! about their own body, and the illustrative [`BodyFit`] that maps those onto a Visible Human /
3//! CCF reference mesh.
4//!
5//! This is forum-internum / Sanctuary-class selfhood content. Every field is optional: the person
6//! declares what they know. Absence is not an assumption. The fit is a **hypothesis overlay** on a
7//! public reference body, never a scan of them and never a diagnosis.
8//!
9//! Geometry stays on the reference atlas. Constitution is a view transform (scale, regional
10//! stretch, hide declared-absent parts, coarse pregnancy bulge). It does not rewrite `.10d` files.
11
12use serde::{Deserialize, Serialize};
13
14use super::knowledge_context::SubjectKnowledgeContext;
15use super::model::{AnatomyModel, Karyotype, normalize_organ_key};
16use super::physiology::Trimester;
17
18/// Visible Human Male standing height used by the CCF / HRA male reference set.
19/// NLM Visible Human Project (male donor). Seed reference, not a population mean.
20pub const VH_MALE_STATURE_MM: u16 = 1800;
21/// Visible Human Female standing height used by the CCF / HRA female reference set.
22pub const VH_FEMALE_STATURE_MM: u16 = 1676;
23
24/// Typical sitting-height / stature ratio on the adult reference (seed).
25pub const REF_SITTING_RATIO: f32 = 0.52;
26/// Typical inseam / stature ratio on the adult reference (seed).
27pub const REF_INSEAM_RATIO: f32 = 0.45;
28
29pub const AGE_MONTHS_RANGE: (u16, u16) = (0, 1560);
30
31pub use super::measurements::BodyMeasurements;
32
33/// Side the person names as dominant, if they name one.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum DominantSide {
37    Left,
38    Right,
39    Ambidextrous,
40}
41
42/// Relatively stable facts the person declares about their body (not a measurement).
43#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
44pub struct BodyCharacteristics {
45    /// Chromosomal basis they declare — selects the CCF male/female reference set.
46    /// Biological-substrate attribute, not a gender or identity claim.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub karyotype: Option<Karyotype>,
49    /// Age in whole months (a newborn is 0; 18 years is 216).
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub age_months: Option<u16>,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub dominant_side: Option<DominantSide>,
54}
55
56impl BodyCharacteristics {
57    ///  when empty.
58    pub fn is_empty(&self) -> bool {
59        *self == Self::default()
60    }
61
62    /// The reference mesh set this declaration selects, if they named a karyotype.
63    pub fn anatomy_model(&self) -> Option<AnatomyModel> {
64        self.karyotype.map(Karyotype::anatomy_model)
65    }
66}
67
68/// Why a named structure is not present on *this* person's body.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71pub enum AbsenceReason {
72    Surgical,
73    Congenital,
74    Amputation,
75    PersonDeclared,
76}
77
78/// A structure the person says is not on their body (so the reference mesh is hidden).
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct AbsentPart {
81    /// Organ / part key (`uterus`, `prostate`, `left-leg`, or a CCF token).
82    pub key: String,
83    pub reason: AbsenceReason,
84}
85
86/// Person-authored attributes that change which parts are shown, or apply a named
87/// coarse shape (pregnancy abdomen). Not a diagnosis.
88#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
89pub struct BodyAttributes {
90    #[serde(default, skip_serializing_if = "Vec::is_empty")]
91    pub absent: Vec<AbsentPart>,
92    /// Optional pregnancy abdomen hint. Prefer the physiological-state declaration
93    /// when both exist — this is a geometry-only override.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub pregnancy: Option<Trimester>,
96    /// The person's own words. Stored, never parsed into geometry.
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub notes: Option<String>,
99    /// Declared appearance. Independent of ethnicity. Painted only when those meshes exist (W16).
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub eye_colour: Option<String>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub hair_colour: Option<String>,
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub skin_tone: Option<String>,
106}
107
108impl BodyAttributes {
109    ///  when empty.
110    pub fn is_empty(&self) -> bool {
111        self.absent.is_empty()
112            && self.pregnancy.is_none()
113            && self.notes.is_none()
114            && self.eye_colour.is_none()
115            && self.hair_colour.is_none()
116            && self.skin_tone.is_none()
117    }
118}
119
120/// The full constitution the person may author. Empty = identity fit (reference body as published).
121#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
122pub struct BodyConstitution {
123    #[serde(default)]
124    pub measurements: BodyMeasurements,
125    #[serde(default)]
126    pub characteristics: BodyCharacteristics,
127    #[serde(default)]
128    pub attributes: BodyAttributes,
129    /// Ethnicity / imported ancestry. Knowledge context only — never a fit input.
130    #[serde(default, skip_serializing_if = "SubjectKnowledgeContext::is_empty")]
131    pub knowledge: SubjectKnowledgeContext,
132}
133
134impl BodyConstitution {
135    ///  when empty.
136    pub fn is_empty(&self) -> bool {
137        self.measurements.is_empty()
138            && self.characteristics.is_empty()
139            && self.attributes.is_empty()
140            && self.knowledge.is_empty()
141    }
142
143    /// Reject values outside the soft clamps. The person can still clear a field.
144    pub fn validate(&self) -> Result<(), String> {
145        self.measurements.validate()?;
146        if let Some(a) = self.characteristics.age_months {
147            if a > AGE_MONTHS_RANGE.1 {
148                return Err(format!(
149                    "age_months {a} is outside 0–{}",
150                    AGE_MONTHS_RANGE.1
151                ));
152            }
153        }
154        Ok(())
155    }
156
157    /// The reference stature for the mesh set this constitution will be fitted onto.
158    pub fn reference_stature_mm(&self) -> u16 {
159        match self.characteristics.anatomy_model() {
160            Some(AnatomyModel::Female) => VH_FEMALE_STATURE_MM,
161            _ => VH_MALE_STATURE_MM,
162        }
163    }
164
165    /// Illustrative seed girths (mm) for the chosen reference. Not measured on the GLB.
166    pub fn reference_girths_mm(&self) -> ReferenceGirths {
167        match self.characteristics.anatomy_model() {
168            Some(AnatomyModel::Female) => ReferenceGirths {
169                chest_mm: 940,
170                waist_mm: 780,
171                hip_mm: 1000,
172                shoulder_width_mm: 360,
173            },
174            _ => ReferenceGirths {
175                chest_mm: 1000,
176                waist_mm: 900,
177                hip_mm: 980,
178                shoulder_width_mm: 410,
179            },
180        }
181    }
182
183    /// Compute the view transform. Does not invent a height from age.
184    pub fn fit(&self) -> BodyFit {
185        self.fit_with_pregnancy(self.attributes.pregnancy)
186    }
187
188    /// Same as [`Self::fit`], but a caller can pass the declared physiological
189    /// trimester so pregnancy geometry and the continuum stay one source of truth.
190    pub fn fit_with_pregnancy(&self, pregnancy: Option<Trimester>) -> BodyFit {
191        let ref_h = self.reference_stature_mm() as f32;
192        let girth = self.reference_girths_mm();
193        let mut used: Vec<String> = Vec::new();
194        let mut notes: Vec<String> = Vec::new();
195
196        let stature_scale = if let Some(h) = self.measurements.stature_mm {
197            used.push("stature_mm".into());
198            (h as f32 / ref_h).clamp(0.25, 2.4)
199        } else {
200            notes.push(
201                "No standing height declared — the body stays at Visible Human scale.".into(),
202            );
203            1.0
204        };
205
206        let mut torso_scale_y = 1.0;
207        let mut leg_scale_y = 1.0;
208        if let (Some(stature), Some(sit)) = (
209            self.measurements.stature_mm,
210            self.measurements.sitting_height_mm,
211        ) {
212            used.push("sitting_height_mm".into());
213            let person_ratio = sit as f32 / stature as f32;
214            torso_scale_y = (person_ratio / REF_SITTING_RATIO).clamp(0.7, 1.35);
215            // Keep overall stature: legs absorb the complementary stretch.
216            leg_scale_y = ((1.0 - person_ratio) / (1.0 - REF_SITTING_RATIO)).clamp(0.7, 1.45);
217        } else if let (Some(stature), Some(inseam)) =
218            (self.measurements.stature_mm, self.measurements.inseam_mm)
219        {
220            used.push("inseam_mm".into());
221            let person_ratio = inseam as f32 / stature as f32;
222            leg_scale_y = (person_ratio / REF_INSEAM_RATIO).clamp(0.7, 1.45);
223            torso_scale_y = ((1.0 - person_ratio) / (1.0 - REF_INSEAM_RATIO)).clamp(0.7, 1.35);
224        }
225
226        let arm_span_scale_x = if let (Some(stature), Some(span)) =
227            (self.measurements.stature_mm, self.measurements.arm_span_mm)
228        {
229            used.push("arm_span_mm".into());
230            (span as f32 / stature as f32).clamp(0.75, 1.25)
231        } else {
232            1.0
233        };
234
235        let chest_radial = ratio_or_one(
236            self.measurements.chest_mm,
237            girth.chest_mm,
238            &mut used,
239            "chest_mm",
240        );
241        let waist_radial = ratio_or_one(
242            self.measurements.waist_mm,
243            girth.waist_mm,
244            &mut used,
245            "waist_mm",
246        );
247        let hip_radial = ratio_or_one(self.measurements.hip_mm, girth.hip_mm, &mut used, "hip_mm");
248        let shoulder_scale_x = ratio_or_one(
249            self.measurements.shoulder_width_mm,
250            girth.shoulder_width_mm,
251            &mut used,
252            "shoulder_width_mm",
253        );
254
255        if self.measurements.weight_g.is_some() {
256            used.push("weight_g".into());
257            notes.push(
258                "Weight is stored and shown; it does not yet drive a fat/muscle morph.".into(),
259            );
260        }
261        if self.characteristics.age_months.is_some() && self.measurements.stature_mm.is_none() {
262            notes.push(
263                "Age is stored; height is not guessed from age. Declare standing height to scale the body.".into(),
264            );
265        }
266
267        let pregnancy_abdomen = match pregnancy.or(self.attributes.pregnancy) {
268            Some(Trimester::First) => 0.12,
269            Some(Trimester::Second) => 0.28,
270            Some(Trimester::Third) => 0.45,
271            None => 0.0,
272        };
273        if pregnancy_abdomen > 0.0 {
274            used.push("pregnancy".into());
275            notes.push(
276                "Pregnancy abdomen is a coarse forward bulge on the midriff, not a model of your uterus.".into(),
277            );
278        }
279        if !self.knowledge.is_empty() {
280            notes.push(
281                "Ethnicity / ancestry is knowledge context (prevalence, pharmacology, screening hypotheses). It does not change the mesh, skin, hair, or chromosomal reference.".into(),
282            );
283        }
284        if self.attributes.eye_colour.is_some()
285            || self.attributes.hair_colour.is_some()
286            || self.attributes.skin_tone.is_some()
287        {
288            notes.push(
289                "Eye / hair / skin are declared appearance. They are independent of ethnicity and are not yet painted on the mesh.".into(),
290            );
291        }
292        if self.measurements.has_beyond_anatomy_fit() {
293            notes.push(
294                "Garment, footwear, helmet, glove, and eyewear measures are stored for those Qualia surfaces. Anatomy fit currently uses height, sitting height, inseam, arm span, shoulders, chest, waist, and hip only.".into(),
295            );
296        }
297
298        let hidden_keys: Vec<String> = self
299            .attributes
300            .absent
301            .iter()
302            .map(|p| normalize_organ_key(&p.key))
303            .collect();
304        if !hidden_keys.is_empty() {
305            used.push("absent_parts".into());
306        }
307
308        notes.insert(
309            0,
310            "Illustrative fit onto a Visible Human / CCF reference body — not a scan of you."
311                .into(),
312        );
313
314        BodyFit {
315            stature_scale,
316            torso_scale_y,
317            leg_scale_y,
318            arm_span_scale_x,
319            shoulder_scale_x,
320            chest_radial,
321            waist_radial,
322            hip_radial,
323            pregnancy_abdomen,
324            pelvis_y_norm: 0.42,
325            waist_y_norm: 0.52,
326            chest_y_norm: 0.68,
327            shoulder_y_norm: 0.78,
328            hidden_keys,
329            used_fields: used,
330            honesty_notes: notes,
331            identity: stature_scale == 1.0
332                && torso_scale_y == 1.0
333                && leg_scale_y == 1.0
334                && arm_span_scale_x == 1.0
335                && shoulder_scale_x == 1.0
336                && chest_radial == 1.0
337                && waist_radial == 1.0
338                && hip_radial == 1.0
339                && pregnancy_abdomen == 0.0,
340        }
341    }
342}
343
344fn ratio_or_one(declared: Option<u16>, reference: u16, used: &mut Vec<String>, field: &str) -> f32 {
345    match declared {
346        Some(v) if reference > 0 => {
347            used.push(field.into());
348            (v as f32 / reference as f32).clamp(0.55, 1.8)
349        }
350        _ => 1.0,
351    }
352}
353
354/// Seed girths for the chosen Visible Human reference (not measured on the mesh).
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub struct ReferenceGirths {
357    pub chest_mm: u16,
358    pub waist_mm: u16,
359    pub hip_mm: u16,
360    pub shoulder_width_mm: u16,
361}
362
363/// Numeric view transform applied to decoded organ vertices in CCF space,
364/// *before* the portal's global orbit-frame normalise.
365#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
366pub struct BodyFit {
367    pub stature_scale: f32,
368    pub torso_scale_y: f32,
369    pub leg_scale_y: f32,
370    pub arm_span_scale_x: f32,
371    pub shoulder_scale_x: f32,
372    pub chest_radial: f32,
373    pub waist_radial: f32,
374    pub hip_radial: f32,
375    /// 0 = none; ~0.45 = third-trimester coarse bulge.
376    pub pregnancy_abdomen: f32,
377    pub pelvis_y_norm: f32,
378    pub waist_y_norm: f32,
379    pub chest_y_norm: f32,
380    pub shoulder_y_norm: f32,
381    pub hidden_keys: Vec<String>,
382    pub used_fields: Vec<String>,
383    pub honesty_notes: Vec<String>,
384    /// True when the fit is the identity (no declared geometry).
385    pub identity: bool,
386}
387
388impl BodyFit {
389    /// Identity transform.
390    pub fn identity() -> Self {
391        Self {
392            stature_scale: 1.0,
393            torso_scale_y: 1.0,
394            leg_scale_y: 1.0,
395            arm_span_scale_x: 1.0,
396            shoulder_scale_x: 1.0,
397            chest_radial: 1.0,
398            waist_radial: 1.0,
399            hip_radial: 1.0,
400            pregnancy_abdomen: 0.0,
401            pelvis_y_norm: 0.42,
402            waist_y_norm: 0.52,
403            chest_y_norm: 0.68,
404            shoulder_y_norm: 0.78,
405            hidden_keys: Vec::new(),
406            used_fields: Vec::new(),
407            honesty_notes: vec![
408                "No constitution declared — showing the public reference body.".into(),
409            ],
410            identity: true,
411        }
412    }
413
414    /// Whether `organ_key` should be omitted from the assembled body.
415    pub fn hides(&self, organ_key: &str) -> bool {
416        let norm = normalize_organ_key(organ_key);
417        self.hidden_keys
418            .iter()
419            .any(|k| k == &norm || norm.contains(k.as_str()) || k.contains(norm.as_str()))
420    }
421
422    /// Apply the fit to one vertex in the body's axis-aligned bounds.
423    /// `y` is the CCF up axis (feet → head).
424    pub fn transform_point(&self, p: [f32; 3], gmin: [f32; 3], gmax: [f32; 3]) -> [f32; 3] {
425        let span_y = (gmax[1] - gmin[1]).max(1e-6);
426        let mid_x = (gmin[0] + gmax[0]) * 0.5;
427        let mid_z = (gmin[2] + gmax[2]) * 0.5;
428        let y_norm = ((p[1] - gmin[1]) / span_y).clamp(0.0, 1.0);
429
430        let mut x = p[0] - mid_x;
431        let mut y = p[1];
432        let mut z = p[2] - mid_z;
433
434        let y_seg = if y_norm < self.pelvis_y_norm {
435            self.leg_scale_y
436        } else {
437            self.torso_scale_y
438        };
439        y = gmin[1] + (y - gmin[1]) * y_seg;
440
441        let radial = if y_norm < self.pelvis_y_norm {
442            lerp(
443                1.0,
444                self.hip_radial,
445                smoothstep(0.20, self.pelvis_y_norm, y_norm),
446            )
447        } else if y_norm < self.waist_y_norm {
448            lerp(
449                self.hip_radial,
450                self.waist_radial,
451                smoothstep(self.pelvis_y_norm, self.waist_y_norm, y_norm),
452            )
453        } else if y_norm < self.chest_y_norm {
454            lerp(
455                self.waist_radial,
456                self.chest_radial,
457                smoothstep(self.waist_y_norm, self.chest_y_norm, y_norm),
458            )
459        } else {
460            lerp(
461                self.chest_radial,
462                self.shoulder_scale_x,
463                smoothstep(self.chest_y_norm, self.shoulder_y_norm, y_norm),
464            )
465        };
466        x *= radial * self.arm_span_scale_x;
467        z *= radial;
468
469        if self.pregnancy_abdomen > 0.0 {
470            let band = bump(y_norm, 0.48, 0.10);
471            z += self.pregnancy_abdomen * band * span_y * 0.18;
472            x *= 1.0 + self.pregnancy_abdomen * band * 0.12;
473        }
474
475        [
476            mid_x + x * self.stature_scale,
477            (gmin[1] + (y - gmin[1]) * self.stature_scale),
478            mid_z + z * self.stature_scale,
479        ]
480    }
481
482    /// Applies in place.
483    pub fn apply_in_place(&self, positions: &mut [[f32; 3]], gmin: [f32; 3], gmax: [f32; 3]) {
484        if self.identity {
485            return;
486        }
487        for p in positions.iter_mut() {
488            *p = self.transform_point(*p, gmin, gmax);
489        }
490    }
491}
492
493// ===========================================================================
494// 3-Stage Calibration Pipeline (BIO-WP-08):
495//   Stage 1: SSDM Subspace Projection & Non-Uniform Bone Scaling Tensors S_b
496//   Stage 2: Locally Affine Stiffness-Penalized Registration
497//   Stage 3: Harmonic / Biharmonic TPS Soft-Tissue & Organ Cavity Co-Calibration
498// ===========================================================================
499
500/// Number of standardized anthropometric / ontogenetic / endocrine features in [`SsdmBasis`].
501pub const SSDM_FEATURE_COUNT: usize = 14;
502
503const REF_WEIGHT_MALE_G: f64 = 78_000.0;
504const REF_WEIGHT_FEMALE_G: f64 = 64_000.0;
505const REF_THIGH_MALE_MM: f64 = 560.0;
506const REF_THIGH_FEMALE_MM: f64 = 550.0;
507const REF_CALF_MALE_MM: f64 = 375.0;
508const REF_CALF_FEMALE_MM: f64 = 355.0;
509const REF_BICEPS_MALE_MM: f64 = 325.0;
510const REF_BICEPS_FEMALE_MM: f64 = 285.0;
511
512/// Per-bone sensitivity of log-scale `(sx, sy, sz)` to a single [`SsdmShapeMode`].
513#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
514pub struct BoneScaleLoading {
515    pub bone_id: String,
516    pub axis_loadings: [f64; 3],
517}
518
519/// One principal geometric mode in the Statistical Shape & Density Model (`SsdmBasis`).
520#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
521pub struct SsdmShapeMode {
522    pub id: String,
523    /// Prior variance (`sigma_i^2 > 0`) for ridge regularization.
524    pub eigenvalue: f64,
525    /// Loadings across the [`SSDM_FEATURE_COUNT`] standardized anthropometric features.
526    pub feature_loadings: [f64; SSDM_FEATURE_COUNT],
527    /// Resulting per-bone log-scale sensitivities `[dx, dy, dz]`.
528    pub bone_loadings: Vec<BoneScaleLoading>,
529}
530
531/// One principal bone-mineral-density (BMD) mode in [`SsdmBasis`].
532#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
533pub struct SsdmDensityMode {
534    pub id: String,
535    pub eigenvalue: f64,
536    pub age_loading: f64,
537    pub endocrine_loading: f64,
538    pub mass_loading: f64,
539    /// Regional apparent density shift `delta rho_app` (g/cm^3 per unit mode weight).
540    pub regional_bmd_loadings: Vec<(String, f64)>,
541}
542
543/// Low-rank Statistical Shape & Density Mode basis for Stage 1 projection.
544#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
545pub struct SsdmBasis {
546    pub reference_model: AnatomyModel,
547    pub mean_stature_mm: f64,
548    pub mean_mass_g: f64,
549    pub regularization_lambda: f64,
550    pub shape_modes: Vec<SsdmShapeMode>,
551    pub density_modes: Vec<SsdmDensityMode>,
552}
553
554impl SsdmBasis {
555    /// Construct the canonical human low-rank SSDM basis for `VH_Male` or `VH_Female`.
556    pub fn canonical_human(reference_model: AnatomyModel) -> Self {
557        let (mean_stature_mm, mean_mass_g) = match reference_model {
558            AnatomyModel::Male => (VH_MALE_STATURE_MM as f64, REF_WEIGHT_MALE_G),
559            AnatomyModel::Female => (VH_FEMALE_STATURE_MM as f64, REF_WEIGHT_FEMALE_G),
560        };
561
562        let loading = |bone_id: &str, axis_loadings: [f64; 3]| BoneScaleLoading {
563            bone_id: bone_id.to_string(),
564            axis_loadings,
565        };
566
567        let shape_modes = vec![
568            // Mode 1: Overall stature & longitudinal skeletal allometry
569            SsdmShapeMode {
570                id: "overall_stature_allometry".to_string(),
571                eigenvalue: 1.0,
572                feature_loadings: [
573                    0.78, 0.04, 0.06, 0.56, 0.16, 0.10, 0.06, 0.10, 0.00, 0.04, 0.04, 0.04,
574                    -0.06, 0.00,
575                ],
576                bone_loadings: vec![
577                    loading("cranium", [0.22, 0.24, 0.22]),
578                    loading("thoracic_ribcage", [0.38, 0.72, 0.35]),
579                    loading("lumbar_spine", [0.30, 0.80, 0.30]),
580                    loading("pelvis", [0.42, 0.65, 0.40]),
581                    loading("femur_l", [0.32, 0.92, 0.32]),
582                    loading("femur_r", [0.32, 0.92, 0.32]),
583                    loading("tibia_l", [0.30, 0.94, 0.30]),
584                    loading("tibia_r", [0.30, 0.94, 0.30]),
585                    loading("humerus_l", [0.28, 0.88, 0.28]),
586                    loading("humerus_r", [0.28, 0.88, 0.28]),
587                    loading("radius_ulna_l", [0.26, 0.90, 0.26]),
588                    loading("radius_ulna_r", [0.26, 0.90, 0.26]),
589                ],
590            },
591            // Mode 2: Cormic index / trunk-to-leg proportion
592            SsdmShapeMode {
593                id: "trunk_to_limb_proportion".to_string(),
594                eigenvalue: 0.45,
595                feature_loadings: [
596                    0.00, 0.72, -0.68, -0.10, 0.04, 0.04, 0.02, 0.00, 0.00, -0.02, -0.02, 0.00,
597                    -0.08, 0.00,
598                ],
599                bone_loadings: vec![
600                    loading("thoracic_ribcage", [0.08, 0.58, 0.08]),
601                    loading("lumbar_spine", [0.06, 0.68, 0.06]),
602                    loading("pelvis", [0.05, 0.25, 0.05]),
603                    loading("femur_l", [0.02, -0.62, 0.02]),
604                    loading("femur_r", [0.02, -0.62, 0.02]),
605                    loading("tibia_l", [0.02, -0.65, 0.02]),
606                    loading("tibia_r", [0.02, -0.65, 0.02]),
607                ],
608            },
609            // Mode 3: Shoulder & thoracic frame breadth
610            SsdmShapeMode {
611                id: "shoulder_thoracic_frame".to_string(),
612                eigenvalue: 0.40,
613                feature_loadings: [
614                    0.05, 0.02, -0.02, 0.26, 0.78, 0.52, 0.14, 0.06, 0.08, 0.04, 0.02, 0.14,
615                    0.00, 0.00,
616                ],
617                bone_loadings: vec![
618                    loading("thoracic_ribcage", [0.74, 0.08, 0.52]),
619                    loading("humerus_l", [0.22, 0.14, 0.22]),
620                    loading("humerus_r", [0.22, 0.14, 0.22]),
621                    loading("radius_ulna_l", [0.16, 0.10, 0.16]),
622                    loading("radius_ulna_r", [0.16, 0.10, 0.16]),
623                ],
624            },
625            // Mode 4: Pelvic & hip width / gestational pelvic flare
626            SsdmShapeMode {
627                id: "pelvic_hip_dimorphism".to_string(),
628                eigenvalue: 0.35,
629                feature_loadings: [
630                    0.00, 0.02, -0.02, 0.00, -0.10, 0.08, 0.34, 0.80, 0.22, 0.32, 0.10, 0.04,
631                    0.04, 0.28,
632                ],
633                bone_loadings: vec![
634                    loading("pelvis", [0.76, 0.08, 0.58]),
635                    loading("lumbar_spine", [0.14, -0.04, 0.24]),
636                    loading("femur_l", [0.24, 0.00, 0.20]),
637                    loading("femur_r", [0.24, 0.00, 0.20]),
638                ],
639            },
640            // Mode 5: Soft-tissue / visceral-adipose & gestational abdominal expansion
641            SsdmShapeMode {
642                id: "adiposity_soft_tissue_mass".to_string(),
643                eigenvalue: 0.50,
644                feature_loadings: [
645                    -0.02, 0.00, 0.00, 0.00, 0.08, 0.34, 0.72, 0.38, 0.38, 0.20, 0.10, 0.12,
646                    0.06, 0.18,
647                ],
648                bone_loadings: vec![
649                    loading("thoracic_ribcage", [0.16, 0.00, 0.24]),
650                    loading("lumbar_spine", [0.06, 0.00, 0.12]),
651                    loading("pelvis", [0.12, 0.00, 0.18]),
652                ],
653            },
654            // Mode 6: Appendicular muscularity & diaphyseal robusticity
655            SsdmShapeMode {
656                id: "appendicular_muscularity".to_string(),
657                eigenvalue: 0.30,
658                feature_loadings: [
659                    0.02, 0.00, 0.00, 0.12, 0.20, 0.22, -0.10, 0.08, 0.32, 0.54, 0.48, 0.52,
660                    -0.04, 0.00,
661                ],
662                bone_loadings: vec![
663                    loading("femur_l", [0.28, 0.02, 0.28]),
664                    loading("femur_r", [0.28, 0.02, 0.28]),
665                    loading("tibia_l", [0.24, 0.02, 0.24]),
666                    loading("tibia_r", [0.24, 0.02, 0.24]),
667                    loading("humerus_l", [0.26, 0.02, 0.26]),
668                    loading("humerus_r", [0.26, 0.02, 0.26]),
669                    loading("radius_ulna_l", [0.22, 0.02, 0.22]),
670                    loading("radius_ulna_r", [0.22, 0.02, 0.22]),
671                ],
672            },
673        ];
674
675        let density_modes = vec![
676            SsdmDensityMode {
677                id: "age_senescent_bmd_trajectory".to_string(),
678                eigenvalue: 1.0,
679                age_loading: -0.85,
680                endocrine_loading: -0.35,
681                mass_loading: 0.10,
682                regional_bmd_loadings: vec![
683                    ("lumbar_spine".to_string(), 0.22),
684                    ("pelvis".to_string(), 0.20),
685                    ("femur_l".to_string(), 0.24),
686                    ("femur_r".to_string(), 0.24),
687                    ("tibia_l".to_string(), 0.18),
688                    ("tibia_r".to_string(), 0.18),
689                    ("thoracic_ribcage".to_string(), 0.16),
690                    ("humerus_l".to_string(), 0.15),
691                    ("humerus_r".to_string(), 0.15),
692                    ("radius_ulna_l".to_string(), 0.14),
693                    ("radius_ulna_r".to_string(), 0.14),
694                    ("cranium".to_string(), 0.08),
695                ],
696            },
697            SsdmDensityMode {
698                id: "mechanostat_loading_hypertrophy".to_string(),
699                eigenvalue: 0.5,
700                age_loading: -0.10,
701                endocrine_loading: 0.05,
702                mass_loading: 0.75,
703                regional_bmd_loadings: vec![
704                    ("femur_l".to_string(), 0.16),
705                    ("femur_r".to_string(), 0.16),
706                    ("tibia_l".to_string(), 0.15),
707                    ("tibia_r".to_string(), 0.15),
708                    ("lumbar_spine".to_string(), 0.12),
709                    ("pelvis".to_string(), 0.12),
710                ],
711            },
712            SsdmDensityMode {
713                id: "endocrine_calcium_mobilization".to_string(),
714                eigenvalue: 0.4,
715                age_loading: -0.15,
716                endocrine_loading: -0.80,
717                mass_loading: 0.05,
718                regional_bmd_loadings: vec![
719                    ("lumbar_spine".to_string(), 0.18),
720                    ("pelvis".to_string(), 0.16),
721                    ("femur_l".to_string(), 0.12),
722                    ("femur_r".to_string(), 0.12),
723                ],
724            },
725        ];
726
727        Self {
728            reference_model,
729            mean_stature_mm,
730            mean_mass_g,
731            regularization_lambda: 0.08,
732            shape_modes,
733            density_modes,
734        }
735    }
736}
737
738/// Non-uniform affine bone scaling tensor `S_b = diag(s_{b,x}, s_{b,y}, s_{b,z})`
739/// and compartmental bone mineral stiffness from Stage 1 SSDM projection.
740#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
741pub struct BoneScaleTensor {
742    pub bone_id: String,
743    /// Principal diagonal scale factors `[s_x, s_y, s_z]` (strictly positive).
744    pub diag_scale: [f64; 3],
745    /// Apparent wet bone density `rho_app` in g/cm^3.
746    pub apparent_density_g_cm3: f64,
747    /// Carter-Hayes / Morgan-Keaveny elastic modulus `E(rho_app)` in GPa.
748    pub elastic_modulus_gpa: f64,
749    /// Estimated cortical shell thickness in mm.
750    pub cortical_thickness_mm: f64,
751}
752
753impl BoneScaleTensor {
754    /// Materializes `S_b = diag(s_{b,x}, s_{b,y}, s_{b,z})` as a row-major `3x3` matrix.
755    pub fn matrix_3x3(&self) -> [[f64; 3]; 3] {
756        [
757            [self.diag_scale[0], 0.0, 0.0],
758            [0.0, self.diag_scale[1], 0.0],
759            [0.0, 0.0, self.diag_scale[2]],
760        ]
761    }
762}
763
764/// Weighted anthropometric or anatomical landmark observation for Stage 2 registration.
765#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
766pub struct CalibrationObservation {
767    /// Name of the measurement or landmark (e.g. `"waist_mm"`, `"femur_l_trochanter"`).
768    pub feature_id: String,
769    /// Optional target bone identifier for spatial Stage 2 registration.
770    #[serde(default, skip_serializing_if = "Option::is_none")]
771    pub region_bone_id: Option<String>,
772    /// Optional 3D target displacement vector (meters) in CCF coordinates.
773    #[serde(default, skip_serializing_if = "Option::is_none")]
774    pub target_displacement_m: Option<[f64; 3]>,
775    /// Instrument/epistemic confidence `c_0` in `[0.0, 1.0]`.
776    pub base_confidence: f64,
777    /// Elapsed days since phenomenon time (`>= 0.0`).
778    pub elapsed_days: f64,
779    /// Biological temporal half-life `t_{1/2}` in days (`> 0.0`).
780    pub half_life_days: f64,
781}
782
783impl CalibrationObservation {
784    /// Exponential temporal decay weight `w_k = c_obs(t) = c_0 * 2^(-dt / half_life)`.
785    pub fn decayed_confidence(&self) -> f64 {
786        let c0 = self.base_confidence.clamp(0.0, 1.0);
787        if !c0.is_finite() || !self.elapsed_days.is_finite() {
788            return 0.0;
789        }
790        let dt = self.elapsed_days.max(0.0);
791        let hl = if self.half_life_days.is_finite() && self.half_life_days > 0.0 {
792            self.half_life_days
793        } else {
794            365.0
795        };
796        (c0 * (-(dt / hl) * std::f64::consts::LN_2).exp()).clamp(0.0, 1.0)
797    }
798}
799
800/// Stage 2 per-bone locally affine stiffness-penalized correction `(A_b, t_b)`.
801#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
802pub struct BoneAffineCorrection {
803    pub bone_id: String,
804    /// Orientation-preserving locally affine matrix `A_b` (`det(A_b) > 0`).
805    pub linear_3x3: [[f64; 3]; 3],
806    /// Local translational correction `t_b` in meters.
807    pub translation_m: [f64; 3],
808    /// Determinant `det(A_b) > 0`.
809    pub jacobian_det: f64,
810    /// Bone mineral stiffness `E(rho_app)` in GPa governing stiffness regularization.
811    pub bone_stiffness_gpa: f64,
812    /// Aggregated observation confidence `w_k = c_obs(t)` driving this bone's correction.
813    pub observation_confidence: f64,
814}
815
816/// Stage 3 deformed internal organ / soft-tissue cavity point with Jacobian volume check.
817#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
818pub struct OrganCavityTransfer {
819    pub organ_id: String,
820    pub reference_point_m: [f64; 3],
821    pub calibrated_point_m: [f64; 3],
822    /// Local volume ratio `det(J) > 0` guaranteeing no self-intersection / foldover.
823    pub jacobian_det: f64,
824}
825
826/// Input bundle for [`derive_anatomical_calibration`].
827pub struct AnatomicalCalibrationInput<'a> {
828    pub constitution: &'a BodyConstitution,
829    pub physiological_state: Option<super::physiology::PhysiologicalState>,
830    pub observations: &'a [CalibrationObservation],
831    /// Optional internal organ/cavity query coordinates `(organ_id, xyz_m)`.
832    /// When empty, canonical thoracic/abdominal/pelvic cavity landmarks are evaluated.
833    pub organ_query_points: &'a [(&'a str, [f64; 3])],
834    /// Optional caller-supplied SSDM basis; defaults to [`SsdmBasis::canonical_human`].
835    pub basis: Option<&'a SsdmBasis>,
836}
837
838/// Full 3-stage calibration output preserving backward compatibility via `body_fit`.
839#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
840pub struct AnatomicalCalibrationResult {
841    pub reference_model: AnatomyModel,
842    pub shape_mode_weights: Vec<f64>,
843    pub density_mode_weights: Vec<f64>,
844    pub bone_scalings: Vec<BoneScaleTensor>,
845    pub bone_corrections: Vec<BoneAffineCorrection>,
846    pub control_cage: Vec<[f64; 3]>,
847    pub displaced_cage: Vec<[f64; 3]>,
848    pub organ_transfers: Vec<OrganCavityTransfer>,
849    pub body_fit: BodyFit,
850    pub is_identity: bool,
851}
852
853/// Canonical bone reference anchors `[x, y, z]` in meters (CCF up = `+y`, anterior = `+z`).
854const CANONICAL_BONES: &[(&str, [f64; 3], f64, f64)] = &[
855    // (bone_id, canonical_center_m, baseline_rho_app_g_cm3, baseline_cortical_mm)
856    ("cranium", [0.0, 1.68, 0.01], 1.82, 4.2),
857    ("thoracic_ribcage", [0.0, 1.28, 0.0], 1.48, 2.4),
858    ("lumbar_spine", [0.0, 1.02, -0.04], 1.18, 1.8),
859    ("pelvis", [0.0, 0.86, 0.0], 1.42, 2.8),
860    ("femur_l", [-0.10, 0.64, 0.0], 1.85, 5.2),
861    ("femur_r", [0.10, 0.64, 0.0], 1.85, 5.2),
862    ("tibia_l", [-0.09, 0.25, 0.0], 1.84, 4.6),
863    ("tibia_r", [0.09, 0.25, 0.0], 1.84, 4.6),
864    ("humerus_l", [-0.21, 1.24, 0.0], 1.78, 3.8),
865    ("humerus_r", [0.21, 1.24, 0.0], 1.78, 3.8),
866    ("radius_ulna_l", [-0.24, 0.96, 0.02], 1.76, 3.2),
867    ("radius_ulna_r", [0.24, 0.96, 0.02], 1.76, 3.2),
868];
869
870/// Canonical thoracic / abdominal / pelvic internal organ cavity query landmarks (meters).
871const CANONICAL_ORGAN_CAVITY_POINTS: &[(&str, [f64; 3])] = &[
872    ("heart", [0.03, 1.27, 0.04]),
873    ("lung_l", [-0.08, 1.30, 0.01]),
874    ("lung_r", [0.08, 1.30, 0.01]),
875    ("diaphragm", [0.0, 1.18, 0.02]),
876    ("liver", [0.07, 1.12, 0.03]),
877    ("stomach", [-0.05, 1.10, 0.04]),
878    ("pelvic_cavity", [0.0, 0.84, 0.02]),
879];
880
881fn bone_elastic_modulus_gpa(rho_app: f64) -> f64 {
882    // Carter & Hayes (1977) / Morgan-Keaveny power-law scaling normalized to cortical 1.85 g/cm^3 -> 16.5 GPa
883    let r = (rho_app / 1.85).clamp(0.15, 1.35);
884    16.5 * r.powf(2.2)
885}
886
887fn mat3_det_f64(m: &[[f64; 3]; 3]) -> f64 {
888    m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
889        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
890        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
891}
892
893/// Solve dense `n x n` linear system `A x = b` via Gaussian elimination with partial pivoting.
894fn solve_linear_system(n: usize, a_in: &[f64], b_in: &[f64]) -> Option<Vec<f64>> {
895    if n == 0 || a_in.len() != n * n || b_in.len() != n {
896        return None;
897    }
898    let mut a = a_in.to_vec();
899    let mut b = b_in.to_vec();
900    for col in 0..n {
901        let mut pivot = col;
902        let mut max_abs = a[col * n + col].abs();
903        for row in (col + 1)..n {
904            let v = a[row * n + col].abs();
905            if v > max_abs {
906                max_abs = v;
907                pivot = row;
908            }
909        }
910        if !max_abs.is_finite() || max_abs < 1e-13 {
911            return None;
912        }
913        if pivot != col {
914            for k in 0..n {
915                a.swap(col * n + k, pivot * n + k);
916            }
917            b.swap(col, pivot);
918        }
919        let diag = a[col * n + col];
920        for row in (col + 1)..n {
921            let factor = a[row * n + col] / diag;
922            a[row * n + col] = 0.0;
923            for k in (col + 1)..n {
924                a[row * n + k] -= factor * a[col * n + k];
925            }
926            b[row] -= factor * b[col];
927        }
928    }
929    let mut x = vec![0.0_f64; n];
930    for row in (0..n).rev() {
931        let mut sum = b[row];
932        for col in (row + 1)..n {
933            sum -= a[row * n + col] * x[col];
934        }
935        let diag = a[row * n + row];
936        if !diag.is_finite() || diag.abs() < 1e-13 {
937            return None;
938        }
939        x[row] = sum / diag;
940    }
941    Some(x)
942}
943
944/// Precomputed 3D biharmonic Thin-Plate Spline (TPS) / Harmonic volume transfer field.
945#[derive(Debug, Clone)]
946struct HarmonicTpsField {
947    centroid: [f64; 3],
948    scale: f64,
949    eps: f64,
950    norm_cage: Vec<[f64; 3]>,
951    weights: Vec<[f64; 3]>,
952    affine_linear: [[f64; 3]; 3],
953    affine_translation: [f64; 3],
954}
955
956impl HarmonicTpsField {
957    fn fit(control_cage: &[[f64; 3]], displaced_cage: &[[f64; 3]]) -> Option<Self> {
958        let n = control_cage.len();
959        if n == 0 || n != displaced_cage.len() {
960            return None;
961        }
962        if control_cage
963            .iter()
964            .chain(displaced_cage.iter())
965            .flatten()
966            .any(|v| !v.is_finite())
967        {
968            return None;
969        }
970
971        let mut centroid = [0.0_f64; 3];
972        for p in control_cage {
973            centroid[0] += p[0];
974            centroid[1] += p[1];
975            centroid[2] += p[2];
976        }
977        centroid[0] /= n as f64;
978        centroid[1] /= n as f64;
979        centroid[2] /= n as f64;
980
981        let mut max_r2 = 0.0_f64;
982        for p in control_cage {
983            let dx = p[0] - centroid[0];
984            let dy = p[1] - centroid[1];
985            let dz = p[2] - centroid[2];
986            max_r2 = max_r2.max(dx * dx + dy * dy + dz * dz);
987        }
988        let scale = max_r2.sqrt().max(1e-4);
989        let eps = 1e-3;
990        let norm_cage: Vec<[f64; 3]> = control_cage
991            .iter()
992            .map(|p| [
993                (p[0] - centroid[0]) / scale,
994                (p[1] - centroid[1]) / scale,
995                (p[2] - centroid[2]) / scale,
996            ])
997            .collect();
998        let norm_disp: Vec<[f64; 3]> = displaced_cage
999            .iter()
1000            .zip(control_cage.iter())
1001            .map(|(d, c)| [
1002                (d[0] - c[0]) / scale,
1003                (d[1] - c[1]) / scale,
1004                (d[2] - c[2]) / scale,
1005            ])
1006            .collect();
1007
1008        // Build orthonormal polynomial columns Q1 (N x r, r <= 4) from [1, x, y, z] via modified Gram-Schmidt
1009        let mut p_cols: Vec<Vec<f64>> = vec![vec![0.0; n]; 4];
1010        for (i, c) in norm_cage.iter().enumerate() {
1011            p_cols[0][i] = 1.0;
1012            p_cols[1][i] = c[0];
1013            p_cols[2][i] = c[1];
1014            p_cols[3][i] = c[2];
1015        }
1016
1017        let mut q_cols: Vec<Vec<f64>> = Vec::with_capacity(4);
1018        let mut q_orig_idx: Vec<usize> = Vec::with_capacity(4);
1019        let mut r_mat = vec![vec![0.0_f64; 4]; 4];
1020        for col_idx in 0..4 {
1021            let mut v = p_cols[col_idx].clone();
1022            for (q_idx, q) in q_cols.iter().enumerate() {
1023                let dot: f64 = v.iter().zip(q.iter()).map(|(a, b)| a * b).sum();
1024                r_mat[q_idx][col_idx] = dot;
1025                for (vi, qi) in v.iter_mut().zip(q.iter()) {
1026                    *vi -= dot * qi;
1027                }
1028            }
1029            let norm: f64 = v.iter().map(|x| x * x).sum::<f64>().sqrt();
1030            if norm > 1e-8 {
1031                let inv = 1.0 / norm;
1032                for vi in &mut v {
1033                    *vi *= inv;
1034                }
1035                r_mat[q_cols.len()][col_idx] = norm;
1036                q_orig_idx.push(col_idx);
1037                q_cols.push(v);
1038            }
1039        }
1040
1041        let r_rank = q_cols.len();
1042        let dim = n + r_rank;
1043        let mut sys = vec![0.0_f64; dim * dim];
1044        let lambda_k = 1e-6;
1045        for i in 0..n {
1046            for j in 0..n {
1047                let dx = norm_cage[i][0] - norm_cage[j][0];
1048                let dy = norm_cage[i][1] - norm_cage[j][1];
1049                let dz = norm_cage[i][2] - norm_cage[j][2];
1050                let r = (dx * dx + dy * dy + dz * dz + eps * eps).sqrt();
1051                // 3D biharmonic kernel U(r) = -r is conditionally positive-definite on ker(P^T)
1052                sys[i * dim + j] = -r + if i == j { lambda_k } else { 0.0 };
1053            }
1054            for k in 0..r_rank {
1055                let qik = q_cols[k][i];
1056                sys[i * dim + (n + k)] = qik;
1057                sys[(n + k) * dim + i] = qik;
1058            }
1059        }
1060
1061        let mut weights = vec![[0.0_f64; 3]; n];
1062        let mut affine_linear = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
1063        let mut affine_translation = [0.0_f64; 3];
1064
1065        for axis in 0..3 {
1066            let mut rhs = vec![0.0_f64; dim];
1067            for i in 0..n {
1068                rhs[i] = norm_disp[i][axis];
1069            }
1070            let sol = solve_linear_system(dim, &sys, &rhs)?;
1071            for i in 0..n {
1072                weights[i][axis] = sol[i];
1073            }
1074            // Recover affine coefficients in [1, x, y, z] from Q1 * sol[n..]
1075            let mut poly = [0.0_f64; 4];
1076            for k in (0..r_rank).rev() {
1077                let orig = q_orig_idx[k];
1078                let mut sum = sol[n + k];
1079                for j in (k + 1)..r_rank {
1080                    let orig_j = q_orig_idx[j];
1081                    sum -= r_mat[k][orig_j] * poly[orig_j];
1082                }
1083                poly[orig] = sum / r_mat[k][orig];
1084            }
1085            affine_translation[axis] = poly[0] * scale;
1086            affine_linear[axis][0] += poly[1];
1087            affine_linear[axis][1] += poly[2];
1088            affine_linear[axis][2] += poly[3];
1089        }
1090
1091        Some(Self {
1092            centroid,
1093            scale,
1094            eps,
1095            norm_cage,
1096            weights,
1097            affine_linear,
1098            affine_translation,
1099        })
1100    }
1101
1102    fn eval_raw(&self, query_point: [f64; 3]) -> ([f64; 3], [[f64; 3]; 3]) {
1103        let qn = [
1104            (query_point[0] - self.centroid[0]) / self.scale,
1105            (query_point[1] - self.centroid[1]) / self.scale,
1106            (query_point[2] - self.centroid[2]) / self.scale,
1107        ];
1108        let mut out = [0.0_f64; 3];
1109        let mut jac = self.affine_linear;
1110        for axis in 0..3 {
1111            out[axis] = self.centroid[axis]
1112                + self.affine_translation[axis]
1113                + self.scale
1114                    * (self.affine_linear[axis][0] * qn[0]
1115                        + self.affine_linear[axis][1] * qn[1]
1116                        + self.affine_linear[axis][2] * qn[2]);
1117        }
1118
1119        for (c, w) in self.norm_cage.iter().zip(self.weights.iter()) {
1120            let dx = qn[0] - c[0];
1121            let dy = qn[1] - c[1];
1122            let dz = qn[2] - c[2];
1123            let r = (dx * dx + dy * dy + dz * dz + self.eps * self.eps).sqrt();
1124            let u = -r;
1125            let inv_r = 1.0 / r;
1126            let grad = [-dx * inv_r, -dy * inv_r, -dz * inv_r];
1127            for axis in 0..3 {
1128                out[axis] += self.scale * w[axis] * u;
1129                for col in 0..3 {
1130                    jac[axis][col] += w[axis] * grad[col];
1131                }
1132            }
1133        }
1134        (out, jac)
1135    }
1136
1137    /// Evaluate deformed point and Jacobian determinant, enforcing `det(J) > 0`
1138    /// via homotopy damping toward an orientation-preserving baseline when needed.
1139    fn eval_volume_preserving(&self, query_point: [f64; 3]) -> ([f64; 3], f64) {
1140        let (pt, jac) = self.eval_raw(query_point);
1141        let det = mat3_det_f64(&jac);
1142        const MIN_DET: f64 = 1e-3;
1143        if det.is_finite() && det > MIN_DET {
1144            return (pt, det);
1145        }
1146
1147        // Choose an orientation-preserving baseline: affine base if det(A) > MIN_DET, else identity.
1148        let det_aff = mat3_det_f64(&self.affine_linear);
1149        let (base_pt, base_jac) = if det_aff.is_finite() && det_aff > MIN_DET {
1150            let qn = [
1151                (query_point[0] - self.centroid[0]) / self.scale,
1152                (query_point[1] - self.centroid[1]) / self.scale,
1153                (query_point[2] - self.centroid[2]) / self.scale,
1154            ];
1155            let mut bp = [0.0; 3];
1156            for axis in 0..3 {
1157                bp[axis] = self.centroid[axis]
1158                    + self.affine_translation[axis]
1159                    + self.scale
1160                        * (self.affine_linear[axis][0] * qn[0]
1161                            + self.affine_linear[axis][1] * qn[1]
1162                            + self.affine_linear[axis][2] * qn[2]);
1163            }
1164            (bp, self.affine_linear)
1165        } else {
1166            (
1167                query_point,
1168                [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
1169            )
1170        };
1171
1172        let mut lo = 0.0_f64;
1173        let mut hi = 1.0_f64;
1174        for _ in 0..24 {
1175            let mid = 0.5 * (lo + hi);
1176            let mut j_mid = [[0.0_f64; 3]; 3];
1177            for r in 0..3 {
1178                for c in 0..3 {
1179                    j_mid[r][c] = (1.0 - mid) * base_jac[r][c] + mid * jac[r][c];
1180                }
1181            }
1182            if mat3_det_f64(&j_mid) > MIN_DET {
1183                lo = mid;
1184            } else {
1185                hi = mid;
1186            }
1187        }
1188
1189        let mut j_safe = [[0.0_f64; 3]; 3];
1190        for r in 0..3 {
1191            for c in 0..3 {
1192                j_safe[r][c] = (1.0 - lo) * base_jac[r][c] + lo * jac[r][c];
1193            }
1194        }
1195        let safe_pt = [
1196            (1.0 - lo) * base_pt[0] + lo * pt[0],
1197            (1.0 - lo) * base_pt[1] + lo * pt[1],
1198            (1.0 - lo) * base_pt[2] + lo * pt[2],
1199        ];
1200        (safe_pt, mat3_det_f64(&j_safe).max(MIN_DET))
1201    }
1202}
1203
1204/// Stage 3: Harmonic / 3D biharmonic Thin-Plate Spline soft-tissue & organ-cavity transfer.
1205///
1206/// Maps `query_point` smoothly from `control_cage` to `displaced_cage` and returns
1207/// `(deformed_point, det_jacobian)` with guaranteed `det(J) > 0` so thoracic/abdominal
1208/// organ cavities never invert or self-intersect.
1209pub fn harmonic_tps_organ_transfer(
1210    control_cage: &[[f64; 3]],
1211    displaced_cage: &[[f64; 3]],
1212    query_point: [f64; 3],
1213) -> ([f64; 3], f64) {
1214    if query_point.iter().any(|v| !v.is_finite()) {
1215        return (query_point, 1.0);
1216    }
1217    match HarmonicTpsField::fit(control_cage, displaced_cage) {
1218        Some(field) => field.eval_volume_preserving(query_point),
1219        None => (query_point, 1.0),
1220    }
1221}
1222
1223/// Extract observed standardized anthropometric/ontogenetic/endocrine features and their
1224/// observation confidence weights `(feature_index, standardized_delta, weight)`.
1225fn extract_ssdm_observations(
1226    constitution: &BodyConstitution,
1227    physiological_state: Option<super::physiology::PhysiologicalState>,
1228    observations: &[CalibrationObservation],
1229    basis: &SsdmBasis,
1230) -> (Vec<(usize, f64, f64)>, f64, f64, f64) {
1231    let m = &constitution.measurements;
1232    let girth = constitution.reference_girths_mm();
1233    let model = constitution
1234        .characteristics
1235        .anatomy_model()
1236        .unwrap_or(basis.reference_model);
1237    let (ref_thigh, ref_calf, ref_biceps) = match model {
1238        AnatomyModel::Male => (REF_THIGH_MALE_MM, REF_CALF_MALE_MM, REF_BICEPS_MALE_MM),
1239        AnatomyModel::Female => (
1240            REF_THIGH_FEMALE_MM,
1241            REF_CALF_FEMALE_MM,
1242            REF_BICEPS_FEMALE_MM,
1243        ),
1244    };
1245
1246    let obs_weight = |key: &str| -> f64 {
1247        let mut best = 0.0_f64;
1248        for o in observations {
1249            if o.feature_id == key {
1250                best = best.max(o.decayed_confidence());
1251            }
1252        }
1253        if best > 0.0 { best } else { 1.0 }
1254    };
1255
1256    let mut feats: Vec<(usize, f64, f64)> = Vec::new();
1257    let stature_mm = m.stature_mm.map(|v| v as f64);
1258    if let Some(h) = stature_mm {
1259        feats.push((0, (h / basis.mean_stature_mm) - 1.0, obs_weight("stature_mm")));
1260    }
1261    let eff_stature = stature_mm.unwrap_or(basis.mean_stature_mm);
1262    if let Some(sit) = m.sitting_height_mm {
1263        let delta = (sit as f64 / eff_stature) - REF_SITTING_RATIO as f64;
1264        feats.push((1, delta / REF_SITTING_RATIO as f64, obs_weight("sitting_height_mm")));
1265    }
1266    if let Some(ins) = m.inseam_mm {
1267        let delta = (ins as f64 / eff_stature) - REF_INSEAM_RATIO as f64;
1268        feats.push((2, delta / REF_INSEAM_RATIO as f64, obs_weight("inseam_mm")));
1269    }
1270    if let Some(span) = m.arm_span_mm {
1271        feats.push((3, (span as f64 / eff_stature) - 1.0, obs_weight("arm_span_mm")));
1272    }
1273    if let Some(sh) = m.shoulder_width_mm {
1274        feats.push((
1275            4,
1276            (sh as f64 / girth.shoulder_width_mm as f64) - 1.0,
1277            obs_weight("shoulder_width_mm"),
1278        ));
1279    }
1280    if let Some(ch) = m.chest_mm {
1281        feats.push((
1282            5,
1283            (ch as f64 / girth.chest_mm as f64) - 1.0,
1284            obs_weight("chest_mm"),
1285        ));
1286    }
1287    if let Some(wa) = m.waist_mm.or(m.abdomen_mm) {
1288        feats.push((
1289            6,
1290            (wa as f64 / girth.waist_mm as f64) - 1.0,
1291            obs_weight("waist_mm"),
1292        ));
1293    }
1294    if let Some(hp) = m.hip_mm {
1295        feats.push((
1296            7,
1297            (hp as f64 / girth.hip_mm as f64) - 1.0,
1298            obs_weight("hip_mm"),
1299        ));
1300    }
1301    let mut mass_z = 0.0_f64;
1302    if let Some(wt) = m.weight_g {
1303        let h_ratio = eff_stature / basis.mean_stature_mm;
1304        let expected_mass = basis.mean_mass_g * h_ratio * h_ratio;
1305        mass_z = ((wt as f64 / expected_mass).max(0.25)).ln();
1306        feats.push((8, mass_z, obs_weight("weight_g")));
1307    }
1308    if let Some(th) = m.thigh_mm.or(m.mid_thigh_mm) {
1309        feats.push((9, (th as f64 / ref_thigh) - 1.0, obs_weight("thigh_mm")));
1310    }
1311    if let Some(cf) = m.calf_mm {
1312        feats.push((10, (cf as f64 / ref_calf) - 1.0, obs_weight("calf_mm")));
1313    }
1314    if let Some(bc) = m.biceps_mm {
1315        feats.push((11, (bc as f64 / ref_biceps) - 1.0, obs_weight("biceps_mm")));
1316    }
1317
1318    // Age maturation & senescent remodeling index (centered around young-adult peak 30y = 360m)
1319    let age_z = if let Some(months) = constitution.characteristics.age_months {
1320        let years = months as f64 / 12.0;
1321        let z = if years < 20.0 {
1322            -(20.0 - years) / 20.0
1323        } else if years <= 35.0 {
1324            0.0
1325        } else {
1326            ((years - 35.0) / 50.0).min(1.2)
1327        };
1328        feats.push((12, z, 0.6));
1329        z
1330    } else {
1331        0.0
1332    };
1333
1334    // Sex/endocrine continuum state
1335    use super::physiology::{PhysiologicalState, ReproductiveState};
1336    let endocrine_z = match physiological_state {
1337        Some(PhysiologicalState::Reproductive(ReproductiveState::Pregnant(t))) => match t {
1338            Trimester::First => 0.25,
1339            Trimester::Second => 0.60,
1340            Trimester::Third => 1.00,
1341        },
1342        Some(PhysiologicalState::Reproductive(ReproductiveState::Lactating)) => 0.35,
1343        Some(PhysiologicalState::Reproductive(ReproductiveState::Perimenopause)) => 0.45,
1344        Some(PhysiologicalState::Reproductive(ReproductiveState::PostMenopause)) => 0.85,
1345        _ => match constitution.attributes.pregnancy {
1346            Some(Trimester::First) => 0.25,
1347            Some(Trimester::Second) => 0.60,
1348            Some(Trimester::Third) => 1.00,
1349            None => 0.0,
1350        },
1351    };
1352    if endocrine_z > 0.0 {
1353        feats.push((13, endocrine_z, 0.85));
1354    }
1355
1356    (feats, age_z, endocrine_z, mass_z)
1357}
1358
1359/// Derive the full 3-stage anatomical, densitometric, and organ-cavity calibration.
1360///
1361/// Preserves full backward compatibility via `result.body_fit` while adding:
1362/// - **Stage 1:** Weighted ridge-regularized SSDM subspace projection -> `(b, c)` and
1363///   non-uniform bone scaling tensors `S_b = diag(s_{b,x}, s_{b,y}, s_{b,z})`.
1364/// - **Stage 2:** Locally affine stiffness-penalized per-bone registration weighted by
1365///   observation confidence `w_k = c_obs(t)` and bone mineral stiffness `E(rho_app)`.
1366/// - **Stage 3:** 3D biharmonic TPS / Harmonic soft-tissue & organ-cavity transfer with
1367///   guaranteed `det(J) > 0`.
1368pub fn derive_anatomical_calibration(
1369    input: &AnatomicalCalibrationInput<'_>,
1370) -> AnatomicalCalibrationResult {
1371    let model = input
1372        .constitution
1373        .characteristics
1374        .anatomy_model()
1375        .unwrap_or(AnatomyModel::Male);
1376    let owned_basis;
1377    let basis = match input.basis {
1378        Some(b) => b,
1379        None => {
1380            owned_basis = SsdmBasis::canonical_human(model);
1381            &owned_basis
1382        }
1383    };
1384
1385    let pregnancy_override = match input.physiological_state {
1386        Some(super::physiology::PhysiologicalState::Reproductive(
1387            super::physiology::ReproductiveState::Pregnant(t),
1388        )) => Some(t),
1389        _ => input.constitution.attributes.pregnancy,
1390    };
1391    let body_fit = input.constitution.fit_with_pregnancy(pregnancy_override);
1392
1393    let (feats, age_z, endocrine_z, mass_z) = extract_ssdm_observations(
1394        input.constitution,
1395        input.physiological_state,
1396        input.observations,
1397        basis,
1398    );
1399
1400    // Stage 1A: Solve regularized weighted least squares (Phi^T W Phi + Lambda) b = Phi^T W f
1401    let m_modes = basis.shape_modes.len();
1402    let mut shape_weights = vec![0.0_f64; m_modes];
1403    if !feats.is_empty() && m_modes > 0 {
1404        let mut h = vec![0.0_f64; m_modes * m_modes];
1405        let mut rhs = vec![0.0_f64; m_modes];
1406        for i in 0..m_modes {
1407            let eig = basis.shape_modes[i].eigenvalue.max(1e-4);
1408            h[i * m_modes + i] = basis.regularization_lambda / eig;
1409        }
1410        for &(feat_idx, delta, w) in &feats {
1411            for i in 0..m_modes {
1412                let phi_i = basis.shape_modes[i].feature_loadings[feat_idx];
1413                rhs[i] += w * phi_i * delta;
1414                for j in 0..m_modes {
1415                    let phi_j = basis.shape_modes[j].feature_loadings[feat_idx];
1416                    h[i * m_modes + j] += w * phi_i * phi_j;
1417                }
1418            }
1419        }
1420        if let Some(sol) = solve_linear_system(m_modes, &h, &rhs) {
1421            shape_weights = sol;
1422        }
1423    }
1424
1425    // Stage 1B: Density mode projection (c)
1426    let k_modes = basis.density_modes.len();
1427    let mut density_weights = vec![0.0_f64; k_modes];
1428    for (k, dm) in basis.density_modes.iter().enumerate() {
1429        let raw = dm.age_loading * age_z.max(0.0)
1430            + dm.endocrine_loading * endocrine_z
1431            + dm.mass_loading * mass_z;
1432        density_weights[k] = (raw / (1.0 + basis.regularization_lambda / dm.eigenvalue.max(1e-4)))
1433            .clamp(-2.5, 2.5);
1434    }
1435
1436    // Stage 1C: Compute non-uniform bone scaling tensors S_b = diag(s_x, s_y, s_z) and E(rho_app)
1437    let mut bone_scalings = Vec::with_capacity(CANONICAL_BONES.len());
1438    for &(bone_id, _center, base_rho, base_cort_mm) in CANONICAL_BONES {
1439        let mut log_s = [0.0_f64; 3];
1440        for (i, sm) in basis.shape_modes.iter().enumerate() {
1441            let b_i = shape_weights[i];
1442            if let Some(bl) = sm.bone_loadings.iter().find(|bl| bl.bone_id == bone_id) {
1443                log_s[0] += b_i * bl.axis_loadings[0];
1444                log_s[1] += b_i * bl.axis_loadings[1];
1445                log_s[2] += b_i * bl.axis_loadings[2];
1446            }
1447        }
1448        let diag_scale = [
1449            log_s[0].exp().clamp(0.35, 2.5),
1450            log_s[1].exp().clamp(0.35, 2.5),
1451            log_s[2].exp().clamp(0.35, 2.5),
1452        ];
1453
1454        let mut delta_rho = 0.0_f64;
1455        for (k, dm) in basis.density_modes.iter().enumerate() {
1456            if let Some((_, loading)) = dm.regional_bmd_loadings.iter().find(|(id, _)| id == bone_id) {
1457                delta_rho += density_weights[k] * *loading;
1458            }
1459        }
1460
1461        // Dominant side upper-limb cortical hypertrophy (+8% cortical thickness, +4% BMD)
1462        let dom_mult = match input.constitution.characteristics.dominant_side {
1463            Some(DominantSide::Left)
1464                if bone_id.ends_with("_l") && (bone_id.starts_with("humerus") || bone_id.starts_with("radius")) =>
1465            {
1466                1.04
1467            }
1468            Some(DominantSide::Right)
1469                if bone_id.ends_with("_r") && (bone_id.starts_with("humerus") || bone_id.starts_with("radius")) =>
1470            {
1471                1.04
1472            }
1473            _ => 1.0,
1474        };
1475
1476        let rho_app = ((base_rho + delta_rho) * dom_mult).clamp(0.30, 2.25);
1477        let cort_mm = (base_cort_mm * (rho_app / base_rho) * dom_mult).clamp(0.4, 12.0);
1478        let e_gpa = bone_elastic_modulus_gpa(rho_app);
1479
1480        bone_scalings.push(BoneScaleTensor {
1481            bone_id: bone_id.to_string(),
1482            diag_scale,
1483            apparent_density_g_cm3: rho_app,
1484            elastic_modulus_gpa: e_gpa,
1485            cortical_thickness_mm: cort_mm,
1486        });
1487    }
1488
1489    // Stage 2: Locally affine stiffness-penalized per-bone registration
1490    // Relaxin modifier during pregnancy increases pelvic/lumbar compliance slightly.
1491    let pelvic_relaxin_factor = if pregnancy_override.is_some() { 0.72 } else { 1.0 };
1492
1493    let mut bone_corrections = Vec::with_capacity(CANONICAL_BONES.len());
1494    let mut control_cage = Vec::with_capacity(CANONICAL_BONES.len());
1495    let mut displaced_cage = Vec::with_capacity(CANONICAL_BONES.len());
1496
1497    // Global vertical anchor (feet at y=0): accumulate scaled vertical centers cleanly
1498    let global_y_scale = bone_scalings
1499        .iter()
1500        .find(|b| b.bone_id == "femur_l")
1501        .map(|b| b.diag_scale[1])
1502        .unwrap_or(1.0);
1503    let trunk_x_scale = bone_scalings
1504        .iter()
1505        .find(|b| b.bone_id == "thoracic_ribcage")
1506        .map(|b| b.diag_scale[0])
1507        .unwrap_or(1.0);
1508
1509    for (idx, &(bone_id, ref_center, _base_rho, _)) in CANONICAL_BONES.iter().enumerate() {
1510        let sb = &bone_scalings[idx];
1511        let mut linear = sb.matrix_3x3();
1512        let mut trans = [
1513            ref_center[0] * (trunk_x_scale - 1.0) * 0.45,
1514            ref_center[1] * (0.5 * (global_y_scale + sb.diag_scale[1]) - 1.0),
1515            0.0,
1516        ];
1517
1518        // Pregnancy abdominal/pelvic anterior shift
1519        if body_fit.pregnancy_abdomen > 0.0 && (bone_id == "pelvis" || bone_id == "lumbar_spine") {
1520            trans[2] += body_fit.pregnancy_abdomen as f64 * 0.045;
1521        }
1522
1523        let eff_stiffness = sb.elastic_modulus_gpa
1524            * if bone_id == "pelvis" || bone_id == "lumbar_spine" {
1525                pelvic_relaxin_factor
1526            } else {
1527                1.0
1528            };
1529
1530        let mut total_conf = 0.0_f64;
1531        let mut weighted_disp = [0.0_f64; 3];
1532        for obs in input.observations {
1533            let matches_bone = obs
1534                .region_bone_id
1535                .as_deref()
1536                .is_some_and(|b| b == bone_id)
1537                || obs.feature_id == bone_id;
1538            if matches_bone {
1539                let w = obs.decayed_confidence();
1540                if w > 0.0 {
1541                    total_conf += w;
1542                    if let Some(d) = obs.target_displacement_m {
1543                        weighted_disp[0] += w * d[0];
1544                        weighted_disp[1] += w * d[1];
1545                        weighted_disp[2] += w * d[2];
1546                    }
1547                }
1548            }
1549        }
1550
1551        if total_conf > 0.0 {
1552            // Stiffness-penalized update: d_applied = (w / (w + alpha * E / E_ref)) * d_obs
1553            // Higher cortical BMD E(rho_app) resists non-physiological local distortion.
1554            let alpha_stiff = 0.25 * (eff_stiffness / 15.0);
1555            let gain = total_conf / (total_conf + alpha_stiff);
1556            let avg_d = [
1557                weighted_disp[0] / total_conf,
1558                weighted_disp[1] / total_conf,
1559                weighted_disp[2] / total_conf,
1560            ];
1561            trans[0] += gain * avg_d[0];
1562            trans[1] += gain * avg_d[1];
1563            trans[2] += gain * avg_d[2];
1564
1565            // Gentle stiffness-penalized anisotropic shear/scale accommodation
1566            let local_strain = (gain * 0.15).min(0.25);
1567            for axis in 0..3 {
1568                let s_adj = (1.0 + local_strain * avg_d[axis].clamp(-1.0, 1.0)).clamp(0.75, 1.35);
1569                linear[axis][axis] *= s_adj;
1570            }
1571        }
1572
1573        let det = mat3_det_f64(&linear).max(1e-6);
1574        let displaced_center = [
1575            ref_center[0] * linear[0][0]
1576                + ref_center[1] * linear[0][1]
1577                + ref_center[2] * linear[0][2]
1578                + trans[0],
1579            ref_center[0] * linear[1][0]
1580                + ref_center[1] * linear[1][1]
1581                + ref_center[2] * linear[1][2]
1582                + trans[1],
1583            ref_center[0] * linear[2][0]
1584                + ref_center[1] * linear[2][1]
1585                + ref_center[2] * linear[2][2]
1586                + trans[2],
1587        ];
1588
1589        control_cage.push(ref_center);
1590        displaced_cage.push(displaced_center);
1591        bone_corrections.push(BoneAffineCorrection {
1592            bone_id: bone_id.to_string(),
1593            linear_3x3: linear,
1594            translation_m: trans,
1595            jacobian_det: det,
1596            bone_stiffness_gpa: eff_stiffness,
1597            observation_confidence: total_conf,
1598        });
1599    }
1600
1601    // Stage 3: Harmonic / TPS Soft-Tissue & Organ Cavity Co-Calibration
1602    let tps_field = HarmonicTpsField::fit(&control_cage, &displaced_cage);
1603    let queries: Vec<(&str, [f64; 3])> = if input.organ_query_points.is_empty() {
1604        CANONICAL_ORGAN_CAVITY_POINTS.to_vec()
1605    } else {
1606        input.organ_query_points.to_vec()
1607    };
1608
1609    let mut organ_transfers = Vec::with_capacity(queries.len());
1610    for &(organ_id, qpt) in &queries {
1611        let (cal_pt, j_det) = match &tps_field {
1612            Some(f) if !qpt.iter().any(|v| !v.is_finite()) => f.eval_volume_preserving(qpt),
1613            _ => (qpt, 1.0),
1614        };
1615        organ_transfers.push(OrganCavityTransfer {
1616            organ_id: organ_id.to_string(),
1617            reference_point_m: qpt,
1618            calibrated_point_m: cal_pt,
1619            jacobian_det: j_det,
1620        });
1621    }
1622
1623    let is_identity = body_fit.identity
1624        && input.observations.is_empty()
1625        && shape_weights.iter().all(|w| w.abs() < 1e-9);
1626
1627    AnatomicalCalibrationResult {
1628        reference_model: model,
1629        shape_mode_weights: shape_weights,
1630        density_mode_weights: density_weights,
1631        bone_scalings,
1632        bone_corrections,
1633        control_cage,
1634        displaced_cage,
1635        organ_transfers,
1636        body_fit,
1637        is_identity,
1638    }
1639}
1640
1641impl BodyConstitution {
1642    /// Run the 3-stage SSDM + Stiffness-Penalized Registration + Harmonic/TPS calibration pipeline.
1643    pub fn derive_anatomical_calibration(
1644        &self,
1645        physiological_state: Option<super::physiology::PhysiologicalState>,
1646        observations: &[CalibrationObservation],
1647    ) -> AnatomicalCalibrationResult {
1648        derive_anatomical_calibration(&AnatomicalCalibrationInput {
1649            constitution: self,
1650            physiological_state,
1651            observations,
1652            organ_query_points: &[],
1653            basis: None,
1654        })
1655    }
1656}
1657
1658fn lerp(a: f32, b: f32, t: f32) -> f32 {
1659    a + (b - a) * t.clamp(0.0, 1.0)
1660}
1661
1662fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
1663    let t = ((x - edge0) / (edge1 - edge0).max(1e-6)).clamp(0.0, 1.0);
1664    t * t * (3.0 - 2.0 * t)
1665}
1666
1667fn bump(x: f32, center: f32, width: f32) -> f32 {
1668    let t = ((x - center) / width).abs();
1669    if t >= 1.0 { 0.0 } else { 1.0 - t * t }
1670}
1671
1672#[cfg(test)]
1673mod tests {
1674    use super::*;
1675
1676    #[test]
1677    fn empty_constitution_is_identity_fit() {
1678        let fit = BodyConstitution::default().fit();
1679        assert!(fit.identity);
1680        assert!((fit.stature_scale - 1.0).abs() < f32::EPSILON);
1681        assert!(fit.hidden_keys.is_empty());
1682    }
1683
1684    #[test]
1685    fn taller_person_scales_up() {
1686        let mut c = BodyConstitution::default();
1687        c.measurements.stature_mm = Some(2000);
1688        let fit = c.fit();
1689        assert!(!fit.identity);
1690        assert!((fit.stature_scale - 2000.0 / 1800.0).abs() < 1e-4);
1691        let p = fit.transform_point([0.0, 1.8, 0.0], [0.0, 0.0, 0.0], [0.4, 1.8, 0.3]);
1692        assert!(p[1] > 1.8, "crown should rise with stature, got {}", p[1]);
1693    }
1694
1695    #[test]
1696    fn xx_uses_female_reference_stature() {
1697        let mut c = BodyConstitution::default();
1698        c.characteristics.karyotype = Some(Karyotype::Xx);
1699        c.measurements.stature_mm = Some(VH_FEMALE_STATURE_MM);
1700        let fit = c.fit();
1701        assert!(
1702            (fit.stature_scale - 1.0).abs() < 1e-4,
1703            "matching the female reference is identity scale"
1704        );
1705    }
1706
1707    #[test]
1708    fn sitting_height_stretches_torso_not_legs() {
1709        let mut c = BodyConstitution::default();
1710        c.measurements.stature_mm = Some(1800);
1711        c.measurements.sitting_height_mm = Some(1100); // longer torso than 0.52*1800=936
1712        let fit = c.fit();
1713        assert!(fit.torso_scale_y > 1.05);
1714        assert!(fit.leg_scale_y < 1.0);
1715    }
1716
1717    #[test]
1718    fn absent_uterus_hides_uterus_key() {
1719        let mut c = BodyConstitution::default();
1720        c.attributes.absent.push(AbsentPart {
1721            key: "3d-vh-f-uterus.glb".into(),
1722            reason: AbsenceReason::Surgical,
1723        });
1724        let fit = c.fit();
1725        assert!(fit.hides("uterus"));
1726        assert!(fit.hides("3d-vh-f-uterus.glb"));
1727        assert!(!fit.hides("heart"));
1728    }
1729
1730    #[test]
1731    fn third_trimester_adds_abdomen_bulge() {
1732        let mut c = BodyConstitution::default();
1733        c.attributes.pregnancy = Some(Trimester::Third);
1734        let fit = c.fit();
1735        assert!(fit.pregnancy_abdomen > 0.3);
1736        let mid = fit.transform_point([0.0, 0.95, 0.0], [0.0, 0.0, 0.0], [0.4, 1.8, 0.3]);
1737        let crown = fit.transform_point([0.0, 1.8, 0.0], [0.0, 0.0, 0.0], [0.4, 1.8, 0.3]);
1738        assert!(
1739            mid[2] > crown[2],
1740            "abdomen should come forward more than the crown"
1741        );
1742    }
1743
1744    #[test]
1745    fn validate_rejects_impossible_sitting_height() {
1746        let mut c = BodyConstitution::default();
1747        c.measurements.stature_mm = Some(1600);
1748        c.measurements.sitting_height_mm = Some(1600);
1749        assert!(c.validate().is_err());
1750    }
1751
1752    #[test]
1753    fn validate_rejects_out_of_range_stature() {
1754        let mut c = BodyConstitution::default();
1755        c.measurements.stature_mm = Some(80);
1756        assert!(c.validate().is_err());
1757    }
1758
1759    #[test]
1760    fn age_without_height_does_not_invent_stature() {
1761        let mut c = BodyConstitution::default();
1762        c.characteristics.age_months = Some(48);
1763        let fit = c.fit();
1764        assert!((fit.stature_scale - 1.0).abs() < f32::EPSILON);
1765        assert!(
1766            fit.honesty_notes
1767                .iter()
1768                .any(|n| n.contains("not guessed from age"))
1769        );
1770    }
1771
1772    #[test]
1773    fn round_trip_json() {
1774        let mut c = BodyConstitution::default();
1775        c.measurements.stature_mm = Some(1720);
1776        c.measurements.waist_mm = Some(820);
1777        c.characteristics.karyotype = Some(Karyotype::Xx);
1778        c.attributes.absent.push(AbsentPart {
1779            key: "uterus".into(),
1780            reason: AbsenceReason::Surgical,
1781        });
1782        let s = serde_json::to_string(&c).unwrap();
1783        let back: BodyConstitution = serde_json::from_str(&s).unwrap();
1784        assert_eq!(c, back);
1785    }
1786
1787    #[test]
1788    fn garment_and_helmet_measures_do_not_change_fit() {
1789        let mut clothed = BodyConstitution::default();
1790        clothed.measurements.sleeve_mm = Some(620);
1791        clothed.measurements.neck_mm = Some(390);
1792        clothed.measurements.head_mm = Some(570);
1793        clothed.measurements.foot_left_mm = Some(265);
1794        clothed.measurements.foot_right_mm = Some(268);
1795        clothed.measurements.ring_finger_circ_mm = Some(55);
1796        let empty = BodyConstitution::default().fit();
1797        let fit = clothed.fit();
1798        assert!(fit.identity);
1799        assert_eq!(fit.stature_scale, empty.stature_scale);
1800        assert_eq!(fit.chest_radial, empty.chest_radial);
1801        assert!(
1802            fit.honesty_notes
1803                .iter()
1804                .any(|n| n.contains("Garment, footwear, helmet"))
1805        );
1806    }
1807
1808    #[test]
1809    fn stage1_ssdm_projection_produces_non_uniform_bone_scalings_and_bmd() {
1810        use super::super::physiology::{PhysiologicalState, ReproductiveState};
1811
1812        let mut young = BodyConstitution::default();
1813        young.characteristics.karyotype = Some(Karyotype::Xx);
1814        young.characteristics.age_months = Some(30 * 12);
1815        young.characteristics.dominant_side = Some(DominantSide::Right);
1816        young.measurements.stature_mm = Some(1760);
1817        young.measurements.sitting_height_mm = Some(930);
1818        young.measurements.waist_mm = Some(740);
1819        young.measurements.hip_mm = Some(1020);
1820        young.measurements.weight_g = Some(68_000);
1821
1822        let cal_young = young.derive_anatomical_calibration(None, &[]);
1823        assert!(!cal_young.is_identity);
1824        assert_eq!(cal_young.reference_model, AnatomyModel::Female);
1825        assert!(cal_young.body_fit.stature_scale > 1.0);
1826
1827        let femur_r = cal_young
1828            .bone_scalings
1829            .iter()
1830            .find(|b| b.bone_id == "femur_r")
1831            .unwrap();
1832        // Non-uniform scaling: longitudinal y differs from transverse x/z
1833        assert!(
1834            (femur_r.diag_scale[1] - femur_r.diag_scale[0]).abs() > 1e-3,
1835            "expected non-uniform S_b: {:?}",
1836            femur_r.diag_scale
1837        );
1838        assert!(femur_r.diag_scale.iter().all(|&s| s > 0.35 && s < 2.5));
1839
1840        // Dominant right humerus has higher BMD & cortical thickness than left
1841        let hum_r = cal_young
1842            .bone_scalings
1843            .iter()
1844            .find(|b| b.bone_id == "humerus_r")
1845            .unwrap();
1846        let hum_l = cal_young
1847            .bone_scalings
1848            .iter()
1849            .find(|b| b.bone_id == "humerus_l")
1850            .unwrap();
1851        assert!(hum_r.apparent_density_g_cm3 > hum_l.apparent_density_g_cm3);
1852        assert!(hum_r.cortical_thickness_mm > hum_l.cortical_thickness_mm);
1853
1854        // Older + postmenopausal state lowers lumbar BMD & elastic modulus E(rho_app)
1855        let mut older = young.clone();
1856        older.characteristics.age_months = Some(75 * 12);
1857        let cal_older = older.derive_anatomical_calibration(
1858            Some(PhysiologicalState::Reproductive(
1859                ReproductiveState::PostMenopause,
1860            )),
1861            &[],
1862        );
1863        let lumbar_young = cal_young
1864            .bone_scalings
1865            .iter()
1866            .find(|b| b.bone_id == "lumbar_spine")
1867            .unwrap();
1868        let lumbar_older = cal_older
1869            .bone_scalings
1870            .iter()
1871            .find(|b| b.bone_id == "lumbar_spine")
1872            .unwrap();
1873        assert!(lumbar_older.apparent_density_g_cm3 < lumbar_young.apparent_density_g_cm3);
1874        assert!(lumbar_older.elastic_modulus_gpa < lumbar_young.elastic_modulus_gpa);
1875    }
1876
1877    #[test]
1878    fn stage2_stiffness_penalized_registration_weights_confidence_and_bmd() {
1879        let mut young = BodyConstitution::default();
1880        young.characteristics.age_months = Some(28 * 12);
1881        young.measurements.stature_mm = Some(1800);
1882
1883        let mut older = young.clone();
1884        older.characteristics.age_months = Some(80 * 12);
1885
1886        let obs_fresh = [CalibrationObservation {
1887            feature_id: "lumbar_spine".into(),
1888            region_bone_id: Some("lumbar_spine".into()),
1889            target_displacement_m: Some([0.0, 0.0, 0.08]),
1890            base_confidence: 0.95,
1891            elapsed_days: 1.0,
1892            half_life_days: 180.0,
1893        }];
1894        let obs_stale = [CalibrationObservation {
1895            feature_id: "lumbar_spine".into(),
1896            region_bone_id: Some("lumbar_spine".into()),
1897            target_displacement_m: Some([0.0, 0.0, 0.08]),
1898            base_confidence: 0.95,
1899            elapsed_days: 3650.0,
1900            half_life_days: 180.0,
1901        }];
1902
1903        let res_young_fresh = young.derive_anatomical_calibration(None, &obs_fresh);
1904        let res_older_fresh = older.derive_anatomical_calibration(None, &obs_fresh);
1905        let res_young_stale = young.derive_anatomical_calibration(None, &obs_stale);
1906
1907        let c_yf = res_young_fresh
1908            .bone_corrections
1909            .iter()
1910            .find(|b| b.bone_id == "lumbar_spine")
1911            .unwrap();
1912        let c_of = res_older_fresh
1913            .bone_corrections
1914            .iter()
1915            .find(|b| b.bone_id == "lumbar_spine")
1916            .unwrap();
1917        let c_ys = res_young_stale
1918            .bone_corrections
1919            .iter()
1920            .find(|b| b.bone_id == "lumbar_spine")
1921            .unwrap();
1922
1923        assert!(c_yf.observation_confidence > c_ys.observation_confidence);
1924        assert!(c_yf.translation_m[2] > c_ys.translation_m[2]);
1925        // Lower BMD (lower E) yields more to the same observation displacement than stiffer bone
1926        assert!(c_of.bone_stiffness_gpa < c_yf.bone_stiffness_gpa);
1927        assert!(c_of.translation_m[2] > c_yf.translation_m[2]);
1928        assert!(c_yf.jacobian_det > 0.0 && c_of.jacobian_det > 0.0);
1929    }
1930
1931    #[test]
1932    fn stage3_harmonic_tps_preserves_affine_and_positive_jacobian_det() {
1933        let cage = [
1934            [-0.2, 0.8, -0.15],
1935            [0.2, 0.8, -0.15],
1936            [-0.2, 1.4, -0.15],
1937            [0.2, 1.4, -0.15],
1938            [-0.2, 0.8, 0.15],
1939            [0.2, 0.8, 0.15],
1940            [-0.2, 1.4, 0.15],
1941            [0.2, 1.4, 0.15],
1942        ];
1943        // Pure anisotropic affine scaling (1.15, 1.10, 1.25) -> det = 1.58125
1944        let displaced_affine: Vec<[f64; 3]> = cage
1945            .iter()
1946            .map(|p| [p[0] * 1.15, p[1] * 1.10, p[2] * 1.25 + 0.02])
1947            .collect();
1948        let (pt, det) = harmonic_tps_organ_transfer(&cage, &displaced_affine, [0.04, 1.15, 0.03]);
1949        assert!((pt[0] - 0.04 * 1.15).abs() < 1e-6);
1950        assert!((pt[1] - 1.15 * 1.10).abs() < 1e-6);
1951        assert!((pt[2] - (0.03 * 1.25 + 0.02)).abs() < 1e-6);
1952        assert!((det - (1.15 * 1.10 * 1.25)).abs() < 1e-5, "det={det}");
1953
1954        // Extreme inverted cage must still preserve det(J) > 0 (no organ cavity foldover)
1955        let displaced_inverted: Vec<[f64; 3]> = cage
1956            .iter()
1957            .map(|p| [-p[0] * 2.0, p[1], -p[2] * 2.0])
1958            .collect();
1959        let (safe_pt, safe_det) =
1960            harmonic_tps_organ_transfer(&cage, &displaced_inverted, [0.02, 1.10, 0.02]);
1961        assert!(safe_pt.iter().all(|v| v.is_finite()));
1962        assert!(safe_det > 0.0, "Jacobian det must stay > 0, got {safe_det}");
1963
1964        // Full 3-stage pipeline preserves det(J) > 0 across all internal organ cavities
1965        let mut c = BodyConstitution::default();
1966        c.characteristics.karyotype = Some(Karyotype::Xx);
1967        c.measurements.stature_mm = Some(1700);
1968        c.measurements.chest_mm = Some(980);
1969        c.measurements.waist_mm = Some(860);
1970        c.measurements.hip_mm = Some(1080);
1971        c.attributes.pregnancy = Some(Trimester::Third);
1972        let full = c.derive_anatomical_calibration(None, &[]);
1973        assert!(!full.organ_transfers.is_empty());
1974        for t in &full.organ_transfers {
1975            assert!(
1976                t.jacobian_det > 0.0,
1977                "organ {} had non-positive det(J)={}",
1978                t.organ_id,
1979                t.jacobian_det
1980            );
1981            assert!(t.calibrated_point_m.iter().all(|v| v.is_finite()));
1982        }
1983    }
1984
1985    #[test]
1986    fn ethnicity_does_not_alter_3stage_calibration_geometry() {
1987        let mut with_eth = BodyConstitution::default();
1988        with_eth.measurements.stature_mm = Some(1740);
1989        with_eth.measurements.waist_mm = Some(810);
1990        with_eth
1991            .knowledge
1992            .ethnicities
1993            .push(super::super::knowledge_context::EthnicityAffiliation::declared("Greek").unwrap());
1994
1995        let mut without_eth = BodyConstitution::default();
1996        without_eth.measurements.stature_mm = Some(1740);
1997        without_eth.measurements.waist_mm = Some(810);
1998
1999        let a = with_eth.derive_anatomical_calibration(None, &[]);
2000        let b = without_eth.derive_anatomical_calibration(None, &[]);
2001        assert_eq!(a.bone_scalings, b.bone_scalings);
2002        assert_eq!(a.organ_transfers, b.organ_transfers);
2003    }
2004}